{"title":"Eight million pixels and counting","link":[{"@attributes":{"href":"https:\/\/nical.github.io\/","rel":"alternate"}},{"@attributes":{"href":"https:\/\/nical.github.io\/feeds\/all.atom.xml","rel":"self"}}],"id":"https:\/\/nical.github.io\/","updated":"2023-04-06T00:00:00+02:00","entry":[{"title":"Custom allocators in Rust","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/rust-custom-allocators.html","rel":"alternate"}},"published":"2023-04-06T00:00:00+02:00","updated":"2023-04-06T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2023-04-06:\/posts\/rust-custom-allocators.html","summary":"<p>Lately I have been looking into custom allocators in the Rust. Recent internet chatter about <a href=\"https:\/\/ziglang.org\/\">the Zig programming language<\/a> has brought allocators back to my attention, but custom allocators are an old topic. I remember playing with that a long while back in my C++ days after watching <a href=\"https:\/\/www.youtube.com\/watch?v=LIb3L4vKZ7U&amp;t=21s\">a talk \u2026<\/a><\/p>","content":"<p>Lately I have been looking into custom allocators in the Rust. Recent internet chatter about <a href=\"https:\/\/ziglang.org\/\">the Zig programming language<\/a> has brought allocators back to my attention, but custom allocators are an old topic. I remember playing with that a long while back in my C++ days after watching <a href=\"https:\/\/www.youtube.com\/watch?v=LIb3L4vKZ7U&amp;t=21s\">a talk by Andrei Alexandrescu<\/a>. I found it a satisfying thing to hack on because you can start off with simple things that work quickly, build them out of composable parts and of course the rabbit hole is deep enough that after spending a lot of time you get to feel great about pulling advanced stunts. That said, I'm already digressing. I am not going to write about building memory allocators today, just about writing data structures that can accept different allocators. This isn't about replacing the global allocator either, mind you, but making it possible for different parts of a program to chose their memory allocation strategies. I'll first superficially ramble a bit about the the motivation and state of affairs in the Rust ecosystem, then I'll go over an experiment I made to integrate custom allocators in <a href=\"https:\/\/crates.io\/crates\/lyon\">lyon<\/a>'s tessellator in a few different ways.<\/p>\n<h1>The ubiquitous global allocator<\/h1>\n<p>I've long had a mild dislike for the \"one and only global allocator\" strategy. It's a pretty simple and decent default, to a point that a lot of programmers forgot that there are alternative ways to work with memory. I look at performance profiles a lot at work and allocation\/deallocation is at the same time always prominent and also kind of elusive. It is hard to distill down simple benchmarks for allocation overhead, because of much of that overhead comes from cache misses and contention between multiple threads using the same allocator.<\/p>\n<p>To mitigate allocation performance issues, it is very common to build algorithms in ways that allow keeping the data structures that hold intermediate state around. This way subsequent runs can reuse the allocations from the previous ones. <a href=\"https:\/\/crates.io\/crates\/lyon\">lyon<\/a>'s tessellator is written like that for example. In <a href=\"https:\/\/github.com\/servo\/webrender\">WebRender<\/a> we also try to keep temporary allocations around. I'll refer to this approach as \"recycling allocations\" and it is basically about accepting that interacting with allocators is slow and making contraptions to avoid it.<\/p>\n<p>Another option is to take a step back and think a bit about whether memory allocations really need to be slow. What are the different allocation patterns? Are they all best served by a general purpose allocator? Bump allocators are very good at providing very fast short-lived allocations. They also can work very well with groups of allocations with a common and well defined scope, for example a frame in a video game or a graphics rendering engine. Most allocations stay in the thread they are created with. Using a simpler thread-local allocator wherever it makes sense can provides some wins.\nOf course there are also long-lived allocations with mostly unpredictable lifetimes backing resources that may or may not move to different threads. These are well served by a global allocator, are they the majority of allocations in majority of programs? I don't think so and I'm not the only one. Some languages (Zig, Jai and others) have made that it a pillar of their library design to make it possible and convenient to pick the right allocation strategy everywhere allocation needs to happen.<\/p>\n<p>Using custom allocators to avoid paying the cost of memory allocations for temporary data sounds like more work than recycling for about the same benefits, but the benefits can go beyond merely skipping the allocator overhead. When keeping around an allocation for later use, we take memory that is nice and warm in the cache hierarchy after its use and enforce that only future uses of this specific code will be able to use it again. Something else that runs immediately after could have benefited from that memory for its own temporary allocations, but it will have to reach for other pieces of memory that may not be as readily available.\nWhen running on a tight memory budgets, hoarding temporary data structures can also occupy precious resources.<\/p>\n<p>Of course all of these advantages require understanding allocation lifetime patterns and picking the right strategy for the each part of the code. It's not like slapping a bump allocator under an algorithm will always make it faster. That algorithm could be made slower if the underlying allocator is fast but fails to reuse memory that is warm in CPU caches. It's an extra mental load for the programmer for sure and it may not be the right amount of effort for everyone. Whether or not this option is good for everyone, I think that we will be in a good place when that option is easily reachable.<\/p>\n<h1>Custom allocators and Rust<\/h1>\n<p>Rust, like most languages chose to start with the stance that most people should not have to think about how memory allocation is happening. All allocations go through a default general-purpose global allocator. The good news is that the standard library provisioned for evolving into eventually letting you opt into custom allocators.<\/p>\n<p>There are two proposals for adding\/exposing support for custom memory allocators. The one I am most interested in is the <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/32838\">allocator-api<\/a> feature which can be used with nightly versions of rustc today. The <a href=\"https:\/\/crates.io\/crates\/allocator-api2\">allocator-api2 crate<\/a> can be used as a polyfill on stable Rust while waiting for the feature to be stabilized.\nThere is also the <a href=\"https:\/\/github.com\/rust-lang\/wg-allocators\/issues\/93\">storage proposal<\/a> which aims to provide, a superset of <code>allocator-api<\/code>'s features, mainly to be able to express things like <code>SmallVec<\/code> directly in the <code>Vec<\/code> type using a custom storage.<\/p>\n<p>In a nutshell, the main conceptual differences between the two proposals are:<\/p>\n<ul>\n<li><code>allocator-api<\/code> adds a fairly straightforward <code>Allocator<\/code> trait with methods for allocating, deallocating and reallocating memory. You ask that trait to allocate memory and it gives you a pointer.<\/li>\n<li>The <code>storage<\/code> proposal instead wants to replace the pointer, so that it can express inline allocations (that can be moved along with the data structure).<\/li>\n<\/ul>\n<p>In my humble opinion I prefer the <code>allocator-api<\/code> proposal, because it is much simpler while covering the majority of the important features. I understand the appeal of a more general solution, but the added features don't quite pull the weight of the extra complexity for me. <code>SmallVec<\/code> (and equivalents for other data structures) can be a separate implementation, it does not <em>need<\/em> to be unified into <code>Vec<\/code>. Of course, that's a very personal view, I don't think I'm going to sway anyone that's already emotionally invested in the debate with this argument, and that's not the aim of this blog post.<\/p>\n<h1>Allowing custom allocators in a Rust data structure.<\/h1>\n<p>Apologies for the overlong preamble, here comes the part that this post is really about.<\/p>\n<p>There are a few different ways to go about making data structures accept custom allocators in rust. In this post I am focusing on the particular case of temporary data structures. The stuff that is tied to the internal needs of an algorithm and typically have very short lifetimes. Keep this in mind because the mentioned trade-offs would be different for the longer lived data structures that represent the interesting state of your programs. First I am going to simplify the problem down to an imaginary <code>Tessellator<\/code> struct containing a single vector so that the code snippets remain approachable. I leave extrapolating to a more realistic\/complex case as an exercise to the reader (or if you feel adventurous, go through the branches in lyon's repository that are linked later in the post). Then I'll briefly expand on how various approaches played out with <a href=\"https:\/\/crates.io\/crates\/lyon\">lyon<\/a>'s fill tessellator.<\/p>\n<h3>Hard coded custom allocator<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">u32<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">CustomAllocator<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This is as simple as it gets. Not very flexible, sure, but flexibility isn't always the goal. When creating small modular crates it can be hard to pick this approach, but for code that belongs to an application this is typically the most efficient and least amount of work.<\/p>\n<h3>Generic parameter on the data structure<\/h3>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">A<\/span>: <span class=\"nc\">Allocator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Global<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">u32<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">A<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This version is the most flexible: it abstracts over whether the data structure is owned or borrowed, sendable, etc. It takes advantage of the common case where the Allocator type is zero-sized (like <code>Global<\/code>, for example).<\/p>\n<p>I would default to this approach with data structures that are already generic and when I don't want to enforce constraints about things like <code>Send<\/code> and <code>Sync<\/code>.<\/p>\n<p>Adding a generic parameter to a complex structure that otherwise did not have any can be a bummer, though.<\/p>\n<ul>\n<li>It adds noise in the code and documentation.<\/li>\n<li>For something like custom memory allocators that are likely not going to be used by the majority of users of this API, it isn't very satisfying (to me at least) to put this advanced parameter under everyone's nose by making it show at the type level.<\/li>\n<li>For things that contain a large amount of code, it is easy to bloat the binary size by (accidentally) causing multiple instantiations of the entire thing. Not that in this case the power is still in the user's hands, they can decide to always use the same allocator or always use a <code>&amp;dyn Allocator<\/code> as the allocator type.<\/li>\n<\/ul>\n<p>On the performance side the pros and cons are:<\/p>\n<ul>\n<li><strong>pro<\/strong>: sometimes static dispatch produces faster code than dynamic dispatch (the compiler has more information work with after all).<\/li>\n<li><strong>con<\/strong>: sometimes static dispatch produces <em>slower<\/em> code than dynamic dispatch. Yes. Slower code. That's actually the case with lyon's tessellator and the impact in this case is hard to ignore. More on that at the end of the post.<\/li>\n<\/ul>\n<h3>Borrowed trait object<\/h3>\n<p>Static dispatch is not the only way to interact with allocators. Lyon's fill tessellator already treats allocation and deallocation as slow operations, so the overhead of dynamic dispatch should not matter for performance. In this context, solutions that don't involve generics can be appealing.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">u32<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&#39;<\/span><span class=\"na\">a<\/span><span class=\"w\"> <\/span><span class=\"k\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new_in<\/span><span class=\"p\">(<\/span><span class=\"n\">allocator<\/span>: <span class=\"kp\">&amp;<\/span><span class=\"o\">&#39;<\/span><span class=\"na\">a<\/span> <span class=\"nc\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"n\">allocator<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ A good default. The static lifetime is functionally equivalent to not having<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ a lifetime constraint which means the borrow checker will be off our back for<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ objects coming out of this constructor.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Global<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ An alias for the common case can also help making things look a bit simpler for the<\/span>\n<span class=\"c1\">\/\/ common case.<\/span>\n<span class=\"k\">type<\/span> <span class=\"nc\">SimpleTessellator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">;<\/span>\n\n<span class=\"c1\">\/\/ This one can move around freely.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n\n<span class=\"c1\">\/\/ This one is tied to the allocator handle on the stack.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">allocator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">SomeBumpAllocator<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span><span class=\"w\"> <\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">allocator<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>Again, adding a lifetime parameter for purpose of custom allocators may or may not rub you the wrong way, just like the generic parameter of the previous solution. It does bother me a bit in this case, even with the type alias.\nFor the most part I can live with the extra noise of the lifetime parameters in the code, but I care deeply about how public facing APIs are presented to the users, in particular in the generated documentation. Conceptually I would like to have something that looks like <code>Tessellator<\/code> and <code>TessellatorWithAllocator&lt;'alloc&gt;<\/code> where the simple type signature describes the simple common case while the more complicated signature describes a more advanced usage. I could have the complicated <code>TessellatorWithAllocator&lt;'a&gt;<\/code> be the real structure and the simpler <code>Tessellator<\/code> be the alias, but as far as I know rustdoc can only show the methods on the actual struct, so the advanced parameter is forced on the user in a way that I am unhappy with.<\/p>\n<p>Note that since we can default to <code>'static<\/code> (and that works with <code>Global<\/code>), the lifetime does not mean we suddenly made our type difficult to move around, I think that it's pretty neat.<\/p>\n<p>An added constraint of this scheme is that the data structure must decide up front whether it needs to be <code>Send<\/code>. For example the one in the snipped above is not <code>Send<\/code>.<\/p>\n<p>Another important thing to note is that when using a trait object in the allocator field, types like <code>Vec<\/code> and <code>Box<\/code> (that no doubt your complex data structure uses in multiple places) put on some weight (a trait object contains two pointers so 16 bytes on most things Rust runs on these days) compared to <code>Global<\/code>'s zero bytes. Whether that's an issue depends on how many of these find their way into your data structures and how much the performance is sensitive to the size of the structures. It did not make a measurable difference in the context of lyon's fill tessellator.\nThis potential bloat issue assumes your data structure is built upon types like the standard containers which store the allocator, but nothing prevents you from using equivalent containers that do not store the allocator. More on this soon, but first I want to address the extra lifetime parameter issue.<\/p>\n<h3>Using two structures<\/h3>\n<p>The documentation issue I had with the generic and borrowed trait object approaches can be solved by using two structs, one being a thin wrapper around the other. This gives full control over what the doc looks like at the cost of more boilerplate.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">inner<\/span>: <span class=\"nc\">TessellatorWithAllocator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"c1\">\/\/ or<\/span>\n<span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">inner<\/span>: <span class=\"nc\">TessellatorWithAllocator<\/span><span class=\"o\">&lt;<\/span><span class=\"n\">Global<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<h3>Static trait object<\/h3>\n<p>Dynamic dispatch was fine but for some reason you do not want to make the structure parameterized over a lifetime. No problem, you can just force the lifetime to be static:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">u32<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"o\">&gt;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ A good default.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Global<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"sd\">\/\/\/ Using a custom allocator.<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">\/\/\/<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">\/\/\/ Note: Users of this type can decide at their own risk to cast away the static<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">\/\/\/ lifetime. This will not cause problem with this type as long as the provided<\/span>\n<span class=\"w\">    <\/span><span class=\"sd\">\/\/\/ allocator outlives the data structure.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new_in<\/span><span class=\"p\">(<\/span><span class=\"n\">allocator<\/span>: <span class=\"kp\">&amp;<\/span><span class=\"o\">&#39;<\/span><span class=\"nb\">static<\/span> <span class=\"nc\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">data<\/span>: <span class=\"nb\">Vec<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"n\">allocator<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This version is actually a subset of the borrowed trait object restricted to the static lifetime and with nicer syntax (no <code>&lt;'a&gt;<\/code> everywhere).<\/p>\n<p>This one is probably closest to what one would write in languages like C++. The data structure just assumes the allocator will outlive it, and it is up to the user to either use an static allocator, or pretend to using unsafe code to cast away the lifetime while making sure that the allocator outlives the data structure without the compiler's support.<\/p>\n<p>I know many in the Rust community will frown upon this approach, but to be honest I don't think that it is a terrible solution in the context of an advanced feature like custom allocation strategies. <code>Tessellator<\/code> does not expose an unsafe API, but it documents that if its users were to break the rules they'd simply have to make sure the allocator outlives the data structure. In any other language with this kind of control over memory management, this contract would have to be manually upheld by users of the API and it is considered normal.<\/p>\n<h3>Trait objects \u00e0 la Zig<\/h3>\n<p>I wrote earlier about how the extra space occupied by the allocator field in the vectors, boxes and maps that make your data structure may or may not be an issue. What can we do about it? Well, we could use a similar container types that do not store their own allocator. Matklad <a href=\"https:\/\/matklad.github.io\/2023\/03\/26\/zig-and-rust.html\">wrote recently<\/a> about how Zig provides a vector container that takes the allocator as a parameter of all of the methods that may need to allocate or deallocate memory. There are tradeoffs to this approach. In Rust, almost all of these allocating methods have to be marked <code>unsafe<\/code> since memory safety depends on the user correctly passing the same allocator the container was created with. In the context of a larger data structure that's a pretty trivial contract to uphold, the outer data structure would probably just store the allocator at its root and pass it to the internal containers.\nLet's have a look:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">struct<\/span> <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">allocator<\/span>: <span class=\"kp\">&amp;<\/span><span class=\"o\">&#39;<\/span><span class=\"na\">a<\/span> <span class=\"nc\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">data<\/span>: <span class=\"nc\">RawVector<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">u32<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ A good default.<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span>::<span class=\"n\">new_in<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Global<\/span><span class=\"w\"> <\/span><span class=\"k\">as<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;&#39;<\/span><span class=\"nb\">static<\/span><span class=\"w\"> <\/span><span class=\"k\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new_in<\/span><span class=\"p\">(<\/span><span class=\"n\">allocator<\/span>: <span class=\"kp\">&amp;<\/span><span class=\"o\">&#39;<\/span><span class=\"na\">a<\/span> <span class=\"nc\">dyn<\/span><span class=\"w\"> <\/span><span class=\"n\">Allocator<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">Tessellator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">           <\/span><span class=\"n\">data<\/span>: <span class=\"nc\">RawVector<\/span>::<span class=\"n\">with_capacity<\/span><span class=\"p\">(<\/span><span class=\"mi\">128<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">allocator<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">           <\/span><span class=\"n\">allocator<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">impl<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"nb\">Drop<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">Tessellator<\/span><span class=\"o\">&lt;&#39;<\/span><span class=\"na\">a<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">drop<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Don&#39;t forget to free the memory!<\/span>\n<span class=\"w\">        <\/span><span class=\"k\">unsafe<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">data<\/span><span class=\"p\">.<\/span><span class=\"n\">deallocate<\/span><span class=\"p\">(<\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">allocator<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you would like to play with an unsafe manually allocated vector like this, I wrote one in the <a href=\"https:\/\/docs.rs\/shared_vector\/latest\/shared_vector\/struct.RawVector.html\">shared_vector<\/a> crate. This wasn't the initial goal of that crate, but it contains a vector type mostly similar to the standard library's and it was easy for me to refactor it into a <code>RawVector&lt;T&gt;<\/code> that contains most of the code and takes the allocator explicitly on top of which the <code>Vector&lt;T, Allocator&gt;<\/code> type is implemented as a thin wrapper. That code is rather fresh so there may be some bugs but fuzzing isn't finding issues so far.<\/p>\n<h1>Results<\/h1>\n<p>I wanted to experiment with custom allocators in a non-committal way. To do so I tried Some of the approaches I described earlier in lyon's <a href=\"https:\/\/docs.rs\/lyon_tessellation\/latest\/lyon_tessellation\/struct.FillTessellator.html\">fill tessellator<\/a>. It is the perfect size for this experiment: big enough to show how things would play out in a non-trivial chunk of code, but small enough to fit in a manageable amount of time while trying a couple of approaches.<\/p>\n<p>The fill tessellator implements an algorithm that generates a triangle mesh from a vector path (the kind of paths you would find in a <a href=\"https:\/\/developer.mozilla.org\/fr\/docs\/Web\/API\/CanvasRenderingContext2D\">canvas<\/a>-style API or an SVG document). Internally it needs to allocate memory for a lot of different things, which I won't bore you with in this post. As a mentioned earlier, the tessellator is a structure instead of a pure function so that it can retain memory allocations in subsequent uses.<\/p>\n<p>The code for the experiment can be found in the following branches:\n - Generic parameter: <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/alloc-generic\/crates\/tessellation\/src\/fill.rs\">alloc-generic branch<\/a>\n - Borrowed trait object: <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/alloc-trait-object\/crates\/tessellation\/src\/fill.rs\">alloc-trait-object branch<\/a>\n - Zig-style manually managed trait object: <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/alloc-raw\/crates\/tessellation\/src\/fill.rs\">alloc-raw branch<\/a><\/p>\n<p>The most adventurous readers might find the courage to read and compare all of that code, I wouldn't blame you if you don't. Here are my thoughts after this little experiment:<\/p>\n<ul>\n<li>Adding support for custom allocators can be a bit tedious, but it is rather easy.<\/li>\n<li>I believe that the yet-to-be-stabilized <code>Allocator<\/code> trait is the right abstraction.<\/li>\n<li>I had been waiting patiently for the nightly-only <a href=\"https:\/\/github.com\/rust-lang\/rust\/issues\/32838\">allocator-api<\/a> feature to stabilize, but since that's just a library thing anyone can use the stable polyfill from the <a href=\"https:\/\/crates.io\/crates\/allocator-api2\">allocator-api2<\/a> crate today in stable rust. I'm happy I stumbled upon it just in time for this experiment.<\/li>\n<li>The fill tessellator is not just one struct like in the simplified example from earlier there are a number of structs only visible internally. Adding a generic or lifetime parameter to all of them is tedious and adds noise that I am not very pleased with. In an ideal world, adding support for custom allocators to an algorithm is so simple that it becomes an idiomatic thing that crate implementors just do even when they don't necessarily need it, just like implementing the <code>Default<\/code>  trait. In this ideal world there may even be a clippy lint that nudges you towards using custom allocators in some places.<\/li>\n<li>Generalizing to a whole program, If everything that allocates memory needs to have generic or lifetime parameters, it may be too tedious as well, or perhaps I have to get used to reading <code>&lt;things&gt;<\/code> everywhere.<\/li>\n<li>At the API level, I am not super fond of adding a generic or lifetime parameter either for an advanced knob that isn't at the forefront of the tessellator's functionality.<\/li>\n<\/ul>\n<h2>Performance<\/h2>\n<p>I mentioned somewhat surprising performance results for the generic version of the tessellator's allocator parameter. What's up with that?<\/p>\n<p>The tessellator recycles its allocations, so using a faster or slower allocator should only significantly affect the performance the first time the tessellator runs. The repository contains a few benchmarks which reuse the same allocator many times so it would make sense for this experiment to not affect these benchmarks. Yet, I have been bitten in the past by surprising performance difference between static and dynamic dispatch so I made sure to run the benchmarks again as a sanity check. In particular I there was a significant performance increase a few years ago when the tessellator's output parameter was converted from a generic parameter to a trait object (making the tessellator entire free of generic parameters).\nI observed the same effect when comparing the different approaches: Adding a generic parameter for the allocator regresses the benchmarks by a solid 5 to 8 percents. Every other approach performed roughly the same (as expected since allocator performance should not be a factor of these benchmarks).<\/p>\n<p>It's difficult to tell what's going on here. There if a fair amount of code involved, so eyeballing the generated code is too much hassle for me to commit to right now. Hopefully there exists some tools for looking at how compiler optimizations played out at a large-ish scale. I can't make particularly educated guesses here, all I know is that:<\/p>\n<ul>\n<li>The benchmarks use a single instance of the generic parameter, so if bloat is to blame it comes from poor inlining decisions and not multiple generic instantiations.<\/li>\n<li>It doesn't seem to matter what parameter is made generic. Any generic parameter on the tessellator appears to throw a wrench into some heuristics and snowballs into slower code <em>for this particular code<\/em>.<\/li>\n<li>I don't have reasons to believe that this generalizes to other code. All I would gather from that is that contrary to popular belief, static dispatch does not always produce faster code than dynamic dispatch (especially at a larger scale than simple code snippets). If performance matters, don't make assumption, try things, measure and then decide.<\/li>\n<\/ul>\n<p>If you are interested, here are a couple of performance profiles (the link will probably go stale after a while):<\/p>\n<p>Generic allocator parameter: <a href=\"https:\/\/share.firefox.dev\/3ZDHPlr\">(profile link)<\/a><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>test fill_events_01_logo                ... bench:      36,856 ns\/iter (+\/- 6,452)\ntest fill_events_02_logo_pre_flattened  ... bench:      22,195 ns\/iter (+\/- 503)\ntest fill_events_03_logo_with_tess      ... bench:      87,390 ns\/iter (+\/- 1,464)\ntest fill_tess_01_logo                  ... bench:      71,749 ns\/iter (+\/- 1,279)\ntest fill_tess_03_logo_no_intersections ... bench:      82,140 ns\/iter (+\/- 379)\ntest fill_tess_05_logo_no_curve         ... bench:      34,081 ns\/iter (+\/- 857)\ntest fill_tess_06_logo_with_ids         ... bench:      70,721 ns\/iter (+\/- 1,166)```\n<\/code><\/pre><\/div>\n\n<p>Non-generic: <a href=\"https:\/\/share.firefox.dev\/3ZGE136\">(profile link)<\/a><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>test fill_events_01_logo                ... bench:      29,859 ns\/iter (+\/- 835)\ntest fill_events_02_logo_pre_flattened  ... bench:      14,986 ns\/iter (+\/- 437)\ntest fill_events_03_logo_with_tess      ... bench:      72,470 ns\/iter (+\/- 5,095)\ntest fill_tess_01_logo                  ... bench:      56,008 ns\/iter (+\/- 1,347)\ntest fill_tess_03_logo_no_intersections ... bench:      66,380 ns\/iter (+\/- 2,144)\ntest fill_tess_05_logo_no_curve         ... bench:      28,297 ns\/iter (+\/- 171)\ntest fill_tess_06_logo_with_ids         ... bench:      54,785 ns\/iter (+\/- 2,835)\n<\/code><\/pre><\/div>\n\n<h1>Conclusion<\/h1>\n<p>Fast software is written with memory allocations in mind. Recycling allocations is an easy way to paper over allocator overhead but picking the right allocator for specific parts of the code is another option which can be even more effective. Ideally developers would have the possibility to easily reach for both and do what makes most sense in context.<\/p>\n<p>I think that custom allocators are a pretty cool feature for a performance-focused library to add. Very few crates do today, probably in part because the standard library hasn't stabilized custom allocators yet, but also because it is very easy and convenient to not think about it at all. There is certainly a niche to fill in the ecosystem for specialized custom allocators. There is <a href=\"https:\/\/docs.rs\/blink-alloc\/\">blink-alloc<\/a> and probably a few others. As this niche fills up and the the allocator API stabilizes, I hope that more people will join the fun. Will I integrate custom allocators in my own crates? I think so. I still need to ponder some more on the different ways to do it. I don't think that one way is strictly superior to the others. For some things a generic parameter is the obvious choice while for others I find that making an entire chunks of a program generic for the sake of supporting custom allocators is not sustainable. Dynamic dispatch for custom allocators can work well in many cases. In lyon I am leaning towards using a generic parameter in the <code>Path<\/code> data structure and dynamic dispatch in the tessellator.<\/p>\n<p>And there is this thorny generics performance situation, but that's more anecdotal. The point is that making code generic over something can have somewhat unexpected consequence (good or bad) the only right thing to do is to validate assumptions. I still hope that static dispatch can produce faster code more often than not.<\/p>\n<p>Comments\/reactions\/discussions about this post on <a href=\"https:\/\/www.reddit.com\/r\/rust\/comments\/12di5bo\/custom_allocators_in_rust\/\">reddit<\/a><\/p>\n<h1>Post scriptum<\/h1>\n<p>Here are few notes following some of the reddit discussions.<\/p>\n<p>A discussion with one of the storage proposal authors provided me with more context and put the proposal in a better light:<\/p>\n<ul>\n<li>The storage API does not need to be as complicated as the code I read in one of its versions.<\/li>\n<li>Even though there is an unresolved issue with Box coercion, that problem only affects some specific cases. The proposal could be stabilized without necessarily resolving it.<\/li>\n<li>Ideally the  <code>Storage<\/code> and <code>Allocator<\/code> traits would both exist and some <code>Storage<\/code> implementations could leverage <code>Allocator<\/code> ones. <code>Storage<\/code> would mainly allow distinguishing between inline and allocator provided memory.<\/li>\n<\/ul>\n<p>I was also reminded of the <a href=\"https:\/\/crates.io\/crates\/bumpalo\">bumpallo<\/a> crate, which also implements support for the unstable <code>Allocator<\/code> trait. The crate does not rely on <code>allocator-api2<\/code> for polyfilling the <code>Allocator<\/code> trait. This underlines the need for stabilizing the <code>Allocator<\/code> trait to let a healthy ecosystem develop on common foundations.<\/p>\n<p>Another interesting highlight: <a href=\"https:\/\/github.com\/emi2k01\/okaoka\">okaoka<\/a> allows switching between allocators using a hook on the global allocator. It does not provide the type of granularity that I was after, it allows injection a different allocator for third party code that does not provide options. None of the approaches discussed in this post let you do that.<\/p>","category":{"@attributes":{"term":"rust"}}},{"title":"Lyon 1.0","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/lyon-1-0.html","rel":"alternate"}},"published":"2022-07-11T00:00:00+02:00","updated":"2022-07-11T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2022-07-11:\/posts\/lyon-1-0.html","summary":"<p>I am happy to finally announce the symbolic release of <code>lyon 1.0.0<\/code>.<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><code>lyon<\/code><\/a> is a Rust crate providing a number of functionalities related to vector graphics and rendering them using polygon tessellation.\nThe most interesting and complex piece is <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/\"><code>lyon_tessellation<\/code><\/a>'s <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/struct.FillTessellator.html\">fill tessellator<\/a> which produces a triangle mesh \u2026<\/p>","content":"<p>I am happy to finally announce the symbolic release of <code>lyon 1.0.0<\/code>.<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><code>lyon<\/code><\/a> is a Rust crate providing a number of functionalities related to vector graphics and rendering them using polygon tessellation.\nThe most interesting and complex piece is <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/\"><code>lyon_tessellation<\/code><\/a>'s <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/struct.FillTessellator.html\">fill tessellator<\/a> which produces a triangle mesh for any arbitrary vector path including shapes with holes and self-intersections. Some people prefer to only use the <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/\"><code>lyon_geom<\/code><\/a> crate which provides a lot of useful b\u00e9zier curve math, or <a href=\"(https:\/\/docs.rs\/lyon_path\/1.0.0\/lyon_path\/)\"><code>lyon_path<\/code><\/a> for building and iterating vector paths.<\/p>\n<p><img alt=\"The logo\" src=\"https:\/\/nical.github.io\/images\/lyon-logo.svg\"><\/p>\n<p align=\"center\">\n  <a href=\"https:\/\/crates.io\/crates\/lyon\">\n      <img src=\"https:\/\/img.shields.io\/crates\/v\/lyon.svg\" alt=\"crates.io\">\n  <\/a>\n  <a href=\"https:\/\/travis-ci.org\/nical\/lyon\">\n      <img src=\"https:\/\/img.shields.io\/travis\/nical\/lyon\/master.svg\" alt=\"Travis Build Status\">\n  <\/a>\n  <a href=\"https:\/\/docs.rs\/lyon\">\n      <img src=\"https:\/\/docs.rs\/lyon\/badge.svg\" alt=\"documentation\">\n  <\/a>\n<\/p>\n\n<p><code>lyon<\/code> first hit crates.io around mid 2016. There have been quite a few releases since then and the last release with breaking changes before <code>1.0.0<\/code> was in January 2021, so about a year and a half ago at the time of writing. The project is quite stable and I have been happy with the robustness of the tessellator for a while. So why not publish a <code>1.0.0<\/code> sooner?<\/p>\n<p>For a large part I, like many in the Rust ecosystem, have been guilty of a bit of \"<code>1.0<\/code> semver shyness\" there's this irrational fear of marking something <code>1.0<\/code> while it isn't perfect and it's API completely figured out. The reality of software is of course that nothing is ever perfect. The other reason, the more important one, is that I've always wanted this project to grow into a fully featured 2D renderer. It was my goal at the beginning and In the process I found that making a fast and robust tessellator is a project in its own right and I got side-tracked. I think of it as a good thing, I am sure that a decent portion of lyon's users are interested in some of the difficult low level components more than in a fully fledged renderer. I haven't given up on the idea, but realistically it will be far enough in the future that the version number should reflect how I think of the pieces that I have now.<\/p>\n<p>So there you have it. I'm taking this ridiculously tiny psychological leap and incrementing the major version to 1, giving me access to not two but three semver numbers to define versions. There will be a 2.0 eventually, and surely many other major versions after that.<\/p>\n<h1>What's new in 1.0?<\/h1>\n<h2>Variable width strokes<\/h2>\n<p>For this release, I wanted to implement something fun. The <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/struct.StrokeTessellator.html\">stroke tessellator<\/a> lets you specify a line width that is constant over the entire path. What if you wanted the line width to change along the path? In <code>lyon 0.17<\/code> you could approximate this effect by storing a line-width per endpoint using custom attributes and implementing your own <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/geometry_builder\/trait.StrokeGeometryBuilder.html\"><code>StrokeGeometryBuilder<\/code><\/a> or <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/geometry_builder\/trait.StrokeVertexConstructor.html\"><code>StrokeVertexConstructor<\/code><\/a> to move each vertex along its normal.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ lyon 0.17.0<\/span>\n\n<span class=\"c1\">\/\/ We&#39;ll have a custom per-endpoint attribute in our path at index 0 to specify the width.<\/span>\n<span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">STROKE_WIDTH<\/span>: <span class=\"kt\">usize<\/span> <span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">;<\/span>\n\n<span class=\"c1\">\/\/ A custom vertex constructor for collecting the output of the stroke tessellator.<\/span>\n<span class=\"k\">struct<\/span> <span class=\"nc\">VariableWidthStrokeCtor<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">StrokeVertexConstructor<\/span><span class=\"o\">&lt;<\/span><span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">]<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">VariableWidthStrokeCtor<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new_vertex<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">vertex<\/span>: <span class=\"nc\">StrokeVertex<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Grab the width. The tessellator automatically (and lazily) did the work of<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ interpolating the custom attributes<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">interpolated_attributes<\/span><span class=\"p\">()[<\/span><span class=\"n\">STROKE_WIDTH<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Instead of using `vertex.position()` compute the adjusted position manually.<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">position<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">position_on_path<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">+<\/span><span class=\"w\"> <\/span><span class=\"n\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">normal<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"n\">width<\/span><span class=\"w\"> <\/span><span class=\"o\">*<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.5<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">        <\/span><span class=\"n\">position<\/span><span class=\"p\">.<\/span><span class=\"n\">to_array<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ Create a path with one custom attribute per endpoint.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder_width_attributes<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">begin<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">40.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">100.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">5.0<\/span><span class=\"p\">]);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">80.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">20.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">30.0<\/span><span class=\"p\">]);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">cubic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">220.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">150.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">50.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">250.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">100.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">]);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">200.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">50.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">40.0<\/span><span class=\"p\">]);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">end<\/span><span class=\"p\">(<\/span><span class=\"kc\">false<\/span><span class=\"p\">);<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">path<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">();<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span>: <span class=\"nc\">VertexBuffers<\/span><span class=\"o\">&lt;<\/span><span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"kt\">u16<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">VertexBuffers<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">stroke_tessellator<\/span><span class=\"p\">.<\/span><span class=\"n\">tessellate_path<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">path<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">StrokeOptions<\/span>::<span class=\"n\">tolerance<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">).<\/span><span class=\"n\">with_line_caps<\/span><span class=\"p\">(<\/span><span class=\"n\">LineCap<\/span>::<span class=\"n\">Round<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">BuffersBuilder<\/span>::<span class=\"n\">new<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">VariableWidthStrokeCtor<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>Rendering the tessellated geometry of this example would look like:<\/p>\n<p><img alt=\"The logo\" src=\"https:\/\/nical.github.io\/images\/variable-width-stroke\/lyon-0-17.png\"><\/p>\n<p>It works, kind of. See how the joins and caps don't look quite right? I would expect the outline to have a smoother curvature where the edges meet joins and caps like in the image below which was produced using <code>lyon 1.0<\/code>'s built-in support for variable line width. <\/p>\n<p><img alt=\"The logo\" src=\"https:\/\/nical.github.io\/images\/variable-width-stroke\/lyon-1-0.png\"><\/p>\n<p>Implementing this feature required a bit of high school trigonometry and a full rewrite of the stroke tessellator.<\/p>\n<p>Some of the APIs have changed a bit so here is the equivalent code for <code>lyon 1.0<\/code>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ lyon 1.0.0<\/span>\n\n<span class=\"c1\">\/\/ We&#39;ll have a custom per-endpoint attribute in our path at index 0 to specify the width.<\/span>\n<span class=\"k\">const<\/span><span class=\"w\"> <\/span><span class=\"n\">STROKE_WIDTH<\/span>: <span class=\"nc\">AttributeIndex<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mi\">0<\/span><span class=\"p\">;<\/span>\n\n<span class=\"c1\">\/\/ We don&#39;t really need a custom constructor now that we only output the vertex position but<\/span>\n<span class=\"c1\">\/\/ let&#39;s make one for the sake of completeness.<\/span>\n<span class=\"k\">struct<\/span> <span class=\"nc\">VariableWidthStrokeCtor<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">StrokeVertexConstructor<\/span><span class=\"o\">&lt;<\/span><span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">]<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">VariableWidthStrokeCtor<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">new_vertex<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">vertex<\/span>: <span class=\"nc\">StrokeVertex<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">Point<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">position<\/span><span class=\"p\">().<\/span><span class=\"n\">to_array<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ [...]<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span>: <span class=\"nc\">VertexBuffers<\/span><span class=\"o\">&lt;<\/span><span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"kt\">u16<\/span><span class=\"o\">&gt;<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">VertexBuffers<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">stroke_tessellator<\/span><span class=\"p\">.<\/span><span class=\"n\">tessellate_path<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">path<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">StrokeOptions<\/span>::<span class=\"n\">tolerance<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">.<\/span><span class=\"n\">with_line_caps<\/span><span class=\"p\">(<\/span><span class=\"n\">LineCap<\/span>::<span class=\"n\">Round<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">.<\/span><span class=\"n\">with_variable_line_width<\/span><span class=\"p\">(<\/span><span class=\"n\">STROKE_WIDTH<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">BuffersBuilder<\/span>::<span class=\"n\">new<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">VariableWidthStrokeCtor<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">),<\/span>\n<span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>That said, there is an important shortcoming to this approach to variable line widths. The line width is interpolated very naively, using the b\u00e9zier curve <code>t<\/code> parameter. This means that the interpolation will tend to vary more rapidly along curvier parts of the curve than around the more flat parts.<\/p>\n<p>But hey, it's still fun to play with, I hope it will be useful to some and I'll work towards the next iteration based on the feedback I receive. Having the option to interpolate attributes linearly (based on distance instead of the curve parameter) could be a pretty nice feature for <code>lyon 2.0<\/code> or some other future release if there is interest for it, just like a more \"serious\" curve offsetting algorithm.<\/p>\n<h2>The path sampler in lyon_algorithms<\/h2>\n<p>Shout out to <a href=\"https:\/\/github.com\/Mivik\">@Mivik<\/a> for proposing and implementing this new feature. In previous versions of <code>lyon<\/code>, if you wanted to find a point at a certain distance along a path or sample positions at fixed intervals along a path, you could use the <a href=\"https:\/\/docs.rs\/lyon_algorithms\/1.0.0\/lyon_algorithms\/walk\/index.html\"><code>PathWalker<\/code><\/a> which goes through the path and fires callbacks at certain distances. Each time a path is walked the algorithm starts from the beginning. If you want to place many points along a path once it is great, however if you need to do thousands of randomly ordered queries on a very large path, this approach is inefficient.<\/p>\n<p>The idea behind path sampling is to create an acceleration data structure, called <a href=\"https:\/\/docs.rs\/lyon_algorithms\/1.0.0\/lyon_algorithms\/measure\/struct.PathMeasurements.html\"><code>PathMeasurements<\/code><\/a>, the creation of which has an important up-front cost (in the same ballpark as walking the path from the beginning to the end), but allows subsequent queries to be much faster than walking the path.<\/p>\n<p>As a bonus the path sampler can be configured to either sample at certain distances along the path, or sample at <em>normalized<\/em> distances (between zero and one where one means the end of the path).<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ PathMeasurements is expensive to build but easy to cache and allows the rest to be quite fast.<\/span>\n<span class=\"c1\">\/\/ It is immutable so it could even be used concurrently on multiple threads.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">measurements<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">PathMeasurements<\/span>::<span class=\"n\">from_path<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">path<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">tolerance<\/span><span class=\"p\">);<\/span>\n<span class=\"c1\">\/\/ PathSampler is a bit more temporary in the sense that it has a lifetime and has some mutable state.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">sampler<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">measurements<\/span><span class=\"p\">.<\/span><span class=\"n\">create_sampler<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">path<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">SampleType<\/span>::<span class=\"n\">Normalized<\/span><span class=\"p\">);<\/span>\n<span class=\"c1\">\/\/ Let&#39;s build a path as a sub-range of the original one:<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">sampler<\/span><span class=\"p\">.<\/span><span class=\"n\">split_range<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.<\/span><span class=\"mi\">5<\/span><span class=\"o\">..<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">);<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">second_half<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">();<\/span>\n<span class=\"c1\">\/\/ And, of course, we can sample the path.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">sample<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">sampler<\/span><span class=\"p\">.<\/span><span class=\"n\">sample<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.5<\/span><span class=\"p\">);<\/span>\n<span class=\"fm\">println!<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;mid-point: {:?}, {:?}, {:?}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">sample<\/span><span class=\"p\">.<\/span><span class=\"n\">position<\/span><span class=\"p\">(),<\/span><span class=\"w\"> <\/span><span class=\"n\">sample<\/span><span class=\"p\">.<\/span><span class=\"n\">tangent<\/span><span class=\"p\">(),<\/span><span class=\"w\"> <\/span><span class=\"n\">sample<\/span><span class=\"p\">.<\/span><span class=\"n\">attributes<\/span><span class=\"p\">());<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Lots of new goodies in lyon_geom<\/h2>\n<p>In no particular order:<\/p>\n<ul>\n<li>Helpers to modify <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.QuadraticBezierSegment.html#method.drag\">quadratic<\/a> and <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.CubicBezierSegment.html#method.drag\">cubic<\/a> b\u00e9zier curves by dragging any point on the curve.<\/li>\n<li>Faster and more precise b\u00e9zier curve <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.QuadraticBezierSegment.html#method.length\">length<\/a> computation (once again implementing <a href=\"https:\/\/raphlinus.github.io\/curves\/2018\/12\/28\/bezier-arclength.html\">Raph Levien's fantastic research work<\/a>).<\/li>\n<li>A few helpers to split b\u00e9zier curves into <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.QuadraticBezierSegment.html#method.for_each_x_monotonic\">x<\/a> and <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/quadratic_bezier\/struct.QuadraticBezierSegment.html#method.for_each_y_monotonic\">y<\/a>-monotonic sub-curves.<\/li>\n<li>Added <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.LineSegment.html#method.closest_point\"><code>LineSegment::closest_point<\/code><\/a>\/<a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.LineSegment.html#method.distance_to_point\"><code>distance_to_point<\/code><\/a>.<\/li>\n<li>Added <a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.QuadraticBezierSegment.html#method.closest_point\"><code>QuadraticBezierSegment::closest_point<\/code><\/a>\/<a href=\"https:\/\/docs.rs\/lyon_geom\/1.0.0\/lyon_geom\/struct.QuadraticBezierSegment.html#method.distance_to_point\"><code>distance_to_point<\/code><\/a>.<\/li>\n<\/ul>\n<h2>Miscellaneous other new features<\/h2>\n<ul>\n<li>A <a href=\"https:\/\/docs.rs\/lyon_tessellation\/1.0.0\/lyon_tessellation\/struct.BuffersBuilder.html#method.with_inverted_winding\">helper<\/a> to invert the triangle winding produced by the tessellators.<\/li>\n<li>A <a href=\"https:\/\/docs.rs\/lyon_algorithms\/1.0.0\/lyon_algorithms\/rect\/fn.to_axis_aligned_rectangle.html\">function<\/a> to determine whether a path is shaped like an axis aligned rectangle.<\/li>\n<li><a href=\"https:\/\/docs.rs\/lyon_path\/1.0.0\/lyon_path\/struct.Path.html#method.reversed\"><code>Path::reversed<\/code><\/a> is now implemented as an iterator.<\/li>\n<\/ul>\n<h1>Notable API changes<\/h1>\n<p>The rest of this post goes into some API details. It is probably not a particularly fun read unless you are using some of <code>lyon<\/code>'s advanced features. You have been warned.<\/p>\n<h2>The PathBuilder API now includes custom attributes.<\/h2>\n<p>I did my best to avoid changing the whole API with this one, so it will hopefully not affect most users, unless they use or implement the <code>PathBuilder<\/code> trait manually.<\/p>\n<p>So what are custom attributes anyway? Custom attributes, also called \"interpolated attributes\" in some places, are a fixed number of <code>f32<\/code> values that can optionally associated with each endpoint in a path. They can be used to represent various things, such as our varying line width example above, colors, or whatever can be linearly interpolated between endpoints. The fill and stroke tessellators provide access to them when creating vertices and lazily interpolate them if needed for vertices that are along a curve or at the intersection between edges.<\/p>\n<p>One of my motivations with <code>lyon 1.0<\/code> was to get custom attributes better integrated with the various path manipulation abstractions and adapters. If a path data structure implements the <code>PathBuilder<\/code> trait, it automatically gets access to some generic functionalities such as flattening curves into line segments, applying transforms and other goodies. Before 1.0 <code>PathBuilder<\/code> methods used to not take custom attributes, so all of the generic adapters were only available to paths without attributes.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ With lyon 0.17:<\/span>\n\n<span class=\"c1\">\/\/ This worked. `transformed` is provided by the `PathBuilder` trait.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">.<\/span><span class=\"n\">transformed<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Rotation<\/span>::<span class=\"n\">radians<\/span><span class=\"p\">(<\/span><span class=\"n\">PI<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">));<\/span>\n\n<span class=\"c1\">\/\/ This did not. The builder with attributes didn&#39;t implement `PathBuilder`.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder_with_attributes<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">.<\/span><span class=\"n\">transformed<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Rotation<\/span>::<span class=\"n\">radians<\/span><span class=\"p\">(<\/span><span class=\"n\">PI<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">));<\/span>\n<\/code><\/pre><\/div>\n\n<p>In <code>lyon 1.0<\/code> the <a href=\"https:\/\/docs.rs\/lyon_path\/1.0.0\/lyon_path\/builder\/trait.PathBuilder.html\"><code>PathBuilder<\/code> trait<\/a> takes custom attributes so that the generic adapters can take, forward or even modify them as needed. Paths that don't accept custom attributes can still implement the <code>PathBuilder<\/code> trait and simply discard the attributes or assert that they are empty.<\/p>\n<p>To avoid the need to explicitly pass empty attributes (<code>&amp;[]<\/code> or <code>NO_ATTRIBUTES<\/code>) everywhere when they aren't needed, there is a <code>NoAttributes&lt;Builder&gt;<\/code> adapter that exposes the <code>PathBuilder<\/code> methods without the attributes parameter.<\/p>\n<p>As a result:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ With lyon 1.0:<\/span>\n\n<span class=\"c1\">\/\/ This still works. The type of builder is `NoAttributes&lt;Transformed&lt;BuilderImpl&gt;&gt;`.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">.<\/span><span class=\"n\">transformed<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Rotation<\/span>::<span class=\"n\">radians<\/span><span class=\"p\">(<\/span><span class=\"n\">PI<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">));<\/span>\n\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">begin<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">end<\/span><span class=\"p\">(<\/span><span class=\"kc\">false<\/span><span class=\"p\">);<\/span>\n\n\n<span class=\"c1\">\/\/ This works now. The type of builder_2 is `Transformed&lt;BuilderWithAttributes&gt;`.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder_with_attributes<\/span><span class=\"p\">(<\/span><span class=\"mi\">3<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">.<\/span><span class=\"n\">transformed<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">Rotation<\/span>::<span class=\"n\">radians<\/span><span class=\"p\">(<\/span><span class=\"n\">PI<\/span><span class=\"w\"> <\/span><span class=\"o\">\/<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">));<\/span>\n\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">begin<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">3.0<\/span><span class=\"p\">];<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">4.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">5.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">6.0<\/span><span class=\"p\">];<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">end<\/span><span class=\"p\">(<\/span><span class=\"kc\">false<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>In addition, some algorithms built on top of <code>PathBuilder<\/code> such as the path walker got support for custom attributes.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">dots<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"nb\">Vec<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">walker<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">PathWalker<\/span>::<span class=\"n\">new<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">RegularPattern<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">callback<\/span>: <span class=\"kp\">&amp;<\/span><span class=\"nc\">mut<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"n\">event<\/span>: <span class=\"nc\">WalkerEvent<\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">r<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"p\">.<\/span><span class=\"n\">attributes<\/span><span class=\"p\">[<\/span><span class=\"mi\">0<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">g<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"p\">.<\/span><span class=\"n\">attributes<\/span><span class=\"p\">[<\/span><span class=\"mi\">1<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"p\">.<\/span><span class=\"n\">attributes<\/span><span class=\"p\">[<\/span><span class=\"mi\">2<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">        <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"p\">.<\/span><span class=\"n\">attributes<\/span><span class=\"p\">[<\/span><span class=\"mi\">3<\/span><span class=\"p\">];<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">dots<\/span><span class=\"p\">.<\/span><span class=\"n\">push<\/span><span class=\"p\">(<\/span><span class=\"n\">Dot<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">position<\/span>: <span class=\"nc\">event<\/span><span class=\"p\">.<\/span><span class=\"n\">position<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">r<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">g<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">b<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">a<\/span><span class=\"w\"> <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">        <\/span><span class=\"kc\">true<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ Return true to continue walking along the path.<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">},<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Invoke the callback above at a regular interval of 3 units.<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">interval<\/span>: <span class=\"mf\">3.0<\/span><span class=\"p\">,<\/span>\n<span class=\"p\">});<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">red<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">];<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">blue<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"p\">[<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">];<\/span>\n<span class=\"c1\">\/\/ Start with some red dots...<\/span>\n<span class=\"n\">walker<\/span><span class=\"p\">.<\/span><span class=\"n\">begin<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">red<\/span><span class=\"p\">);<\/span>\n<span class=\"c1\">\/\/ And end with blue ones. The dots in between will be have their color<\/span>\n<span class=\"c1\">\/\/ automatically interpolated between red and blue.<\/span>\n<span class=\"n\">walker<\/span><span class=\"p\">.<\/span><span class=\"n\">quadratic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">50.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">blue<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">walker<\/span><span class=\"p\">.<\/span><span class=\"n\">end<\/span><span class=\"p\">(<\/span><span class=\"kc\">false<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<h2>New SVG path syntax parser<\/h2>\n<p>The SVG path syntax parser which was optionally available in the <code>lyon_svg<\/code> crate was re-implemented in the <code>lyon_extra<\/code> crate. The <a href=\"https:\/\/docs.rs\/lyon_extra\/1.0.0\/lyon_extra\/parser\/struct.PathParser.html\">new parser<\/a> supports a superset of the SVG path syntax in order to support specifying custom attributes. The syntax is the same with one exception: after each endpoint the following sequence of N numbers are parsed as the attributes of the endpoint.<\/p>\n<p>For example with two custom attributes, <code>M 0 0 1 2 Q 10 0 11 5 3 4<\/code> is equivalent to the standard SVG path <code>M 0 0 Q 10 0 11 5<\/code> where the endpoint at position <code>(0, 0)<\/code> has attributes <code>[1, 2]<\/code> and the endpoint <code>(11, 5)<\/code> has attributes <code>[3, 4]<\/code>. Note that control points cannot have custom attributes.<\/p>\n<p>You can give it a try in the command line app in the <code>cli<\/code> folder of the repository:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\"># Display a stroked path with a single custom attribute (attribute index 0) interpreted as the variable line width multiplier.<\/span>\ncargo<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>--<span class=\"w\"> <\/span>show<span class=\"w\"> <\/span><span class=\"s2\">&quot;M 40 100 5 80 20 30 C 100 220 150 50 250 100 2 L 200 50 40&quot;<\/span><span class=\"w\"> <\/span>-s<span class=\"w\"> <\/span>--line-cap<span class=\"w\"> <\/span>Round<span class=\"w\"> <\/span>--line-join<span class=\"w\"> <\/span>Round<span class=\"w\"> <\/span>--custom-attributes<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"w\"> <\/span>--variable-line-width<span class=\"w\"> <\/span><span class=\"m\">0<\/span>\n<\/code><\/pre><\/div>\n\n<h2>Side::Left\/Right renamed into Side::Positive\/Negative.<\/h2>\n<p>This change was pretty significant internally, but will only affect users of <code>StrokeVertex::side<\/code>.<\/p>\n<p>This enum is used to indicate on which side a point is along a stroked path. The side is determined using the sign of the cross product between and edge's tangent and a vector between the edge and the point in consideration. If the cross product is positive, we are on the left side... wait is it the right side? Well it depends on whether your y axis points up or down. Lyon's tessellators don't know or need to know about that. A possibility could have been to standardize on the y-down convention like most vector graphics packages, but it was a source of confusion and bugs. The new terminology, while less evocative, is unambiguous and less error prone. As a bonus <code>lyon_tessellation<\/code> doesn't get dictate or contradict its users conception of what is up and down which I think is a good thing.<\/p>\n<h1>Spring cleaning<\/h1>\n<p>In this release I removed a number of redundant or half-baked features that I felt was either not needed anymore, or wouldn't receive proper attention:<\/p>\n<ul>\n<li>Bindings for the libtess2 tessellator (The <code>lyon_tess2<\/code> crate) which could be enabled with the <code>tess2<\/code> cargo feature and provide an alternative tessellator. I originally maintained a wrapper in order to have something to compare lyon against and as an alternative for users running into issues. Since then the fill tessellator has matured enough that I don't think keeping the libtess2 alternative is worth the effort anymore.<\/li>\n<li>The path splitter, which was fun but buggy. I never had the time\/energy\/motivation to grow into a robust implementation.<\/li>\n<li>The <code>Monotonic&lt;T&gt;<\/code> wrapper in <code>lyon_geom<\/code>.<\/li>\n<li>The <code>lyon_svg<\/code> crate (the path parser moved to <code>lyon_extra<\/code>).<\/li>\n<li><code>lyon_extra<\/code> had a buggy software rasterizer that I had intended to use for testing but never got to working properly.<\/li>\n<\/ul>\n<p>I suspect that most of the removed features had little to no users. If you depended on one of them, I suggest copying their implementation from <code>lyon 0.17<\/code> in your code.<\/p>\n<p>These removals relieve some maintenance burden and bring the whole package to a more consistent level of quality and robustness. Some of the half-baked parts contributed to my mental block around calling it a <code>1.0<\/code>.<\/p>\n<h1>Wrapping up<\/h1>\n<p><code>lyon 1.0.0<\/code> wasn't as big a release as, say, <code>0.15.0<\/code> in which the fill tessellator was rewritten. It isn't the end of a cycle nor the beginning of one, it is simply time to do a bit of cleanup and mark the symbolic <code>1.0<\/code> to reflect that the project is fairly stable.<\/p>\n<p>I did rewrite the stroke tessellator to introduce the fancy variable width feature. It was not a major effort because the stroke tessellator is a fairly simple algorithm, but it means there's realistically a higher risk of finding some new bugs there. I encourage you all to report any issue you run into and I will do my best to fix them quickly.<\/p>\n<p>There are a number of lyon-related things I would like to do next, some of which are venturing away from tessellated triangle meshes. I don't want to tease them out too soon as it may be a while before I get them into a workable state. Stay tuned!<\/p>\n<p>This symbolic milestone is as good a time as any to thank all of the people who contributed in small or in big ways to the project. So in chronological order, many thanks to:<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/UrbanSolution\/\">Thomas (@UrbanSolution)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/RazrFalcon\">Evgeniy Reizner (@RazrFalcon)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/o0Ignition0o\">Jeremy Lempereur (@o0Ignition0o)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/emilio\">Emilio Cobos \u00c1lvarez (@emilio)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/icefoxen\">@icefoxen<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/jaemk\">James Kominick (@jaemk)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/dowoncha\">@dowoncha<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/nivkner\">@nivkner<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/kuxv\">@kuxv<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/kaedroho\">Karl Hobley (@kaedroho)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/Noxivs\">@Noxivs<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/anna-liao\">Anna Liao (@anna-liao)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/EloD10\">@EloD10<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/pizzaiter\">@pizzaiter<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/whmountains\">Caleb Whiting (@whmountains)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/bostelk\">Kyle Bostelmann (@bostelk)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/orhanbalci\">Orhan Balci (@orhanbalci)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/zen3ger\">Roland Kovacs (@zen3ger)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/SilentByte\">Rico A. Beti (@SilentByte)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/msiglreith\">@msiglreith<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/kleintom\">Tom Klein (@kleintom)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/gralpli\">@gralpli<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/SimonSapin\">Simon Sapin (@SimonSapin)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/hardiesoft\">Jon Hardie (@hardiesoft)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/Dollab\">Bastien (@Dollab)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/artursapek\">Artur Sapek (@artursapek)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/HalfVoxel\">Aron Granberg (@HalfVoxel)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/bnjbvr\">Benjamin Bouvier (@bnjbvr)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/mr1sunshine\">Aleksandr Ovchinnikov (@mr1sunshine)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/tronical\">Simon Hausmann (@tronical)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/yutannihilation\">Hiroaki Yutani (@yutannihilation)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/carrascomj\">Jorge Carrasco (@carrascomj)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/martinfrances107\">Martin Frances (@martinfrances107)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/adrian17\">Adrian Wielgosik (@adrian17)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/ognarb\">Carl Schwan (@ognarb)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/eduardosm\">Eduardo S\u00e1nchez Mu\u00f1oz (@eduardosm)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/halzy\">Benjamin Halsted (@halzy)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/Herschel\">Mike Welsh (@Herschel)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/simensgreen\">simens (@simensgreen)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/LU15W1R7H\">Luis Wirth (@LU15W1R7H)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/foobar27\">S\u00e9bastien Wagener (@foobar27)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/OfficialURL\">Violeta Hern\u00e1ndez (@OfficialURL)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/gliderkite\">@gliderkite<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/notgull\">John (@notgull)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/atouchet\">Alex Touchet @atouchet<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/sameer\">Sameer Puri (@sameer)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/CoorFun\">@CoorFun<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/murtyjones\">Murty Jones (@murtyjones)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/tarkah\">Cory Forsstrom (@tarkah)<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/Mivik\">@Mivik<\/a><\/li>\n<\/ul>\n<p>Thank y'all! You rock!<\/p>","category":{"@attributes":{"term":"lyon, rust"}}},{"title":"Improving texture atlas allocation in WebRender","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/etagere.html","rel":"alternate"}},"published":"2021-02-04T00:00:00+01:00","updated":"2021-02-04T00:00:00+01:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2021-02-04:\/posts\/etagere.html","summary":"<p>Lately I have been working on improving texture atlas allocation in WebRender. It isn't an outstanding technical feat, but the journey towards achieving this goal was quite pleasant. <\/p>\n<p>This is a longer version of the piece I published in the <a href=\"https:\/\/mozillagfx.wordpress.com\/2021\/02\/04\/improving-texture-atlas-allocation-in-webrender\/\">mozilla gfx team blog<\/a> where I focus on the atlas \u2026<\/p>","content":"<p>Lately I have been working on improving texture atlas allocation in WebRender. It isn't an outstanding technical feat, but the journey towards achieving this goal was quite pleasant. <\/p>\n<p>This is a longer version of the piece I published in the <a href=\"https:\/\/mozillagfx.wordpress.com\/2021\/02\/04\/improving-texture-atlas-allocation-in-webrender\/\">mozilla gfx team blog<\/a> where I focus on the atlas allocation algorithms. In this one I'll go into more details about the process and methodology behind these improvements.<\/p>\n<p>The first part is about the making of guillotiere, a crate that I first released in March 2019. In the second part we'll have a look at more recent work building upon what I did with guillotiere, to improve texture memory usage in WebRender\/Firefox.<\/p>\n<h1>Texture atlas allocation<\/h1>\n<p>In order to submit work to the GPU efficiently, WebRender groups as many drawing primitives as it can into what we call batches. A batch is submitted to the GPU as a single drawing command and has a few constraints. for example a batch can only reference a fixed set of resources (such as GPU buffers and textures). So in order to group as many drawing primitives as possible in a single batch we need to place as many drawing parameters as possible in few resources. When rendering text, WebRender pre-renders the glyphs before compositing them on the screen  so this means packing as many pre-rendered glyphs as possible into a single texture, and the same applies for rendering images and various other things.<\/p>\n<p>For a moment let's simplify the case of images and text and assume that it is the same problem: input images (rectangles) of various rectangular sizes that we need to pack into a larger rectangle. This is the job of the texture atlas allocator. Another common name for this is rectangle bin packing.<\/p>\n<p><img alt=\"Atlas allocation\" src=\"https:\/\/nical.github.io\/images\/atlas\/atlas-allocation.svg\"><\/p>\n<p>Many in game and web development are used to packing many images into fewer assets. In most cases this can be achieved at build time Which means that the texture atlas allocator only needs to find a good layout for a fixed set of rectangles without supporting dynamic deallocation and allocation within the atlas at run time. I call this \"static\" atlas allocation as opposed to \"dynamic\" atlas allocation.<\/p>\n<p>There's a lot more literature out there about static than dynamic atlas allocation. I recommend reading <a href=\"http:\/\/pds25.egloos.com\/pds\/201504\/21\/98\/RectangleBinPack.pdf\"><em>A thousand ways to pack the bin<\/em><\/a> which is a very good survey of various static packing algorithms. Dynamic atlas allocation is unfortunately more difficult to implement while keeping good run-time performance. WebRender needs to maintain texture atlases into which items are added and removed over time. In other words we don't have a way around needing dynamic atlas allocation.<\/p>\n<h1>Chapter 1<\/h1>\n<p>A while back, WebRender had a naive implementation of the guillotine algorithm (explained in <a href=\"http:\/\/pds25.egloos.com\/pds\/201504\/21\/98\/RectangleBinPack.pdf\"><em>A thousand ways to pack the bin<\/em><\/a>). This algorithm strikes a good compromise between packing quality and implementation complexity.\nThe main idea behind it can be explained simply: \"Maintain a list of free rectangles, find one that can hold your allocation, split the requested allocation size out of it, creating up to two additional rectangles that are added back to the free list.\". There is subtlety in which free rectangle to choose and how to split it, but the overall, the algorithm is built upon reassuringly understandable concepts.<\/p>\n<p><img alt=\"Guillotine allocation steps\" src=\"https:\/\/nical.github.io\/images\/atlas\/guillotine-alloc.svg\"><\/p>\n<p>Deallocation could simply consist of adding the deallocated rectangle back to the free list, but without some way to merge back neighbor free rectangles, the atlas would quickly get into a fragmented stated with a lot of small free rectangles and can't allocate larger ones anymore.<\/p>\n<p><img alt=\"Fragmented state\" src=\"https:\/\/nical.github.io\/images\/atlas\/fragmented.svg\"><\/p>\n<p>To address that, WebRender's implementation would regularly do a O(n\u00b2) complexity search to find and merge neighbor free rectangles, which was very slow when dealing with thousands of items. Eventually we stopped using the  guillotine allocator in systems that needed support for deallocation, replacing it with a very simple slab allocator which I'll get back to later in this post.<\/p>\n<p>I wasn't satisfied with moving to a worse allocator because of the run-time defragmentation issue, so as a side project I wrote a guillotine allocator that tracks rectangle splits in a tree in order to find and merge neighbor free rectangle in constant instead of quadratic time. I published it in the <a href=\"https:\/\/crates.io\/crates\/guillotiere\">guillotiere<\/a> crate. I wrote about how it works in details in <a href=\"https:\/\/docs.rs\/guillotiere\/0.6.0\/guillotiere\/struct.AtlasAllocator.html\">the documentation<\/a> so I won't go over it here. I'm quite happy about how it turned out, although I haven't pushed to use it in WebRender, mostly because I wanted to first see evidence that it would help and I already had evidence that many other things needed to be worked on.<\/p>\n<h2>Visualizing program state using SVG<\/h2>\n<p>guillotiere lets you dump a visualization of the atlas in SVG format.<\/p>\n<p><img alt=\"Guillotine allocation visualization\" src=\"https:\/\/nical.github.io\/images\/atlas\/guillotine-example-1.svg\"><\/p>\n<p>The image above shows the state of the atlas after a few allocations. Allocated space is represented in light blue while free space is in dark gray. It is much easier to work with than a list of coordinates in plain text. It was handy when developing and tuning the algorithm, but also when using it in other projects. While looking at the visual representation of the state animate you quickly develop an intuition of how the algorithm unfolds Concepts that are hard to explain in written form sometimes just \"make sense\" visually.<\/p>\n<p>Dumping visual representations in a .svg file is not only a powerful tool when exploring problem some spaces, it is also surprisingly simple to do. SVG is a straightforward XML type of format which is annoying to type by hand but effortless to generate with very simple helpers. Here is how it looks using a tiny helper crate called <a href=\"https:\/\/crates.io\/crates\/svg_fmt\">svg_fmt<\/a>:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"w\">    <\/span><span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">svg_fmt<\/span>::<span class=\"o\">*<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">output<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">std<\/span>::<span class=\"n\">fs<\/span>::<span class=\"n\">File<\/span>::<span class=\"n\">create<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;tmp.svg&quot;<\/span><span class=\"p\">).<\/span><span class=\"n\">unwrap<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Need this at the beginning of the file. Set the size of the drawable area to 800x600.<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">writeln!<\/span><span class=\"p\">(<\/span><span class=\"n\">output<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;{}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">BeginSvg<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">w<\/span>: <span class=\"mf\">800.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">h<\/span>: <span class=\"mf\">600.0<\/span><span class=\"w\"> <\/span><span class=\"p\">})<\/span><span class=\"o\">?<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Draw a rectangle.<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">writeln!<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">output<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"s\">r#&quot;    {}&quot;#<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">rectangle<\/span><span class=\"p\">(<\/span><span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">200.0<\/span><span class=\"p\">)<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">.<\/span><span class=\"n\">fill<\/span><span class=\"p\">(<\/span><span class=\"n\">rgb<\/span><span class=\"p\">(<\/span><span class=\"mi\">40<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">40<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mi\">40<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">.<\/span><span class=\"n\">stroke<\/span><span class=\"p\">(<\/span><span class=\"n\">Stroke<\/span>::<span class=\"n\">Color<\/span><span class=\"p\">(<\/span><span class=\"n\">black<\/span><span class=\"p\">(),<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">))<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">)<\/span><span class=\"o\">?<\/span><span class=\"p\">;<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Draw some text at position 100.0 100.0<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">writeln!<\/span><span class=\"p\">(<\/span><span class=\"n\">output<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;{}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">text<\/span><span class=\"p\">(<\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">100.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;Some text!&quot;<\/span><span class=\"p\">.<\/span><span class=\"n\">to_string<\/span><span class=\"p\">()));<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Need this at the end.<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">writeln!<\/span><span class=\"p\">(<\/span><span class=\"n\">output<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s\">&quot;{}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">EndSvg<\/span><span class=\"p\">)<\/span><span class=\"o\">?<\/span><span class=\"p\">;<\/span>\n<\/code><\/pre><\/div>\n\n<p>So many useful visualizations can be easily built out of simple colored rectangles and text and there's other primitives provided by svg_fmt. Rectangles were all I needed in guillotiere.<\/p>\n<p>You can look at <a href=\"https:\/\/github.com\/nical\/rust_debug\/blob\/492600cac47f64bcadaf9ad037ed64c5fecc8e63\/svg_fmt\/src\/svg.rs\">how simple the svg_fmt code is<\/a>. It has become a dependency to most of the things I've worked on lately, including WebRender which uses it to dump visualizations of texture atlases and the render graph.<\/p>\n<p><img alt=\"Render graph visualization\" src=\"https:\/\/nical.github.io\/images\/atlas\/rendergraph.svg\"><\/p>\n<p>My hope by now is that if you are working on problems that can be represented in 2D space, I've managed to convince you of how easily you can supplement or break free of reading text in your debugger\/terminal. If anything, just <code>println!(r#\"&lt;rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill:rgb(100,0,0)\" \/&gt;\"\"#, x, y, w, h);<\/code> your way into looking at your algorithms unfolding.<\/p>\n<h2>Making\/testing\/debugging a small rust crate<\/h2>\n<p>I had a great time writing guillotiere for several reasons. The problem itself had some nice properties:<\/p>\n<ul>\n<li>It's a well defined problem with simple input and output data. As a result it is very easy to write unit tests and fuzz the code.<\/li>\n<li>No nebulous design space for fancy abstractions. A retained state, query a size in, get a rectangle out. Simple.<\/li>\n<li>Can be implemented in its own library outside of a big rendering engine, and enjoy fast compile\/debug iterations.<\/li>\n<\/ul>\n<p>It was the Rust programming language and ecosystem that really made it a such pleasant journey.<\/p>\n<p>Bootstrapping a simple library, creating unit tests, adding dependencies is simple and effortless in Rust. This alone is a huge time saver for me compared to when I would do this sort of thing in C++ (I can only hope that the situation has improved in C++ since). Fellow Rust developers are pretty used to that so let's move on.<\/p>\n<p>I quickly wrote a simple command-line application to interactively play with the packing algorithm.\nThe application deserializes the state of the atlas from a file, execute a command (for example allocation or deallocation) and serializes back into the file (using the .ron file format). In addition, the command-line application could dump a visualization of the atlas in SVG.<\/p>\n<p>The command-line app was put together very quickly thanks to fantastic pieces of the Rust ecosystem:<\/p>\n<ul>\n<li><a href=\"https:\/\/crates.io\/crates\/serde\">serde<\/a> for serialization\/deserialzation,<\/li>\n<li><a href=\"https:\/\/crates.io\/crates\/ron\">ron<\/a> providing a nice and readable serialized file format,<\/li>\n<li>and <a href=\"https:\/\/crates.io\/crates\/clap\">clap<\/a> for parsing command-line arguments.<\/li>\n<\/ul>\n<p>Put together, this gave me an interactive playground to test the algorithm. Playing around in a terminal would look like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>$<span class=\"w\"> <\/span>guillotiere<span class=\"w\"> <\/span>init<span class=\"w\"> <\/span><span class=\"m\">1024<\/span><span class=\"w\"> <\/span><span class=\"m\">1024<\/span>\n$<span class=\"w\"> <\/span>guillotiere<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">16<\/span><span class=\"w\"> <\/span><span class=\"m\">32<\/span>\nAllocated<span class=\"w\"> <\/span>rectangle<span class=\"w\"> <\/span>r1<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>size<span class=\"w\"> <\/span>16x32<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>origin<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">]<\/span>\n$<span class=\"w\"> <\/span>guillotiere<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">200<\/span><span class=\"w\"> <\/span><span class=\"m\">100<\/span><span class=\"w\"> <\/span>--svg<span class=\"w\"> <\/span><span class=\"m\">01<\/span>.svg\nAllocated<span class=\"w\"> <\/span>rectangle<span class=\"w\"> <\/span>r2<span class=\"w\"> <\/span>of<span class=\"w\"> <\/span>size<span class=\"w\"> <\/span>200x100<span class=\"w\"> <\/span>at<span class=\"w\"> <\/span>origin<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">16<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">]<\/span>\n$<span class=\"w\"> <\/span>guillotiere<span class=\"w\"> <\/span>deallocate<span class=\"w\"> <\/span>r1<span class=\"w\"> <\/span>--svg<span class=\"w\"> <\/span><span class=\"m\">02<\/span>.svg\n\netc...\n<\/code><\/pre><\/div>\n\n<p>At any time in that sequence of commands I can open the <code>atlas.ron<\/code> file and read the state of the atlas as if I was in a debugger, can also copy it around to save the state in a way that almost feels as powerful as using <a href=\"https:\/\/rr-project.org\/\">record-and-replay debugging<\/a>.<\/p>\n<h2>Fuzzing<\/h2>\n<p>I mentioned fuzzing earlier. <a href=\"https:\/\/github.com\/rust-fuzz\/cargo-fuzz\">Cargo fuzz<\/a> is a joy and I really recommend using it whenever possible. It's very easy to setup, I wouldn't necessarily run it on every push, but every once in a while to find some bugs and\/or get a bit of confidence about the robustness of your code. It's great. It has plenty of well written <a href=\"https:\/\/rust-fuzz.github.io\/book\/\">documentation<\/a> so I won't go into details here. I'll just mention that it's a very well made piece of Rust's ecosystem that contributes to the greatness of the whole in my opinion.<\/p>\n<h1>Chapter 2<\/h1>\n<p>Fast forward the end of 2020. Ah 2020.<\/p>\n<p>I was investigating further improvements to draw call batching and texture upload overhead which are big performance bottlenecks on low end Intel GPUs, especially on Windows.<\/p>\n<p>Gathering some statistics about what causes new batches to be generated shows that it is often happening when multiple primitives use the same shader but are reading from different textures. Interesting. If we were able to pack more image into fewer textures we could improve the likelihood of primitives reading the same texture and therefore generate less batches and reduce the driver overhead.<\/p>\n<p>In addition, being able to pack more images into less texture memory means we can afford to keep more of them on the GPU, evict images less often from the atlas (it is an LRU cache), and hopefully reduce the likelihood of having to re-upload images and glyphs. Texture uploads are terribly expensive on some configurations so avoiding them whenever we can is worthwhile.<\/p>\n<p>Of course there is a balancing act. If we keep items longer in the cache we may not be able to pack them into fewer textures. If we pack items into few textures we may have to put pressure on the cache, not letting us keep items longer. The ideal solution will somewhere between the two. In any case, being able to pack more items in a given amount of texture space is very beneficial so more than a year after guillotiere's first release on crates.io, I had some data suggesting that better texture atlases was worth spending time on.<\/p>\n<p>I was not quite at a point where I knew for sure whether integrating guillotiere into WebRender would be the right thing to do (I did have strong suspicions that it would be an improvement but I wanted to validate them first), and guillotiere might not be the best solution for WebRender's particular workloads.<\/p>\n<h2>Methodology<\/h2>\n<p>In order to iterate quickly, I wanted to test algorithms outside of Firefox. I made a small Rust command-line program very similar to the one I had made for guillotiere (read: mostly copy-pasted from it) which I could use to replay recorded real-world atlas allocation workloads, recorded via some instrumentation in Firefox.<\/p>\n<p>I ended up with a few scripts to replay the allocations different browsing sessions, that looked like:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"ch\">#!\/bin\/sh<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">7<\/span><span class=\"w\"> <\/span><span class=\"m\">23<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">1<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">10<\/span><span class=\"w\"> <\/span><span class=\"m\">20<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">2<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">15<\/span><span class=\"w\"> <\/span><span class=\"m\">22<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">3<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">14<\/span><span class=\"w\"> <\/span><span class=\"m\">23<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">4<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">19<\/span><span class=\"w\"> <\/span><span class=\"m\">22<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">5<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">5<\/span><span class=\"w\"> <\/span><span class=\"m\">22<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">6<\/span>\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">15<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">7<\/span>\natlas<span class=\"w\"> <\/span>deallocate<span class=\"w\"> <\/span><span class=\"m\">2<\/span>\natlas<span class=\"w\"> <\/span>deallocate<span class=\"w\"> <\/span><span class=\"m\">5<\/span>\n\natlas<span class=\"w\"> <\/span>svg<span class=\"w\"> <\/span>snapshot-01.svg\n\natlas<span class=\"w\"> <\/span>allocate<span class=\"w\"> <\/span><span class=\"m\">15<\/span><span class=\"w\"> <\/span><span class=\"m\">15<\/span><span class=\"w\"> <\/span>-n<span class=\"w\"> <\/span><span class=\"m\">8<\/span>\n<span class=\"c1\"># ... Tens of thousands of lines like the above.<\/span>\n<\/code><\/pre><\/div>\n\n<p>I would first run the program to set some initial parameters, for example <code>atlas init tiled 2048 2048<\/code>, then run the scripts to replay some workloads. The scripts dumps some snapshots in SVG format at various fixed points. So that I could compare how different algorithms look at the same steps of the the same workloads.<\/p>\n<p>The program would also record various stats such as size distributions, the highest number of allocated items at any given step or the amount of wasted space coming from the allocation strategy.<\/p>\n<h2>The slab allocator<\/h2>\n<p>What replaced WebRender's guillotine allocator in the texture cache was a very simple one based on fixed power-of-two square slabs, with a few special-cased rectangular slab sizes for tall and narrow items to avoid wasting too much space. The texture is split into 512 by 512 regions, each region is split into a grid of slabs with a fixed slab size per region. <\/p>\n<p><img alt=\"Slab allocation visualization\" src=\"https:\/\/nical.github.io\/images\/atlas\/slab-example-1.svg\"><\/p>\n<p>The image above shows the slab allocator in action on the image cache for a real browsing session, replayed in my little tool.<\/p>\n<p>This is a very simple scheme with very fast allocation and deallocation, however it tends to waste a lot of texture memory. For example allocating an 8x10 pixels glyph occupies a 16x16 slot, wasting more than twice the requested space. Ouch!\nIn addition, since regions can allocate a single slab size, space can be wasted by having a region with few allocations because the slab size happens to be uncommon.<\/p>\n<p><img alt=\"Slab allocation wasted space\" src=\"https:\/\/nical.github.io\/images\/atlas\/slab-wasted-space.svg\"><\/p>\n<p>Before replacing the slab allocator, I wanted to see if simple improvements could be enough. It wouldn't be wise to replace simple code with something with more complicated without seeing how far we can push the simple solution.<\/p>\n<h2>Improvements to the slab allocator<\/h2>\n<p>Images and glyphs used to be cached in the same textures. However we render images and glyphs with different shaders, so currently they can never be in the same rendering batches. Having a separate set of textures for images and glyphs therefore doesn't regress batching. On the other hand it provides with a few opportunities.\nNot mixing images and glyphs means the glyph textures get more room for glyphs which reduces the number of textures containing glyphs overall. In other words, less chances to break batches. The same naturally applies to images. This is of course at the expense of allocating more textures on average, but it is a good trade-off for us and we are about to compensate the memory increase by using tighter packing.<\/p>\n<p>In addition, glyphs and images are different types of workloads: we usually have a few hundred images of all sizes in the cache, while we have thousands of glyphs most of which have similar small sizes. Separating them allows us to introduce some simple workload-specific optimizations.<\/p>\n<p>The first optimization came from noticing that glyphs are almost never larger than 128px. Having more and smaller regions, reduces the amount of atlas space that is wasted by partially empty regions, and allows us to hold more slab sizes at a given time so I reduced the region size from 512x512 to 128x128 in the glyph atlases. In the unlikely event that a glyph is larger than 128x128, it will go into the image atlas.<\/p>\n<p>Next, I recorded the allocations and deallocations browsing different pages, gathered some statistics about most common glyph sizes and noticed that on a low-dpi screen, a quarter of the glyphs would land in a 16x16 slab but would have fit in a 8x16 slab. In latin scripts at least, glyphs are usually taller than wide. Adding 8x16 and 16x32 slab sizes that take advantage of this helps a <em>lot<\/em>.\nI could have further optimized specific slab sizes by looking at the data I had collected, but the more slab sizes I would add, the higher the risk of regressing different workloads. This problem is called over-fitting. I don't know enough about the many non-latin scripts used around the world to trust that my testing workloads were representative enough, so I decided that I should stick to safe bets (such as \"glyphs are usually small\") and avoid piling up optimizations that might penalize some languages. Adding two slab sizes was fine (and worth it!) but I wouldn't add ten more of them.<\/p>\n<p><img alt=\"Slab allocator improvements\" src=\"https:\/\/nical.github.io\/images\/atlas\/slab-improvements.svg\"><\/p>\n<p>The image above shows the same (real-world) workload applied to both the original and improved slab allocators.<\/p>\n<p>At this point, I had nice improvements to glyph allocation using the slab allocator, but was starting to get a firm intuition that I was going to hit a ceiling trying to improve it further.<\/p>\n<h2>Shelf packing allocators<\/h2>\n<p>I experimented with two algorithms derived from the shelf packing allocation strategy, both of them released in the Rust crate <a href=\"https:\/\/crates.io\/crates\/etagere\">etagere<\/a>. The general idea behind shelf packing  is to separate the 2-dimensional allocation problem into a 1D vertical allocator for the shelves and within each shelf, 1D horizontal allocation for the items.\nThe atlas is initialized with no shelf. When allocating an item, we first find the shelf that is the best fit for the item vertically, if there is none or the best fit wastes too much vertical space, we add a shelf. Once we have found or added a suitable shelf, an horizontal slice of it is used to host the allocation.<\/p>\n<p><img alt=\"Shelf packing\" src=\"https:\/\/nical.github.io\/images\/atlas\/shelf-packing.svg\"><\/p>\n<p>At a glance we can see that this scheme is likely to provide much better packing than the slab allocator. For one, items are tightly packed horizontally within the shelves. That alone saves a lot of space compared to the power-of-two slab widths. Most of the waste happens vertically, between an item and the top of its shelf. How much the shelf allocator wastes vertically depends on how the shelve heights are chosen. Since we aren't constrained to power-of-two size, we can also do much better than the slab allocator vertically.<\/p>\n<h3>The bucketed shelf allocator<\/h3>\n<p>The first shelf allocator I implemented was inspired from Mapbox's <a href=\"https:\/\/github.com\/mapbox\/shelf-pack\/\">shelf-pack<\/a> allocator written in JavaScript. It has an interesting bucketing strategy: items are accumulated into fixed size \"buckets\" that behave like a small bump allocators. Shelves are divided into a certain number of buckets and buckets are only freed when all elements are freed (via reference counting). The trade-off here is to keep atlas space occupied for longer in order to reduce the CPU cost of allocating and deallocating. Only the top-most shelf is removed when empty so consecutive empty shelves in the middle aren't merged until they become the top-most shelves, which can cause a bit of vertical fragmentation for long running sessions. When the atlas is full of (potentially empty) shelves the chance that a new item is too tall to fit into one of the existing shelves depends on how common the item height is. Glyphs tend to be of similar (small) heights so it works  out well enough.<\/p>\n<p>I added very limited support for merging neighbor empty shelves. When an allocation fails, the atlas iterates over the shelves and checks if there is a sequence of empty shelves that in total would be able to fit the requested allocation. If so, the first shelf of the sequence becomes the size of the sum, and the other shelves are squashed to zero height. It sounds like a band aid (it is) but the code is simple and it is working within the constraints that make the rest of the allocator very simple and fast. It's only a limited form of support for merging empty shelves but it was an improvement for workloads that contain both small and large items.<\/p>\n<p><img alt=\"Shelf packing\" src=\"https:\/\/nical.github.io\/images\/atlas\/glyphs-bucketed-shelf.svg\"><\/p>\n<p>The image above was generated using the command-line tool with one of the glyph cache workloads. We see fewer wide boxes rather than many thin boxes because the allocator internally doesn't keep track of each item rectangle individually, so we only see buckets filling up instead.<\/p>\n<p>This allocator worked quite well for the glyph texture (unsurprisingly, as Mapbox's implementation this was inspired from is used with their glyph cache). The bucketing strategy was problematic, however, with large images. The relative cost of keeping allocated space longer was higher with larger items. Especially with long running sessions, this allocator was good candidate for the glyph cache but not for the image cache.<\/p>\n<h3>The simple shelf allocator<\/h3>\n<p>The guillotine allocator was working rather well with images. I was close to just using it for the image cache and move on. However, having spent a lot of time looking at various allocations patterns, my intuition was that we could do better. Again, this is largely thanks to being able to visualize the algorithm via these neat little SVG dumps.<\/p>\n<p>It motivated experimenting with a second shelf allocator. This one is conceptually even simpler: A basic vertical 1D allocator for shelves with a basic horizontal 1D allocator per shelf. Since all items are managed individually, they are deallocated eagerly which is the main advantage over the bucketed implementation. It is also why it is slower than the bucketed allocator, especially when the number of items is high. This allocator also has full support for merging\/splitting empty shelves wherever they are in the atlas.<\/p>\n<p><img alt=\"A glyph packing workload\" src=\"https:\/\/nical.github.io\/images\/atlas\/glyphs-shelf.svg\"><\/p>\n<p>The image above was generated using the command-line tool with the same glyph cache workload as the previous image. This allocator tracks each individual item so we get a more precise picture. <\/p>\n<p>Unlike the Bucketed allocator, this one worked very well for the image workloads. For short sessions (visiting only a handful of web pages) it was not as tightly packed as the guillotine allocator, but after browsing for longer period of time, it had a tendency to better deal with fragmentation.<\/p>\n<p><img alt=\"An image packing workload\" src=\"https:\/\/nical.github.io\/images\/atlas\/img-shelf.svg\"><\/p>\n<p>The image above was generated using the command-line tool with an image cache workload. Notice how different the image workloads look (using the same texture size), with much fewer items and a mix of large and small items sizes.<\/p>\n<p>The implementation is very simple, scanning shelves linearly and then within the selected shelf another linear scan to find a spot for the allocation. I expected performance to scale somewhat poorly with high number of glyphs (we are dealing in the thousands of glyphs which arguably isn't that high), but the performance hit wasn't as bad I had anticipated, probably helped by mostly cache friendly underlying data-structure.<\/p>\n<h3>A few other experiments<\/h3>\n<p>For both allocators I implemented the ability to split the atlas into a fixed number of columns. Adding columns means more (smaller) shelves in the atlas, which further reduces vertical fragmentation issues, at the cost of wasting some space at the end of the shelves. Good results were obtained on 2048 by 2048 atlases with two columns. You can see in the previous two images that the shelf allocator was configured to use two columns.<\/p>\n<p>The shelf allocators support arranging items in vertical shelves instead of horizontal ones. It can have an impact depending on the type of workload, for example if there is more variation in width than height for the requested allocations. As far as my testing went, it did not make a significant difference with workloads recorded in Firefox so I kept the default horizontal shelves.<\/p>\n<p>The allocators also support enforcing specific alignments in x and y (effectively, rounding up the size of allocated items to a multiple of the x and y alignment). This introduces a bit of wasted space but avoids leaving tiny holes smaller than the alignment size in the atlas. Some platforms also require a certain alignment for various texture transfer operations so it is useful to have this knob to tweak at our disposal. In the Firefox integration, we use different alignments for each type of atlas, favoring small alignments for atlases that mostly contain small items to keep the relative wasted space small.<\/p>\n<h1>Conclusion<\/h1>\n<p><img alt=\"A few more texture atlases for fun\" src=\"https:\/\/nical.github.io\/images\/atlas\/various-atlases.svg\"><\/p>\n<p>The guillotine allocator is the best at keeping track of all available space and can provide the best packing of all algorithms I tried. The shelf allocators waste a bit of space by simplifying the arrangement into shelves, and the slab allocator wastes a lot of space for the sake of simplicity. On the other hand the guillotine allocator is the slowest when dealing with multiple thousands of items and can suffer from fragmentations in some of the workloads I recorded. Overall the best compromise was the simple shelf allocator which I ended up using in Firefox for both glyph and image textures in the cache (in both cases configured to have two columns per texture). The bucketed allocator is still a very reasonable option for glyphs and we could switch to it in the future if we feel we should trade some packing efficiency for allocation\/deallocation performance.<\/p>\n<p>In other parts of WebRender, for short lived atlases (a single frame), the guillotine allocation algorithm is used.<\/p>\n<p>These observations are mostly workload-dependent, though. Workloads are rarely completely random so results may vary.<\/p>\n<p>There are other algorithms I could have explored (and maybe will someday, who knows), but I had found a satisfying compromise between simplicity, packing efficiency, and performance. I wasn't aiming for state of the art packing efficiency. Simplicity was a very important parameter and whatever solutions I came up with would have to be simple enough to ship it in a web browser without risks.<\/p>\n<p>To recap, my goals were to:<\/p>\n<ul>\n<li>allow packing more texture cache items into fewer textures,<\/li>\n<li>reduce the amount of texture allocation\/deallocation churn,<\/li>\n<li>avoid increasing GPU memory usage, and if possible reduce it.<\/li>\n<\/ul>\n<p>This was achieved by improving atlas packing to the point that we rarely have to allocate multiple textures for each item type (provided the amount of pixels that need to be cached which depends on what the page has to show on screen at any given time can possibly fit in a texture of course).<\/p>\n<p>The results look pretty good so far. Before the changes in Firefox, glyphs would often be spread over a number of textures after having visited a couple of websites, Currently the cache eviction is set so that we rarely need more than than one or two textures with the new allocator, and with some future tuning of the cache eviction logic I am confident that we can get glyphs to fit consistently into a single texture. For images, the shelf allocator is pretty big win as well. what fit into five textures now fits into two or three.<\/p>\n<p>Today this translates into fewer draw calls and less CPU-to-GPU transfers which has a noticeable impact on performance on low end Intel GPUs, in addition to reducing GPU memory usage.<\/p>\n<p>The slab allocator improvements landed in <a href=\"https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=1674443\">bug 1674443<\/a> and shipped in Firefox 85, while the shelf allocator integration work went in <a href=\"https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=1679751\">bug 1679751<\/a> and will make it hit the release channel in Firefox 86. The interesting parts of this work are packaged in a couple of rust crates under permissive MIT OR Apache-2.0 license:<\/p>\n<p><a href=\"https:\/\/github.com\/nical\/guillotiere\">guillotiere<\/a>:<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/guillotiere\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/guillotiere\"><\/a> <a href=\"https:\/\/docs.rs\/guillotiere\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/guillotiere\/badge.svg\"><\/a> <\/p>\n<p><a href=\"https:\/\/github.com\/nical\/etagere\">etagere<\/a>:<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/etagere\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/etagere\"><\/a> <a href=\"https:\/\/docs.rs\/etagere\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/etagere\/badge.svg\"><\/a><\/p>\n<p>The hacky tool I put together to experiment with all of this can be found <a href=\"https:\/\/github.com\/nical\/texture-atlas\">on github<\/a>.<\/p>\n<p>I am quite happy with the Firefox improvements. I am also very pleased with the whole journey, with its visual explorations, data-driven decisions and effortless testing, debugging and even fuzzing.<\/p>","category":{"@attributes":{"term":"webrender, rust"}}},{"title":"A new tessellator","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/new-tessellator.html","rel":"alternate"}},"published":"2019-12-26T00:00:00+01:00","updated":"2019-12-26T00:00:00+01:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2019-12-26:\/posts\/new-tessellator.html","summary":"<p>This post is about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, a rust crate to tessellate arbitrary 2D shapes into triangle meshes that can be easily rendered on the GPU.<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p>About a year ago, in the <a href=\"https:\/\/nical.github.io\/posts\/lyon-2018.html\">lyon in 2018 post<\/a> on this blog, I mentioned that I was working on a complete rewrite of lyon's central \u2026<\/p>","content":"<p>This post is about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, a rust crate to tessellate arbitrary 2D shapes into triangle meshes that can be easily rendered on the GPU.<\/p>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p>About a year ago, in the <a href=\"https:\/\/nical.github.io\/posts\/lyon-2018.html\">lyon in 2018 post<\/a> on this blog, I mentioned that I was working on a complete rewrite of lyon's central piece, the <a href=\"https:\/\/docs.rs\/lyon_tessellation\/0.15.0\/lyon_tessellation\/struct.FillTessellator.html\">fill tessellator<\/a>. I have been working on this for quite a bit. The work-in-progress <a href=\"https:\/\/github.com\/nical\/lyon\/pull\/334\">pull request<\/a> was created in February 2018. Almost two years in the making, this work made it in version <a href=\"https:\/\/crates.io\/crates\/lyon\/0.15.0\"><code>0.15<\/code><\/a>, the project's biggest release ever.<\/p>\n<p>It was a lot of work. Too much work. Fortunately, I am pretty happy about the result.<\/p>\n<h1>Motivation<\/h1>\n<p>So, why put so much effort in rewriting all of this?<\/p>\n<h2>Robustness<\/h2>\n<p>The fill tessellator was pretty robust, but not 100% bullet-proof. There's a built-in fuzzer in the test suite that could run for many hours before finding a shape that breaks the tessellator, but would always eventually stumble upon unrecoverable state and panic or return an error. The fuzzer wasn't the only entity to find issues. a few users reported some panics using the tessellator. Some of these reports were easy to address, some were very hard, and it almost always boiled down to precision loss introduced by arithmetic operations performed when detecting and handling self-intersecting geometry. The tessellator's algorithm had been built around a simplified mental model where arithmetic is precise, and key geometric properties could always be taken for granted. Long story short, there were some rare but very hard to fix bugs that required rethinking core parts of the algorithm.<\/p>\n<p>The new tessellator embraces the idea that no matter how hard we try to avoid it, some floating point precision issues will eventually cause some invalid states to appear. Instead of relying on this to be prevented the new algorithm is built around being able to detect and recover from these issues.<\/p>\n<p>This is done by splitting each iteration in two phases: the <em>scan phase<\/em> has most of the interesting logic of the algorithm, but doesn't perform any mutation. Instead it records changes that will be applied int the <em>update phase<\/em> which only performs the mutations.<\/p>\n<p>Errors can be detected during the scan phase. Sometimes these errors imply that some of the analysis performed during the scan is invalid (for example due to incorrect edge ordering), but it doesn't matter because the scan phase hasn't committed any mutation, so we can bail out of it, do our best to sanitize our initial state and run the iteration again.<\/p>\n<p>In overly-simplified Rust pseudo-code, the main loop looks somewhat like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">impl<\/span><span class=\"w\"> <\/span><span class=\"n\">Tesselator<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">fn<\/span> <span class=\"nf\">algorithm<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span>-&gt; <span class=\"nc\">TessellationResult<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ ...<\/span>\n\n<span class=\"w\">        <\/span><span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">iteration<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">iterations<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ Invalid states can be detected during the &quot;analysis&quot; or &quot;scan&quot; phase.<\/span>\n<span class=\"w\">            <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">updates<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"k\">match<\/span><span class=\"w\"> <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">scan_phase<\/span><span class=\"p\">(<\/span><span class=\"n\">iteration<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                <\/span><span class=\"nb\">Ok<\/span><span class=\"p\">(<\/span><span class=\"n\">updates<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"n\">updates<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                <\/span><span class=\"nb\">Err<\/span><span class=\"p\">(<\/span><span class=\"n\">error<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                    <\/span><span class=\"c1\">\/\/ Something is wrong, recover from it before trying again.<\/span>\n<span class=\"w\">                    <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">recover_from_error<\/span><span class=\"p\">(<\/span><span class=\"n\">error<\/span><span class=\"p\">);<\/span>\n\n<span class=\"w\">                    <\/span><span class=\"c1\">\/\/ Return an error if we fail the second time.<\/span>\n<span class=\"w\">                    <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">scan_phase<\/span><span class=\"p\">(<\/span><span class=\"n\">iteration<\/span><span class=\"p\">)<\/span><span class=\"o\">?<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">            <\/span><span class=\"c1\">\/\/ Internal mutations can only happen here.<\/span>\n<span class=\"w\">            <\/span><span class=\"bp\">self<\/span><span class=\"p\">.<\/span><span class=\"n\">update_phase<\/span><span class=\"p\">(<\/span><span class=\"n\">updates<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ ...<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>This doesn't sound like much but it is a major shift in how the algorithm is organized. This alone required a rewrite and it paid off.<\/p>\n<p>Another key aspect of the new design was avoiding to rely on prior events when information can be reconstructed locally. In other words try hard not to have invalid state accumulate and contaminate subsequent steps of the algorithm.<\/p>\n<p>I am sure that bugs will be found as it always goes with any new non-trivial piece of code. It'll be wise to take the claims I made about robustness with a grain of salt until the code has had a chance to be used in more places and pass the test of time. I have let the fuzzer run on 4 of cores of a beefy desktop for about 48 hours and it didn't find any panic. That's already a lot more robust than the previous tessellator, at least with the family of bugs that the fuzzer is good at finding. I am also confident that it will be much easier to fix upcoming issues with the new algorithm.<\/p>\n<h2>Getting rid of fixed-point numbers<\/h2>\n<p>In an effort to make reasoning about precision easier, the old tessellator had moved most (but not all) of its geometric calculations to a fixed point number representation. It helped at first but in the long run it turned out to be a mistake. A mistake that was impossible to come back from after months of adjusting thresholds and other knobs to paper over precision issues that still existed. Fixed-point numbers, while providing a somewhat consistent precision loss that I had an easier time wrapping my head around, still lost precision and didn't solve the root of the issue. They helped with the easy problems and got in the way of fixing the hardest ones.<\/p>\n<p>In addition, fixed point numbers came with two major drawbacks:<\/p>\n<ul>\n<li>The range of numbers that could represented inside the tessellator was greatly reduced in comparison with 32 bit floats. My initial feeling was that users wouldn't often need to work with coordinates larger than <code>32767.0<\/code>, but that assumption proved to be wrong. While it was possible to work around the issue by scaling the path down and scaling the output mesh back up, it was far from a satisfying answer.<\/li>\n<li>The vertices generated by the tessellator were almost but not quite the same as the points of the input shapes, due to being converted to fixed-point and back to float.<\/li>\n<\/ul>\n<p>The new tessellator internally works with 32 bit floating point numbers and the positions from the original path are now unmodified in the output.<\/p>\n<h2>Custom vertex attributes<\/h2>\n<p>In order to achieve certain effects it is often desirable to be able to associate extra attributes per-vertex attributes, for example color, texture coordinates, bone weights, etc.<\/p>\n<p>This has been lyon's most requested feature, but a tricky one to get right. On the surface it seems simple: give all path endpoints their own ID and present these IDs when building the vertices during tessellation. However the tessellator occasionally has to create new vertices that do not correspond to existing endpoints of the input path, for example when handling self-intersections or when flattening b\u00e9zier curves.<\/p>\n<p>To address this, the tessellator keeps track for each vertex of all of the edges that it belongs to and where on these edges. This information can be cumbersome to consume, so a concept of interpolated attributes was built on top of it. The idea is that an array of floating point numbers can be associated to each of the input path's endpoints and passed to the geometry builder when generating vertices. When the source of a vertex is more complex than a single endpoint, the tessellator interpolates the values automatically.<\/p>\n<p>Find out more about this in the <a href=\"https:\/\/docs.rs\/lyon_tessellation\/0.15.0\/lyon_tessellation\/struct.FillTessellator.html#vertex-sources\">documentation<\/a>.<\/p>\n<p>The same mechanism was also added to the stroke tessellator.<\/p>\n<h2>Fill rules<\/h2>\n<p>The old tessellator was pretty much written for the even-odd <a href=\"https:\/\/www.w3.org\/TR\/SVG\/painting.html#WindingRule\">fill rule<\/a> and adding more fill rules turned out to be difficult in hindsight. The new tessellator's algorithms was designed with this in mind and currently supports non-zero and even-odd. More fill rules can easily be added, but these two are the only ones in SVG standard.<\/p>\n<p>The image below shows the same path, filled with the even-odd (on the left) and non-zero (on the right) fill rules<\/p>\n<p><img alt=\"Fill rules\" src=\"https:\/\/nical.github.io\/images\/lyon-evenodd-nonzero.png\"><\/p>\n<h2>Other goodies<\/h2>\n<p>The new tessellator can dynamically chose to traverse the geometry vertically or horizontally. As a rule of thumb it is usually better for performance to do a vertical sweep for shapes that are taller than wide, and do an horizontal sweep for shapes that are wider than tall.<\/p>\n<p>The image below shows the triangles generated with vertical (on the left) and horizontal (on the right) traversals of the same path.<\/p>\n<p><img alt=\"Vertical and horizontal traversals\" src=\"https:\/\/nical.github.io\/images\/lyon-sweep-v-h.png\"><\/p>\n<p>I spent a lot of time on the APIs related to building, storing and iterating over paths. This release has types to make working with simple <a href=\"https:\/\/docs.rs\/lyon_path\/0.15.0\/lyon_path\/polygon\/index.html\">polygons<\/a> nicer, as well as utilities to create <a href=\"https:\/\/docs.rs\/lyon_path\/0.15.0\/lyon_path\/commands\/index.html\">custom path data structures<\/a> which work with the tessellators.<\/p>\n<h1>What's the catch?<\/h1>\n<p>There are few caveats that I want to mention:<\/p>\n<ul>\n<li>The old fill tessellator was able to provide normals at each vertex. The new tessellator, however, cannot do that. Removing normals allowed a great deal of much needed simplification. I don't think that I will add this feature back. The stroke tessellator still has vertex normals, though.<\/li>\n<li>The new tessellator is a bit slower than the old one. This is mostly due to not having spent a lot of time profiling and optimizing yet and I am pretty confident that most of the gap can be closed. The new implementation is still about 50% faster than libtess2 (which I consider to be the \"industry standard\") on the workloads I compared them against (mostly the Rust logo and GhostScript tiger), so it's still pretty decent.<\/li>\n<li>A lot of APIs have changed. If you've used lyon before it'll still be familiar but updating, while not difficult, is likely to take a bit of effort.<\/li>\n<\/ul>\n<p>In previous blog posts I mentioned a plan to handle b\u00e9zier curves directly in the tessellator in order to allow resolution-independent tessellations and handle curves on the GPU (using tessellation or fragment shaders). I had to scope the project down in order to finally get something to shippable and this feature didn't make it. It's possible that I'll revisit it some time in the future, but realistically it will take a long time before I get an ambitious feature such as this one to work, if I ever do.<\/p>\n<h1>What's next?<\/h1>\n<p>For a little while, bug fixes and polish, after which I am hoping to tag a symbolic <code>1.0<\/code> release some time in 2020. I still have this project of improving the quality of the tessellated geometry (generating less thin triangles) that I would like to get back to, and There are a few algorithms I'd like to play with, like stroke-to-fill conversion and boolean operations.\nI would also like to spend some time working <em>with<\/em> lyon rather than only <em>on<\/em> it, though I don't know yet what will come out of that.<\/p>\n<h1>Conclusion<\/h1>\n<p>I am really happy and proud to finally release the new tessellator. It adds up to an enormous amount of work over the last two years, but I think that it was necessary to take the tessellator from pretty good to really robust and reliable. While uncompromising robustness was the main motivation behind this rewrite, a number of important features were also made possible.<\/p>\n<p>Although the rewrite wasn't well set up for external contributions, development didn't stop on the master branch! I would like to thank everyone who made contributions to lyon in 2019 and the years before. Also many thanks to everyone who reported bugs, for their time, patience and support.<\/p>\n<p>This blog does not have a comments section, discussion on <a href=\"https:\/\/www.reddit.com\/r\/rust\/comments\/efz5jb\/lyon_0150_a_new_tessellator\/\">reddit<\/a>.<\/p>","category":{"@attributes":{"term":"lyon, rust"}}},{"title":"A look at pathfinder","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/a-look-at-pathfinder.html","rel":"alternate"}},"published":"2019-05-28T00:00:00+02:00","updated":"2019-05-28T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2019-05-28:\/posts\/a-look-at-pathfinder.html","summary":"<p>This post is about <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a>, a GPU vector graphics renderer written in Rust by Patrick Walton as part of his work in the emerging technologies team at Mozilla. While I have followed this work very closely, I have contributed very little code to pathfinder so the credit really goes to \u2026<\/p>","content":"<p>This post is about <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a>, a GPU vector graphics renderer written in Rust by Patrick Walton as part of his work in the emerging technologies team at Mozilla. While I have followed this work very closely, I have contributed very little code to pathfinder so the credit really goes to Patrick.<\/p>\n<p>If you've read other entries on the blog you've heard of <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, which helps you with rendering vector graphics on the GPU by turning paths into triangle meshes. Pathfinder takes a completely different approach, so you should ignore everything I have written about lyon's tessellator while reading this post.<\/p>\n<p>Also, Pathfinder has gone through several complete rewrites each of which going for very different approaches, so information on <a href=\"https:\/\/pcwalton.github.io\/2017\/02\/14\/pathfinder.html\">some of Patrick's older blog posts<\/a> doesn't apply anymore.<\/p>\n<p>Pathfinder can be used to render glyph atlases and larger scenes such as SVG paths. The two use cases are handled a bit differently and in this post I will be focusing on the latter.<\/p>\n<h2>Tiling<\/h2>\n<p>Pathfinder splits paths into 16x16 pixels tiles. This tiling scheme has the following purposes:\n - Decompose the path which as a whole is a very complex object to render, into may smaller and simpler objects.\n - Use tiles that are completely filled with an opaque pattern for occlusion culling.<\/p>\n<p>For example let's look at the following simple scene:<\/p>\n<p><img alt=\"A simple scene\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/simple-scene.png\"><\/p>\n<p>And decompose it into tiles:<\/p>\n<p><img alt=\"Tiled simple scene\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/tiled-simple-scene.png\"><\/p>\n<p>In the scene, we have a number of opaque tiles that are very simple to render once we have identified that they are fully covered by a path.<\/p>\n<p><img alt=\"Tiled simple scene\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/opaque-tiles.png\"><\/p>\n<p>These are simply rendered by submitting a batch of instanced quads.<\/p>\n<p>A very good property of opaque tiles is that they completely hide what's under them, so we can trivially discard all blue tiles below an opaque green tile since we know it is fully occluded. This massively reduces overdraw in typical SVG drawings.<\/p>\n<p>The image below gives an idea of the overdraw of the famous GhostScript tiger. The lighter a pixel is, the more times it is written to with a traditional back to front rendering algorithm without occlusion culling.<\/p>\n<p><img alt=\"ghostscript tiger overdraw\" src=\"https:\/\/nical.github.io\/images\/rustfest\/tiger-overdraw.svg\"><\/p>\n<p>Because memory bandwidth is often the bottleneck when rendering vector graphics (especially at high resolutions), this occlusion culling is key to pathfinder's performance.<\/p>\n<p>Here is a view of the opaque tile pass for the GhostScript tiger in renderdoc:<\/p>\n<p><img alt=\"Tiger opaque tiles in renderdoc\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/tiger-opaque-tiles.png\"><\/p>\n<p>The opaque tile pass is very fast because it has zero overdraw and doesn't need any blending.<\/p>\n<h2>Alpha tiles<\/h2>\n<p>Back to our simple scene, this leaves us with the partially covered tiles to deal with:<\/p>\n<p><img alt=\"partial tiles of the simple scene\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/simple-scene-partial-tiles.png\"><\/p>\n<p>Opaque tiles are easy. It's good that we were able to detect them and render them with simple instanced quads, it even gives us a crude approximation of the final image, but the real challenge remains to render curves with high quality anti-aliasing.<\/p>\n<p>I will use the terms <em>alpha tiles<\/em> or <em>mask tiles<\/em> for tiles that contain edges. These are rendered in two passes. First a mask is generated in a float texture and the mask is used to render the tile on top of the opaque tiles.<\/p>\n<p>The float texture containing the masks for our simple scene might look something like this:<\/p>\n<p><img alt=\"mask tiles of the simple scene\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/simple-scene-mask.png\"><\/p>\n<h2>Rendering the masks<\/h2>\n<p>It is very common when dealing with vector graphics to separate the computation of coverage (whether a pixel is in or out of the path) shading (color of the pixel if it is covered).\nStencil-and-cover rendering approaches are textbook examples of this, traditionally rendering triangle fans into the stencil buffer to produce a binary coverage mask (pixels are either in or out of the path). Because this doesn't let you express partial coverage per pixel, anti-aliasing is usually done using multi-sampling.<\/p>\n<p>Unfortunately, MSAA is quite slow on Intel integrated GPUs. Even on more powerful NVidia and AMD GPUs, MSAA is expensive with high sample counts, so people will rarely ask for more than 8 samples per pixel which provides something far from what I would call high quality anti-aliasing.<\/p>\n<p>Instead of rendering masks into an integer textures like the stencil buffer, pathfinder renders into a float texture and uses instanced quads instead of building triangle fans along the shape of the path.<\/p>\n<p>Each edge intersecting a tile is submitted as a quad that corresponds the bounding rectangle of the edge intersected with bounds of the tile and with the lower edge snapped to the bottom of the tile.<\/p>\n<p><img alt=\"Tile edge quad\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/tile-mask-quad.png\"><\/p>\n<p>That the shape of these quads might look somewhat arbitrary. Before we can make sense of it we have to look at what this quad actually renders. For each pixel the fragment shader writes 0 if it is fully above the edge, \u00b11 below the edge, or a value in between corresponding to the coverage of the pixel if it is near the edge. The output value is either positive or negative depending on the winding of the edge.<\/p>\n<p><img alt=\"Tile edge quad\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/tile-mask-shader.png\"><\/p>\n<p>The quads are rendered with additive blending, causing the contributions of each edge to accumulate in the tile's mask.<\/p>\n<p><img alt=\"Tile edge quad\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/mask-coverage.png\"><\/p>\n<p>Now why did we snap the bottom of the quads to the bottom of the tile?<\/p>\n<p>In a lot of vector graphics rendering approaches, it helps to imagine that we are casting a ray (usually horizontal) coming from far away and looking at intersections against the path to generate a winding number for each pixel along the ray.<\/p>\n<p>In pathfinder, the edge quads are equivalent to groups of vertical rays coming from the top of the tile, writing the contribution of a single edge to all pixels below the edge, down to the bottom of the tile. We could have also snapped the top of the quad the top of the tile, but since we don't need to consider pixels above the edge we save a few pixel's worth of work by only stating at the top of the edge's bounding box.<\/p>\n<p>Rather than only writing the winding number between edges, pathfinder simply writes  the contribution of each edge to all pixels below it, which will give the same result since the contribution of two edges can cancel each other out if our imaginary ray was going in then out of the path before reaching the pixel.<\/p>\n<p>Note that using vertical rays is purely a matter of convention. Pathfinder could have been written in a way that follows the \"horizontal ray coming from the left\" analogy by snapping the right side of the quad to the right of the tile.<\/p>\n<h2>What if the top of a tile starts is already inside of the path ?<\/h2>\n<p>In the previous illustration we took it from granted that the top of the tile was outside ( initial winding numbers are zeros), but this does not always hold true in practice as any edge above the tile can contribute as well.<\/p>\n<p>One solution could be to simply include all edges above the tile but for large drawing this can bring a lot of edges. So pathfinder handles this during the tiling phase on the CPU by tracking the winding number at the top of each tile and inserting a minimal amount of extra edges to compensate for the information that is lost by only considering edges inside of the tile.<\/p>\n<p><img alt=\"Tile edge quad\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/mask-coverage-2.png\"><\/p>\n<p>On the left side of the image below, the tiger is rendered and the triangles emitted during the compositing pass of the mask tiles are highlighted in yellow. On the right side the same pass is rendered on top of a black background to better see which parts of the drawing end up drawn with mask tiles. The image was produced thanks to renderdoc.<\/p>\n<p><img alt=\"Tile edge quad\" src=\"https:\/\/nical.github.io\/images\/pathfinder\/tiger-alpha-pass.png\"><\/p>\n<h2>Summary<\/h2>\n<p>Piecing it all together:<\/p>\n<ul>\n<li>Paths are split into tiles on the CPU.<\/li>\n<li>Mask tiles are rendered in a float texture on the GPU.<\/li>\n<li>Solid tiles, which were detected during the tiling phase, are rendered into the destination color target.<\/li>\n<li>Mask tiles are composited into the color target, reading from the mask tiles that were rendered in the float texture.<\/li>\n<\/ul>\n<p>The above sequence is what happens under the simplest settings. Pathfinder has the option to start submitting rendering commands while tiling is in progress to hide some of the latency of the tiling phase. There is also the option of tiling paths in parallel using rayon, which provides a nice speedup on computers with more than two physical cores.<\/p>\n<h2>Rendering strokes<\/h2>\n<p>Up to this point I only wrote about filling paths, but strokes are also important.\nCurrently pathfinder simply transforms stroke primitives into fill primitives on the CPU. It works and was a quick way to get things up and running, but it's certainly costly. Rendering strokes without expressing them as fills will be implemented eventually. The strokes can generate mask tiles just like fills. The main difference would be in how these mask tiles are generated. With round line joins and round line caps it's pretty simple. We can use the maximum of the distance to each edge. Other line joins require a bit more work but there is a lot of prior art to follow or get inspiration from.<\/p>\n<h2>Rendering other types of primitives<\/h2>\n<p>Pathfinder's tiling scheme has the following nice properties:<\/p>\n<ul>\n<li>Mask tiles can be rendered in any order.<\/li>\n<li>The \"compositing\" phase is independent from how the mask tiles were generated.<\/li>\n<\/ul>\n<p>This means that any kind of rendering primitive (2D distance fields come to mind for example) that can produce tile masks are very easy to integrate into this system without introducing batching issues, while also benefiting from the occlusion culling optimizations.<\/p>\n<h2>Rendering text<\/h2>\n<p>To some, pathfinder is better known as a text rasterizer than as a way to render larger vector graphics scenes. Rendering glyphs works the same way except that tiling isn't necessary because glyphs are usually small enough that the occlusion culling would not help at all.<\/p>\n<h2>Conclusion<\/h2>\n<p>Pathfinder's main takeaways are:<\/p>\n<ul>\n<li>A tiling scheme allowing powerful optimizations such as occlusion culling and a very fast opaque tile pass.<\/li>\n<li>An interesting way to compute coverage by rendering quads into a floating point texture.<\/li>\n<\/ul>\n<p>The two are actually completely independent and one could use the same tiling approach while rendering tiles in a totally different way for example using multi-sampling instead of computing coverage analytically (There is an open issue about adding an option for that in pathfinder). I really like the composability of this architecture.<\/p>\n<p>Pathfinder is a very simple, pragmatic, yet fast approach to rendering vector graphics using the GPU. It's not finished, there are many missing features and areas in which it can and will improve. I mentioned rendering strokes, and I think that the performance of the CPU tiling pass could be improved. In its current state it is still a good deal faster at rendering very large and complex SVG drawings than using a CPU rasterizer and uploading the result to a texture.<\/p>\n<p>I'm hoping to integrate it in WebRender and start using it in Firefox some time this year. This is possible thanks to pathfinder's reliance on very few GPU features (any GPU supporting float textures works with pathfinder).<\/p>\n<p>Is Pathfinder the fastest GPU vector graphics approach that there is? Probably not. It picks, however, the right trade-offs to be a very good, if not the best, candidate to my knowledge for integration in a web browser with a small rendering team and a very diverse user base (lots of old hardware to support).<\/p>\n<p>I'll close this post with a few good reads for those who want to further explore different approaches to rendering vector graphics on the GPU:<\/p>\n<ul>\n<li><a href=\"https:\/\/raphlinus.github.io\/rust\/graphics\/gpu\/2019\/05\/08\/modern-2d.html\">A presentation of Piet-metal<\/a> by Raph Levien.<\/li>\n<li><a href=\"https:\/\/wdobbie.com\/post\/gpu-text-rendering-with-vector-textures\/\">GPU text rendering with vector textures<\/a> by Will Dobbie.<\/li>\n<li><a href=\"http:\/\/hhoppe.com\/ravg.pdf\">Random access vector graphics<\/a> paper by Hugues Hoppe and Diego Nehab.<\/li>\n<li><a href=\"http:\/\/w3.impa.br\/~diego\/publications\/GanEtAl14.pdf\">Massively parallel vector graphics<\/a> paper by Francisco Ganacim, Rodolfo S. Lima, Luiz Henrique de Figueiredo and Diego Nehab which follows up on the random access paper with a different data structure.<\/li>\n<li>FastUIDraw technical details <a href=\"https:\/\/01.org\/fast-ui-draw\/blogs\/krogovin\/2016\/fast-ui-draw-technical-details-1\">part 1<\/a> and <a href=\"https:\/\/01.org\/fast-ui-draw\/blogs\/krogovin\/2016\/fast-ui-draw-technical-details-2\">part 2<\/a> and <a href=\"https:\/\/www.youtube.com\/watch?v=2ryvYS47V0E&amp;feature=youtu.be&amp;t=6h08m23s\">XDC2016 talk<\/a>.<\/li>\n<li><a href=\"https:\/\/medium.com\/@evanwallace\/easy-scalable-text-rendering-on-the-gpu-c3f4d782c5ac\">Easy scalable text rendering on the GPU<\/a> by Evan Wallace.<\/li>\n<\/ul>","category":{"@attributes":{"term":"pathfinder, rust"}}},{"title":"Lyon in 2018","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/lyon-2018.html","rel":"alternate"}},"published":"2019-02-17T00:00:00+01:00","updated":"2019-02-17T00:00:00+01:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2019-02-17:\/posts\/lyon-2018.html","summary":"<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p>About a year ago I published <a href=\"https:\/\/nical.github.io\/posts\/lyon-intro.html\">\n\"Introduction to lyon: 2D vector graphics rendering on the GPU in rust\"\n<\/a> on this blog. Lyon was in version <a href=\"https:\/\/docs.rs\/lyon\/0.8.8\/lyon\/\"><code>0.8.8<\/code><\/a> back then and I recently published <a href=\"https:\/\/docs.rs\/lyon\/0.13.0\/lyon\/\"><code>0.13.0<\/code><\/a>.<\/p>\n<p>In 2018 my activity on the project has varied depending on the time \u2026<\/p>","content":"<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p>About a year ago I published <a href=\"https:\/\/nical.github.io\/posts\/lyon-intro.html\">\n\"Introduction to lyon: 2D vector graphics rendering on the GPU in rust\"\n<\/a> on this blog. Lyon was in version <a href=\"https:\/\/docs.rs\/lyon\/0.8.8\/lyon\/\"><code>0.8.8<\/code><\/a> back then and I recently published <a href=\"https:\/\/docs.rs\/lyon\/0.13.0\/lyon\/\"><code>0.13.0<\/code><\/a>.<\/p>\n<p>In 2018 my activity on the project has varied depending on the time and energy I have had left after work and other activities. As it turns out, working on <a href=\"http:\/\/mozillagfx.wordpress.com\/\">getting WebRender shipped in Firefox<\/a> is at the same time amazing and very demanding, and what's left of my brain after a good day of work isn't always up to some of the ambitions I have planned for lyon. Fortunately I am not the only one who contributed to the project, and while progress was slow on the most ambitious plans, I did spend some time on smaller features and polish.<\/p>\n<p>I'll get to these big plans towards the end of this post. In the mean time let's look at some of the highlights of what changed in lyon in 2018.<\/p>\n<h2>lyon_geom<\/h2>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_geom\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_geom\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_geom\/badge.svg\"><\/a><\/p>\n<p>I want to start with an epic contribution from <a href=\"https:\/\/github.com\/kleintom\">Tom Klein<\/a>: The addition of a robust cubic b\u00e9zier intersection algorithm using fat line clipping. You can read about this journey in the original <a href=\"https:\/\/github.com\/nical\/lyon\/pull\/422\">pull request<\/a> and <a href=\"https:\/\/github.com\/nical\/lyon\/pull\/427\">followup improvements<\/a>. Suffice to say, I'm impressed with the quality and rigor of the work Tom put in this feature.<\/p>\n<p>Tom also <a href=\"https:\/\/github.com\/nical\/lyon\/pull\/419\">added<\/a> an elliptic arc to cubic b\u00e9zier approximation (<a href=\"https:\/\/docs.rs\/lyon_geom\/0.12.2\/lyon_geom\/arc\/struct.Arc.html#method.for_each_cubic_bezier\">doc link<\/a>).<\/p>\n<p>There were other additions such as tight bounding rectangle calculation for elliptic arcs, improvements and fixes to the various curve approximation algorithms and a lot of API ergonomic improvements.<\/p>\n<p>This year has confirmed the trend that a number of people are using lyon_geom without the rest of lyon. The way the lyon crates are separated seems to have paid off in letting people who only want curve math tools get a minimal dependency.<\/p>\n<h2>lyon_tessellation<\/h2>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_tessellation\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_tessellation\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_tessellation\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_tessellation\/badge.svg\"><\/a><\/p>\n<p>To me, <a href=\"https:\/\/docs.rs\/lyon_tessellation\/0.13.0\/lyon_tessellation\/struct.FillTessellator.html\">the fill tessellator<\/a> is the most important piece of the whole project. The majority of the changes to the fill tessellator were bug fixes, almost all of them related to dreadful numerical precision issues when paths have many self-intersections and in particular when a lot of these self-intersections are almost at the same position. This type of paths isn't representative of human generated content but the robustness of the tessellator is important to me and I want to keep improving it.<\/p>\n<p>As far as API changes are concerned, I added the possibility to chose the type of the generated indices of the vertex\/index buffer pairs. Before that, indices were always <code>u16<\/code> and some users ran into the limit when generating large amount of geometry with a single path or when tessellating too many paths in the same vertex and index buffer pair. The tessellator now internally works with <code>u32<\/code> indices and the convenience <a href=\"https:\/\/docs.rs\/lyon_tessellation\/0.13.0\/lyon_tessellation\/struct.BuffersBuilder.html\"><code>BuffersBuilder<\/code><\/a> and <a href=\"https:\/\/docs.rs\/lyon_tessellation\/0.13.0\/lyon_tessellation\/struct.VertexBuffers.html\"><code>VertexBuffers<\/code><\/a> output can be parametrized over the index type to provide the choice of <code>u16<\/code>, <code>u32<\/code> or anything else that can be converted to a <code>VertexId<\/code>.<\/p>\n<p>In addition, the <code>GeometryBuilder<\/code> trait and the tessellators are set up to properly handle running out of indices, interrupting the tessellation and returning an error instead of causing a panic as it previously did.<\/p>\n<p>This might sound like a detail but several people ran into it and the way the tessellator used to panic when running out of vertex ids was confusing so I am happy that this is now a thing of the past. My initial worry was that the added glue to forward and handle errors would regress performance (which it initially did by about 6%), but with a small amount profiling and tweaks I got the performance back within noise range of the original scores (on the benchmarks in the repository).<\/p>\n<h2>lyon_path<\/h2>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_path\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_path\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_path\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_path\/badge.svg\"><\/a><\/p>\n<p>This crate has received more attention than usual lately.<\/p>\n<p>The first thing people who update from earlier versions of lyon will notice is probably that <code>lyon::path::default::Path<\/code> is now <code>lyon::path::Path<\/code>. But there have been some more interesting developments than this namespace change.<\/p>\n<p>The <a href=\"https:\/\/docs.rs\/lyon_path\/0.13.0\/lyon_path\/iterator\/index.html\">iterator APIs<\/a> got a pretty major revamp. Previously the various flavors of path iterators would let you iterate over events such as <code>MoveTo(Point)<\/code>, <code>Close<\/code>, <code>LineTo(Point)<\/code> and equivalent curve segments types, in a postscript fashion similar to how the paths are created, in which we don't repeat the start of the event since we already provided it as the end of the previous one.\nThis was simple to implement since it maps to how the path is stored, but pretty much every consumer of the API would have to keep track of both the previous end of segment and the starting position of the curve to do any meaningful work with the segments of the path.<\/p>\n<p>The <code>PathEvent<\/code> enum looked like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">enum<\/span> <span class=\"nc\">PathEvent<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">MoveTo<\/span><span class=\"p\">(<\/span><span class=\"n\">Point<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Close<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">LineTo<\/span><span class=\"p\">(<\/span><span class=\"n\">Point<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">QuadraticTo<\/span><span class=\"p\">(<\/span><span class=\"n\">Point<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">Point<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ control point, to<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ etc.<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>And now looks like this:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">pub<\/span><span class=\"w\"> <\/span><span class=\"k\">enum<\/span> <span class=\"nc\">PathEvent<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">MoveTo<\/span><span class=\"p\">(<\/span><span class=\"n\">Point<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Close<\/span><span class=\"p\">(<\/span><span class=\"n\">LineSegment<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">f32<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Line<\/span><span class=\"p\">(<\/span><span class=\"n\">LineSegment<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">f32<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">Quadratic<\/span><span class=\"p\">(<\/span><span class=\"n\">QuadraticBezierSegment<\/span><span class=\"o\">&lt;<\/span><span class=\"kt\">f32<\/span><span class=\"o\">&gt;<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ etc.<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>In other words, I shifted the burden of tracking this information from the user to <a href=\"https:\/\/docs.rs\/lyon_path\/0.13.0\/lyon_path\/struct.Iter.html\">the iterator<\/a> implementation by making path events contain the actual segments and by providing the closing segment in <code>PathEvent::Close(LineSegment&lt;f32&gt;)<\/code>.<\/p>\n<p>I also removed <code>PathSegment::Arc<\/code> (elliptic arcs automatically get approximated with a sequence of cubic b\u00e9zier curves) and simplified the <a href=\"https:\/\/docs.rs\/lyon_path\/0.13.0\/lyon_path\/iterator\/trait.PathIterator.html\"><code>PathIterator<\/code> trait<\/a> which is now a simple extension trait implemented for all <code>Iterator&lt;Item = PathEvent&gt;<\/code>.<\/p>\n<p>There is also a new <a href=\"https:\/\/docs.rs\/lyon_path\/0.13.0\/lyon_path\/struct.Cursor.html\"><code>Cursor<\/code> API<\/a> which makes it possible to refer to specific positions within a path and work with portions of paths instead of always iterating over the entire path from the beginning.<\/p>\n<p>A <a href=\"https:\/\/docs.rs\/lyon_path\/0.13.0\/lyon_path\/iterator\/trait.FlattenedIterator.html#method.length\">helper to approximate the length of a path<\/a> using adaptive curve flattening was added, although Raph Levien wrote about <a href=\"https:\/\/raphlinus.github.io\/curves\/2018\/12\/28\/bezier-arclength.html\">a faster way to evaluate the length of b\u00e9zier curve segments<\/a> which he implemented in in the <a href=\"http:\/\/github.com\/linebender\/kurbo\">kurbo<\/a> crate. Perhaps some of this good stuff will make its way into lyon as well eventually.<\/p>\n<p>In the long term I want to experiment with more changes to the path data structure, for example making it generic over the vertex type to allow <code>f64<\/code> coordinates and potentially arbitrary per-point attributes (for example one could want to store colors, line width, etc.).<\/p>\n<h2>lyon_algorithms<\/h2>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_algorithms\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_algorithms\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_algorithms\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_algorithms\/badge.svg\"><\/a><\/p>\n<p>A new crate was introduced this year! <a href=\"https:\/\/docs.rs\/lyon_algorithms\/\">lyon_algorithms<\/a> contains a number of path related transformations and algorithms such as <a href=\"https:\/\/docs.rs\/lyon_algorithms\/0.13.0\/lyon_algorithms\/hatching\/index.html\">generating hatching and dotting patterns<\/a>, <a href=\"https:\/\/docs.rs\/lyon_algorithms\/0.13.0\/lyon_algorithms\/splitter\/struct.Splitter.html\">splitting paths<\/a>, <a href=\"https:\/\/docs.rs\/lyon_algorithms\/0.13.0\/lyon_algorithms\/aabb\/index.html\">computing bounding boxes<\/a>, <a href=\"https:\/\/docs.rs\/lyon_algorithms\/0.13.0\/lyon_algorithms\/raycast\/fn.raycast_path.html\">ray casting<\/a> and <a href=\"https:\/\/docs.rs\/lyon_algorithms\/0.13.0\/lyon_algorithms\/walk\/index.html\">walking along a path at constant speed<\/a>.<\/p>\n<p>I wrote most of these algorithms for fun. I don't think I will pursue the same robustness goals as the fill tessellator there (path splitting has some very difficult edge cases when several segments overlap exactly for example), but I think that they are good enough to be useful to a lot of people.<\/p>\n<p>I'd love to add more algorithms there, like boolean operations, path simplification, path smoothing, path interpolation, and so on.<\/p>\n<p>I have used these algorithms to generate procedural shapes and print them with my <a href=\"https:\/\/www.axidraw.com\/\">axidraw<\/a> and it's a ton of fun. Hopefully, some people in the plotting community will find them useful.<\/p>\n<p><img alt=\"Hatching example\" src=\"https:\/\/nical.github.io\/images\/hatching-screenshot.png\"><\/p>\n<h2>Work in progress<\/h2>\n<p>I mentioned at the beginning of the post that I have been making slow progress on two fronts:<\/p>\n<h3>A new fill tessellator<\/h3>\n<p>This work is happening in the <a href=\"https:\/\/github.com\/nical\/lyon\/pull\/334\">new-tess branch<\/a>. The main motivations for this are:<\/p>\n<ul>\n<li>Better robustness against numerical precision issues. In broad strokes, the idea is to organize the algorithm so that it can detect and recover from precision bugs that break the invariants of the algorithm. It is a little hard to describe, but in a nutshell the approach is to accept that some arithmetic will produce results that break the invariant of the algorithm and split iterations of the main loop into an analysis phase where we get a chance to detect the error, backtrack one step and recover from it, and a mutation phase. In contrast the current tessellator interleaves mutations of its internal state with analysis of the geometry in a way that makes it hard to interrupt the iteration and recover if a bad state is detected.<\/li>\n<li>Support arbitrary vertex attributes. Today it is hard to associate external data such as colors or bone weights for animation to each vertex and use it in the output of the tessellator.<\/li>\n<li>Move away from fixed point numbers which the current tessellator uses internally. I originally thought that they would be the key to taming precision issues, but it didn't work out that well, and introduced new issues like a limited range of numbers that the tessellator can represent internally.<\/li>\n<li>Support for more fill rules (even-odd is the only currently supported fill rule in the current tessellator).<\/li>\n<li>Handling quadratic b\u00e9zier curves directly in the tessellator. The tessellator would be able to either flatten curves on the fly during tessellation, or produce a mesh in which the curves could be evaluated in a fragment shader or tessellation shader. This goal longer term than the others, though.<\/li>\n<\/ul>\n<p>So far the new tessellator is able to tessellate all of the non-self intersecting curves I have thrown at it (good thing lyon has a pretty large test suite), but doesn't detect intersections yet, and that's on purpose: ignoring intersections is a great way to mess the internal state of the algorithm up and see if it can recover and continue from there. I'll implement detecting and handling intersections eventually of course.\nI have put no effort in performance yet (will get to that when the new tessellator is close to being usable), it doesn't handle curves and I haven't settled on a way to model the API to support arbitrary vertex attributes when vertices are added during tessellation (again because of self-intersections).<\/p>\n<h3>Higher quality monotone tessellation<\/h3>\n<p>By \"higher quality\", I mean reducing the amount of thin triangles that are generated by the algorithm. Long thin triangles have undesirable properties. For example they tend to produce precision issues when used in certain algorithms like physics simulation, and be <a href=\"https:\/\/www.g-truc.net\/post-0662.html\">slower to render on the GPU<\/a>.<\/p>\n<p>The monotone polygon decomposition approach used in lyon has a tendency to produce long horizontal triangles in some cases. I have a prototype that improves upon this but fails in some cases. To be continued.<\/p>\n<p><img alt=\"Thin triangles illustration\" src=\"https:\/\/nical.github.io\/images\/rustfest\/adv-monotone.svg\"><\/p>\n<h2>Wrapping up<\/h2>\n<p>2018 Was a good year for lyon. In this post I put forth Tom Klein's contribution, but other people also helped get the project where it is today. If your name is on <a href=\"https:\/\/github.com\/nical\/lyon\/wiki\/Contributors\">the contributor list<\/a>, then you are awesome and I thank you.<\/p>\n<p>Hopefully 2019 will be the year where the new tessellator matures and replaces the current one and maybe the start of a small vector graphics rendering crate built on top of gfx-hal.<\/p>","category":{"@attributes":{"term":"lyon, rust"}}},{"title":"2d graphics in Rust discussion - A look at GPU memory management","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/rust-2d-graphics-02.html","rel":"alternate"}},"published":"2018-10-28T00:00:00+02:00","updated":"2018-10-28T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2018-10-28:\/posts\/rust-2d-graphics-02.html","summary":"<p>In this post I'll write about an piece of the low level details of an hypothetical rust 2d graphics crate built on top of <a href=\"https:\/\/github.com\/gfx-rs\/gfx\">gfx-hal<\/a>. Gfx provides a vulkan-like interface implemented on top of vulkan, d3d12, metal or flavors of OpenGL. just like the <a href=\"https:\/\/nical.github.io\/posts\/rust-2d-graphics-01.html\">previous post<\/a> this is in the \u2026<\/p>","content":"<p>In this post I'll write about an piece of the low level details of an hypothetical rust 2d graphics crate built on top of <a href=\"https:\/\/github.com\/gfx-rs\/gfx\">gfx-hal<\/a>. Gfx provides a vulkan-like interface implemented on top of vulkan, d3d12, metal or flavors of OpenGL. just like the <a href=\"https:\/\/nical.github.io\/posts\/rust-2d-graphics-01.html\">previous post<\/a> this is in the context of recent discussions about a 2d graphics crate in rust.<\/p>\n<p>I won't actually write much about 2d graphics specific things this time, because a lot of these low level concerns are agnostic to whether the rendered content is in two or three dimensions. I'll mostly focus on memory management and command submission.<\/p>\n<p>This low level thing I am going to talk about isn't a 2d graphics API that most users would play with but rather a base component on top of which various rendering techniques could be implemented (for example using <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a> or some other approach), and this base component would be independent of these rendering techniques.<\/p>\n<h2>Organizing the input of drawing commands on the GPU<\/h2>\n<p>Let's have a look at <a href=\"https:\/\/github.com\/servo\/webrender\">WebRender<\/a>. Most drawing primitives in WebRender use very simple geometry (axis-aligned rectangles) with shaders of varying complexity that compute directly on the GPU what happens to the pixels covered by the geometry. If you've ever done serious work with GPU, one of your primary concerns most likely was to batch rendering commands and avoid state changes. To render a few thousand rectangles, it would be terribly inefficient to have a loop on the CPU that sets some parameters and kicks a drawing command for each rectangle. So what we do is write a lot of parameters into buffers which are sent to the GPU, and kick a few drawing commands, that will each render maybe thousands of rectangles in one go using instancing.\nThe drawing parameters we write into the buffer contain information such as the position and size of the rectangle in layout space, a transformation to go from layout space to screen space, some flags about whether some anti-aliasing must be done, the positions and sizes of some source images in a texture atlas if need be (for example to apply a texture or a mask), the z-index of the primitive to write into the depth buffer, etc.\nThe vertex shader uses an instance id to find the right information in a per-instance parameter buffer, transforms the geometry (a unit quad) into the right rectangle on screen, forwards some data to the fragment shader and the latter executes the per pixel logic (read from the source textures, apply some effect, write output color, etc.).<\/p>\n<p><img alt=\"gpu memory organization example\" src=\"https:\/\/nical.github.io\/images\/gpu-mem-01.svg\"><\/p>\n<p>This approach is fairly generic, not particular to WebRender (a lot of games do this sort of thing) and works quite well.\nWhat's interesting here is that if you get to write the shaders yourself you have a lot of flexibility in how the input data is organized in GPU memory. You can put all of the parameters for a given instance contiguous together or add levels of indirection, share some common parameters among many instances or even devise your own compression scheme for your data. All that matters is for the CPU code to know how to writes bytes and the shader to know how to find the data in GPU memory and interpret it the right way, and then it is up to you to decide what trade-off to make about simplicity, memory usage and data locality.<\/p>\n<p>I like to think of the problem of submitting commands to the GPU as some sort of encoding\/decoding problem. Got data on one side, some binary representation in GPU buffers and need to read that correctly in the shader. As such, submitting commands is very tied to GPU memory management since it amounts to writing the correct information in the right place.\nIn the purpose of a 2d graphics library, what kind of representation would we want? Well we don't know because the shape the data you write into GPU memory may depend on the details of the rendering technique itself and I mentioned earlier that I want this low level component to be agnostic to that. Some other layer above will deal with it and for now we can focus providing a way to write data into these GPU buffers.<\/p>\n<h2>Dealing with GPU memory allocation<\/h2>\n<p>Let's first have a look at some properties I want from a low level GPU memory management system:<\/p>\n<ul>\n<li>Be able to write commands from several threads in parallel.<\/li>\n<li>Be able to separate memory that is rarely updated from memory that we update often in order to minimize transfer and choose the right kind of memory heap.<\/li>\n<li>The system should be embeddable in another application that uses gfx.<\/li>\n<li>Ideally the shader should not have to care about whether a particular property is static or dynamic.<\/li>\n<\/ul>\n<p>Legacy graphics APIs had a lot of memory management magic done in the driver. Modern APIs such as vulkan move this responsibility to the user of the API (us). Simply allocating a lot of small memory segments has a lot overhead. <a href=\"https:\/\/youtu.be\/zSG6dPq57P8?t=1163\">AMD's recommendation<\/a> is to allocate large chunks of memory segments of 256 MiB and manage sub-allocations within these coarse chunks, others talk about 128 MiB blocks, <a href=\"https:\/\/developer.nvidia.com\/vulkan-memory-management\">nVidia's recommendation<\/a> is to manage all allocations out of as few as possible large contiguous memory chunks.<\/p>\n<p>So we can decide to have these large memory blocks with various allocation schemes within them, from a simple bump allocator to a general purpose fully-featured allocator.<\/p>\n<p>For per-frame data which is overwritten each time, a bump allocator looks like a good fit: It is simple, fast and we can easily write a lock-free one that is usable in parallel. For completely static (as in very long-lived) allocations, bump allocators can also work well since we don't need to worry about fragmentation. The area in the middle is a bit tricker. I don't have a precise definitive allocation strategy to provide here, other than that in my opinion, nesting simple and efficient allocators is the way to go. Group memory allocations into blocks of the same lifetime that get deallocated in one go, and try to keep the complicated parts of memory managements for fewer coarser chunks, also try to group allocations by update frequency. In other words, use specific, simple and deterministic allocation strategies rather than relying on a single complicated one-size-fits-all allocation interface like if you had jemalloc for your GPU. Making such a general purpose allocator is for one very hard, and ensuring good and deterministic performance characteristics is even harder.<\/p>\n<p>This idea of nested allocators is a good fit for something that can be embedded into another graphics engine. For example the coarse allocations could be requested to the embedder and the 2d renderer would manage its own allocations inside of them.\nFor multi-threading this is also good: Some thread-safe allocator can allocate chunks in parallel, and these chunks could be managed independently in single-thread fashion but each on their single thread by a nested allocator that is hard to make thread-safe.<\/p>\n<p>Some allocations are best managed manually (explicit allocation and deallocation), while for some other things, using a cache can be more interesting: Each frame, the CPU side requests that the allocations that are used within the cache stay alive, and if an allocation isn't used for a long time, the cache implicitly deallocates it. The next time the allocation is requested, the cache will politely tell the source of the request that the allocation doesn't exist anymore, a new allocation is made and the data is transfered again. A lot the GPU memory management in WebRender is done that way. Having the right heuristics about when to expire cache entries is not always simple.<\/p>\n<p>So far I talked about allocations in the sense of figuring out how many bytes at which offset to reserve in GPU memory for this and that, but we also want to write into these allocations. Often times people think of allocating and writing into memory as single thing. When writing <code>let five = Box::new(5)<\/code> you both ask the allocator to figure out where the value will be and write the value in memory. But sending data to the GPU isn't that simple. In general you can't assume that the memory you are writing to on the CPU is the one that gets read in the shaders. There are several memory heaps with different characteristics (CPU-visible, GPU-visible, fast\/slow to read\/write on the CPU\/GPU, etc.). In practice this means that for a lot things the data is first written into a staging buffer that is CPU-visible, then copied from there into memory that is fast to read from the shaders.<\/p>\n<p><img alt=\"staging buffer\" src=\"https:\/\/nical.github.io\/images\/gpu-mem-02.svg\"><\/p>\n<p>One strategy could be to work with a large GPU buffer for the shader to read and generally smaller staging buffers into which we write only the parts that have changed. In this scheme the shader gets to read from a single contiguous buffer containing static and dynamic data alike and doesn't have to be aware of that. This is at the cost of copying from the staging buffer for data that we now will only read for a single frame. If a lot of data needs to be updated and read only once each frame, using another type of GPU memory heap that is both accessible to the CPU and the GPU, is slower to read in the shader but depending on how the data is read it might still be faster than the copy of the staging buffer. <a href=\"https:\/\/youtu.be\/zSG6dPq57P8?t=991\">An example<\/a> given for this type of memory heap is particle positions in a game, where by definition we know all of it will change each frame. The downside is that the shader can't pretend it is in a unified address space with the rest, so it isn't agnostic to what is animated and what is not. This might not be a good fit for cases where, say, some of the positions are animated while others are not and it all goes through the same code path in the shader.\nAnother thing to be careful about is that some types of memory heaps use write-combined memory which is ideal to fill the staging buffer but can perform poorly if we don't pay attention to how we write into it. So we have to allocate full aligned multiple-of-cacheline sized chunks and avoid random access.<\/p>\n<h2>What's next?<\/h2>\n<p>Phew. That was a lot of words just for pushing some bytes to the GPU! I merely presented some challenges, proposed certain directions from very far away and haven't even really talked about rendering (the fancy tricks that goes into those shaders, generating the geometry and all).<\/p>\n<p>But I believe this is an important part of the foundation. It is built upon mostly independent pieces and that's already some code that needs writing. Fortunately, this weekend was the first in a while that I had time to sit down and do that so I took one of gfx-hal examples and started writing a few things around it. So far I only have a simple <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/371af479cd743c102487835a74299ac50967cadd\/renderer\/src\/allocator.rs#L4\">bump allocator<\/a>, some <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/371af479cd743c102487835a74299ac50967cadd\/renderer\/src\/writer.rs#L93\">glue to use it and write into memory<\/a> from multiple threads, a simple and dumb <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/371af479cd743c102487835a74299ac50967cadd\/renderer\/src\/allocator.rs#L54\">retained allocator<\/a> for coarse allocations, some <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/371af479cd743c102487835a74299ac50967cadd\/renderer\/src\/gfx.rs\">reexports of the gfx types<\/a> without generics all over the place (since the backend is selected with feature flag), and various <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/371af479cd743c102487835a74299ac50967cadd\/renderer\/src\/lib.rs#L99\">small utilities<\/a>. That's not much, I'm still spending time getting familiar with gfx, but that's a humble start.<\/p>\n<p>I'll end this post with hand-wavey overview of how I see this stuff fitting into the bigger picture:<\/p>\n<p><img alt=\"boring architecture diagram\" src=\"https:\/\/nical.github.io\/images\/gpu-mem-03.svg\"><\/p>\n<p>From bottom to top there is:<\/p>\n<ul>\n<li>A gfx-device that is owned by an embedder.<\/li>\n<li>The embedder can be the default one or some glue to integrate with a specific engine or app).<\/li>\n<li>The low level components contain anything that is mostly independent of the rendering technique, for example a lot of the memory management code that I wrote about in this post. The goal of the low level components is to make it easy to write efficient rendering components without having each of them reinvent the common pieces. Rendering components do the more interesting stuff: They register passes, shaders, and implement fun rendering techniques. An example of rendering component could be a glyph renderer using pathfinder. Another one could be a tessellated polygon renderer that uses lyon, another one could be something that is optimized for rendering many axis-aligned rectangles as is common for UIs. Rendering components inform the command submission system which draw calls are order-independent as well as some global requirements such as depth\/stencil behavior, etc. This lets the low level pieces figure out an efficient batching strategy.<\/li>\n<li>You see on top of that several \"API\" boxes. These take care of high level logic and providing user facing APIs. Each API would have to make different tradeoffs and focus on different use cases, picking whatever rendering components they want to use.\nAs much as possible I would like to avoid compromises outside of the \"API\" boxes which will be potentially high level abstractions.<\/li>\n<\/ul>\n<p>I'm intentionally describing this in very broad terms. The idea behind separating things this way is to be able to experiment with various rendering techniques without starting from scratch each time, and also aim for an extendable architecture if things work out. There is a lot of pieces missing and the boundaries will move as real code gets written but this sets a general direction I am happy with for a low level GPU based 2d graphics library.<\/p>","category":{"@attributes":{"term":"graphics"}}},{"title":"Following up on the 2d graphics in Rust discussion","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/rust-2d-graphics-01.html","rel":"alternate"}},"published":"2018-10-14T00:00:00+02:00","updated":"2018-10-14T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2018-10-14:\/posts\/rust-2d-graphics-01.html","summary":"<p>Raph Levien recently published <a href=\"https:\/\/raphlinus.github.io\/rust\/graphics\/2018\/10\/11\/2d-graphics.html\">A crate I want: 2d graphics<\/a> on his blog, which started some interesting discussions <a href=\"https:\/\/www.reddit.com\/r\/rust\/comments\/9nhhh8\/a_crate_i_want_2d_graphics\/\">on reddit<\/a>. At the same time there is a nascent discussion on the <a href=\"https:\/\/github.com\/draw2d\/rfcs\/issues\/1\">draw2d<\/a> repository (which doesn't have any code at this point) about a potential 2d graphics crate.<\/p>\n<p>These discussions contain \u2026<\/p>","content":"<p>Raph Levien recently published <a href=\"https:\/\/raphlinus.github.io\/rust\/graphics\/2018\/10\/11\/2d-graphics.html\">A crate I want: 2d graphics<\/a> on his blog, which started some interesting discussions <a href=\"https:\/\/www.reddit.com\/r\/rust\/comments\/9nhhh8\/a_crate_i_want_2d_graphics\/\">on reddit<\/a>. At the same time there is a nascent discussion on the <a href=\"https:\/\/github.com\/draw2d\/rfcs\/issues\/1\">draw2d<\/a> repository (which doesn't have any code at this point) about a potential 2d graphics crate.<\/p>\n<p>These discussions contain a lot of interesting comments. One notable thing is that \"2d graphics\" means different things to different people. Some people want to render UIs, some people want to make games with rich vector graphics, some people want to be able to render complex but static SVG documents, some people want something designed for modern GPUs, some people want a library that can be used without a GPU, some want it low level, other want it high level, <em>et caetera<\/em>.\nHaving worked with and on different approaches to 2d graphics rendering, I am convinced that 2d graphics isn't a single problem with an established solution, but rather collection of different problems which are best solved with very different solutions.<\/p>\n<p>Because of that I would like this discussion to branch into several specific topics. In this post I'll talk about 2d graphics for the web and for user interfaces (a case could be made about separating the two of course), to a large extent with the intent to underline how specific the needs of these use cases are. Before I do that I'll write a few words about \"canvas-like\" graphics APIs.<\/p>\n<h2>Canvas, Cairo, Skia, QPainter - The immediate mode painting model<\/h2>\n<p><img alt=\"canvas-like APIs\" src=\"https:\/\/nical.github.io\/images\/canvas-api.svg\"><\/p>\n<p>A lot of the most common 2d graphics APIs look somewhat similar: We have a context object which holds various drawing states like the current transform, pattern, or clip, we have a way to describe paths in post-script fashion (for example <code>context.move_to<\/code>, <code>context.line_to<\/code>, or if we are lucky, actual path objects that can be retained and reused). The general mental model is that you specify each drawing operation in back to front order and pixels are being painted immediately at each operation (or this is what the API pretends) but in practice drawing might be deferred so that the underlying implementation can take advantage of knowing about all of the elements and perform some global optimizations. For example CPU backends tend paint each drawing command individually, but GPU implementations pretty much need to be able to perform global optimizations in order to get acceptable performance. Another important aspect of these APIs is that they don't retain a description of the scene, which means that in order to render interactive content, you will submit the commands again each frame with some modifications for the parts that are changing. A common optimization when using this drawing model is for the user to track which region of the final image has changed and only redraw that part (in Firefox we call it invalidation).<\/p>\n<p>Generally, implementing an efficient GPU backend for a pre-existing canvas-like API has proven to be difficult (doable but difficult). A lot of these APIs were designed before GPUs existed or became what they are now, and often a lot of expensive transformations need to happen between the API and the underlying GPU command submissions.<\/p>\n<h2>Compositors<\/h2>\n<p>When motion comes into play (through animations or scrolling), re-rendering rectangles, paths, text and whatever else is moving at a high frame rate can become expensive with these drawing models. A very common solution to this problem is to group elements that tend to move together and paint them into retained surfaces that are often called layers (at least in the world of web browsers). Scrolling then becomes a matter of moving one or several layers and compositing them together to form the resulting image. This compositing operation is the job of... the compositor. Compositing within an application is very similar to compositing for a window manager, to the point where all modern window managers now provide APIs to let applications delegate the work of compositing their layers to the window manager, which avoids one compositing step, saves cycles, memory bandwidth and power. It is somewhat painful that all platforms expose this functionality in subtly different ways, but I think that it would be a mistake for any new UI toolkit to ignore it if they have a concept of retained surfaces.<\/p>\n<p><img alt=\"Gecko compositor\" src=\"https:\/\/nical.github.io\/images\/gecko-compositor.png\"><\/p>\n<h2>Rendering web pages and UIs<\/h2>\n<p>By now I already gave away some of the details about how a lot of web browsers and UI toolkits work: an immediate mode painting abstraction, on top of which an invalidation system and a compositor were implemented to paper over the difficulty of rendering at 60 frames per second (without draining too much power). This is pretty much how Firefox (and most other browsers), Gtk and Qt have been historically approaching 2d graphics. This model is also to some extent something that Firefox, Gtk and Qt have or are in the process of going away from. I'll get to that in a moment, but before that I want to look at what drawing primitives are important for a web browser and a UI toolkit:<\/p>\n<ul>\n<li>Text. Oh text. Text is of course very important in this context and <em>must<\/em> have a particular look in each platform because a lot of users are bothered when hinting or anti-aliasing in an app doesn't match the look of the rest of the platform. In practice this means a lot of graphics libraries go through great lengths and pain to use the font rendering system of each platform they support. Text is hard. I wont get into these details but the people who implement the myriad of things that happen between loading a font file and the letters of this blog post showing up on your screen are heroes (no self-congratulations, I only touched very small portions of that). Patrick Walton is working on the <a href=\"https:\/\/github.com\/pcwalton\/font-kit\">font-kit crate<\/a> which will hopefully erase some of the pain of dealing with font on each platform. I haven't used it yet but it's something to keep an eye on. Unless you are on a very high dpi screen, sub-pixel positioning and anti-aliasing make text a lot easier and nicer to read. One might decide to only target high dpi displays and punt on these features, but I wouldn't call that an easy decision and it will rule out some use case for sure.<\/li>\n<li>Simple shapes: mostly axis aligned rectangles and rounded rectangles, filled and their outlines.<\/li>\n<li>Very complex clipping scenarios: That one might not be necessary for some UI toolkits, but I'll mention it because clipping is a hard problem when your job is to render web pages. In any case it took quite a bit of trial and error to get that work with all use cases in WebRender.<\/li>\n<li>A few effects like drop shadows and blurs.<\/li>\n<\/ul>\n<p>Notice how I didn't mention arbitrary paths? Of course these need to be implemented in a web browser but without them you can already render a large portion of the web. Any modern UI toolkit also needs to render arbitrary vector graphics to provide resolution independent icons and some types of UI widgets, but the need doesn't compare to the heaps of rectangles and text that compose UIs and web pages.\nSince you still need to support both arbitrary vector graphics and these specific simple shapes, you can simply focus on rendering the complex cases and you'll get the simple case for free, right? Except that in doing so, by not making the overwhelmingly most common case a first class citizen of the system a lot of potential for performance optimization would be lost.\nToday, WebRender doesn't know how to render arbitrary shapes. It's main primitives are (rounded) rectangles and more complex shapes just go through a fall-back mechanism that is part of Gecko and provides WebRender with the resulting content already rasterized. We'll eventually implement path rendering on the GPU but the current situation is good enough for us to ship WebRender first with the fall-back.\nMy understanding is that the situation is similar with Gsk (Gtk's next generation rendering infrastructure): arbitrary vector graphics are rasterized using Cairo on the CPU while great care goes into rasterizing rectangles on the GPU.<\/p>\n<p>Interestingly, for a lot of people path rendering is the central theme when thinking about 2d graphics. My point isn't to state what features are more important than others for a 2d graphics library, but really to stress how different the use cases are and that Rust does not need a single 2d graphics crate, but several, each with different goals and trade-offs.<\/p>\n<p>Speaking of focus, I will now attempt to get my chaotic train of thought together and come back to the topic of web pages and UI toolkit I was writing about a few lines earlier.<\/p>\n<h2>Animation<\/h2>\n<p>I already mentioned motion. It is important enough that browsers and UI toolkits went from a simple \"draw each element directly into the pixels of the window\" model to embedding a compositor and\/or relying on the window manager's compositor to accelerate moving things around. In my opinion, not taking motion\/animation into account is one of the biggest mistakes a new graphics API design can make in he context of UIs (and in many other use cases). Frame N+1 is usually very similar to frame N, and taking advantage of this is key to get good performance and battery usage in rich and interactive experiences. There are different ways in which two frames can be similar. For example a few elements could be added, or all elements could exist in the two frames with different positions. For some APIs the latter might be considered as being two totally different scenes because all elements have changed, for other APIs that retain the structure of the scene it could just be thought of as the same frame with a different array of animation parameters. Whether the latter is superior to the former really depends on what you think the common use cases will be what is worth optimizing for.\nWebRender treats updates with several levels of priority. Scrolling for example <em>must<\/em> be able to operate at 60 frames per second, some larger changes to the structure of the scene can be more expensive to operate and are being carried asynchronously to ensure scrolling remains smooth. This is one of the many solutions to the common problem of having to deal with operations that could blow the frame budget. Another way could be to allow expensive work to be done asynchronously by users of the API prior to submitting rendering instructions. In any case I think that it is important to identify these bottlenecks and design the system in a way that prevents them from hurting frame rate.<\/p>\n<p>In term of API, WebRender is much higher level than a traditional canvas-like API. Instead of building a single frame by submitting drawing commands, consumers of the API build a retained representation made of nested \"display lists\", and several frames will be rendered from this representation when animated properties of these display lists change (for example scrolling, or other types of animations). By squinting really hard one might see the display list building API as a sort of canvas-like API that builds a scene instead of an image, with an added notion of animated properties. But the display list building API itself doesn't have the generalist and flexible graphics API look of a Cairo or a Skia, instead focusing on describing positioned CSS primitives.<\/p>\n<h2>Wrapping up<\/h2>\n<p>At this point my plan was to delve into how WebRender approaches rendering on the GPU in more details and explain in what ways it fundamentally differs from Firefox's previous approach, but I already wrote too many words for a single post. To be honest, I think that WebRender already has the potential to fill the UI rendering niche. Some useful features are missing (for example a full software fallback), but these features are wanted in the long term anyway, so better add them (pull requests are welcome!) than try to replicate the colossal amount of effort that already went into the project.<\/p>\n<p>Let this post be about me trying to convince you that rendering UIs comes with very specific design constraints and requirements, and that other niches which I failed to talk about would benefit from very different solutions. Whenever I have time to sit down and write another post I'll try to explain what I think would be a good direction for an hypothetical low-level crate focused on path rendering on the GPU with an eye for complex and dynamic scenes. Something very different in goal and scope from WebRender (and in some ways complementary). My hope is that I can stir some of the potential \"Let's get together and make a 2d graphics crate\" vibe towards that vision.<\/p>","category":{"@attributes":{"term":"graphics"}}},{"title":"RustFest Paris - Part 2 - Path rendering challenges","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/rustfest-paris-02.html","rel":"alternate"}},"published":"2018-06-19T00:00:00+02:00","updated":"2018-06-19T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2018-06-19:\/posts\/rustfest-paris-02.html","summary":"<p>This is the second part of a series about the talk I gave at <a href=\"https:\/\/paris.rustfest.eu\/\">RustFest Paris<\/a> about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, a crate that helps you render vector graphics on the GPU in Rust.<\/p>\n<p>The recordings can be found <a href=\"https:\/\/app.media.ccc.de\/v\/rustfest18-7-vector_graphics_rendering_on_the_gpu_in_rust_with_lyon\">here<\/a> or on <a href=\"https:\/\/www.youtube.com\/watch?v=2Ng5kpDirDI&amp;list=PL85XCvVPmGQgdqz9kz6qH3SI_hp7Zb4s1&amp;index=7\">YouTube<\/a> if you prefer.<\/p>\n<p>Previous episode:<\/p>\n<ul>\n<li><a href=\"rustfest-paris-01.html\">Part 1 - Intro<\/a><\/li>\n<\/ul>\n<h1>The problem \u2026<\/h1>","content":"<p>This is the second part of a series about the talk I gave at <a href=\"https:\/\/paris.rustfest.eu\/\">RustFest Paris<\/a> about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a>, a crate that helps you render vector graphics on the GPU in Rust.<\/p>\n<p>The recordings can be found <a href=\"https:\/\/app.media.ccc.de\/v\/rustfest18-7-vector_graphics_rendering_on_the_gpu_in_rust_with_lyon\">here<\/a> or on <a href=\"https:\/\/www.youtube.com\/watch?v=2Ng5kpDirDI&amp;list=PL85XCvVPmGQgdqz9kz6qH3SI_hp7Zb4s1&amp;index=7\">YouTube<\/a> if you prefer.<\/p>\n<p>Previous episode:<\/p>\n<ul>\n<li><a href=\"rustfest-paris-01.html\">Part 1 - Intro<\/a><\/li>\n<\/ul>\n<h1>The problem<\/h1>\n<p>Screens tend to have a lot of pixels these days.<\/p>\n<p><img alt=\"screens\" src=\"https:\/\/nical.github.io\/images\/rustfest\/screen.svg\"><\/p>\n<p>To the point that when rendering interesting vector graphics (or rendering anything, really) at a high resolution, the per-pixel work adds up and becomes a real challenge for the CPU to process sequentially. Our goal here is to render complex vector graphics at interactive frame rates (This typically means a 16ms budget per frame) and we'd obviously like to have some processing power left to do other things.<\/p>\n<h1>Filling paths on the CPU<\/h1>\n<p>I am going to use the term \"rasterization\" and \"rasterizer\" quite a bit in this post. <a href=\"https:\/\/en.wikipedia.org\/wiki\/Rasterisation\">Rasterization<\/a>, in a nutshell, is the action of turning vector graphics into raster graphics. In other words it's taking vector graphics and rendering them into pixels. I'll focus on filling paths which is probably the most common primitive, but it's not the only thing vector graphics are made of.<\/p>\n<blockquote>\n<p>What's the deal with GPUs, anyway? I have a beefy CPU, isn't that enough?<\/p>\n<\/blockquote>\n<p>Because images are usually laid out in memory row by row in a contiguous buffer, it's ideal to fill shapes from top to bottom, row after row to maximize cache locality of memory accesses and help the CPU's prefetcher.\nSo it comes without surprise that most path filling implementations use <a href=\"https:\/\/en.wikipedia.org\/wiki\/Sweep_line_algorithm\">sweep-line algorithms<\/a>. The general idea is to start with a list of the path's edges sorted from top to bottom. Imagine an imaginary line (the sweep-line) that traverses the output image a row of pixels at a time. We maintain another list, this one containing the edges that intersect the current row, sorted from left to right (let's call them active edges). During the traversal we use the first sorted list to know which edges to add to the active edge list and when. For each row we go through the active edge list to figure out where to start and stop filling pixels, as well as what to do with pixels that are partially covered.<\/p>\n<p><img alt=\"sweep line\" src=\"https:\/\/nical.github.io\/images\/rustfest\/sweepline.gif\"><\/p>\n<p>There are variations around this algorithm. For example some implementations run the algorithm in a single pass while others will first generate a data structure that represents the spans of pixels to fill and then fill the pixels in a second pass.<\/p>\n<p>Sweep-lines are very useful when dealing with a lot of different geometry problems (2D and 3D alike) I think that I'll come back to what I like so much about them in another post (maybe in part 3).<\/p>\n<p>For now if you are interested in knowing more about this stuff I recommend having a look at <a href=\"https:\/\/searchfox.org\/mozilla-central\/rev\/3737701cfab93ccea04c0e9cab211ad10f931d87\/gfx\/skia\/skia\/src\/core\/SkScan_Path.cpp#106\">Skia's scanline rasterization code<\/a>, or <a href=\"http:\/\/git.savannah.gnu.org\/cgit\/freetype\/freetype2.git\/tree\/src\/raster\/ftraster.c?id=af585ad4fec965fa85f5d61c759f3bc940936de4#n2652\">Freetype's<\/a>. The coding style is different but the overall principle is the same. Oh and since this blog post is written in the context of rustfest, you can check <a href=\"https:\/\/github.com\/redox-os\/rusttype\/blob\/master\/src\/rasterizer.rs\">rusttype's rasterizer<\/a> out too, it's implemented in rust.<\/p>\n<p><img alt=\"scanline fill\" src=\"https:\/\/nical.github.io\/images\/rustfest\/raster.svg\"><\/p>\n<p>There is another approach worth mentioning implemented in <a href=\"https:\/\/medium.com\/@raphlinus\/inside-the-fastest-font-renderer-in-the-world-75ae5270c445\">font.rs<\/a>, which involves rendering information about the outline of the shape in an accumulation buffer and using that as input to fill the shape in a single tightly optimized loop over the destination image. Notable about this approach is the simplicity of the main filling loop. It runs the same logic on all pixels inside and outside of the shape with very few branches which is very efficient on modern CPUs, at the expense of going over pixels that are outside the shape. When rendering very small images this trade-off works wonderfully. When rendering at very large resolutions, having a sparse representation to avoid touching pixels outside of the shape begins paying off.<\/p>\n<p>This is a good segue into an important point: There is no optimal one-size-fits-all (or should I say, one-fits-all-sizes!) solution.\nWhen filling a small amount of pixels, a lot of time is typically spent computing the anti-aliasing along the edges, while paths that cover lots of pixel tend to put more pressure on memory bandwidth filling the interior.<\/p>\n<p>With lyon I focused on large paths covering many pixels, and I wouldn't advise using lyon to render very small text. In another post in this series I will talk a bit about <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a> which implements two algorithms: one for small resolutions (typically text), and one for larger paths.\nI think that there is no way around having dedicated implementations if you want to cover both use cases optimally.<\/p>\n<h1>Overdraw<\/h1>\n<p>We saw how to figure out which pixels are inside a shape and fill them. From there to a drawing containing hundreds of paths the process is usually to render these paths individually from back to front, so that front-most elements don't get overwritten by the ones behind them.\nSimple enough, however this means that for drawings that are built upon many shapes stacked on top of one another like the famous GhostScript tiger, pixels will typically get written to many times. It's quite a shame, because it means that hidden parts add to the rendering cost just as much as the rest even though they do not contribute to the final image.<\/p>\n<p><img alt=\"ghostscript tiger overdraw\" src=\"https:\/\/nical.github.io\/images\/rustfest\/tiger-overdraw.svg\"><\/p>\n<p>The image above gives an idea of the overdraw for the GhostScript tiger. The lighter a pixel is, the more times it is written to with a traditional back to front rendering algorithm.<\/p>\n<p>Where overdraw really hurts is usually memory bandwidth. Unfortunately hammering memory tends to make every thing else slower as well. The other threads end up sitting around waiting for memory which limits parallelism, and after the algorithm is done running, other code will typically run into cold caches. It is very hard to avoid this cost in the context of rasterizing 2D graphics on the CPU (in the best case scenario we have to touch every pixel at least once which is already quite a lot).\nI have to mention a very cool technique that helps a lot here: the \"full-scene rasterizer\" approach which consists in having a single sweep-line that renders all paths at once and therefore can touch pixels only once. The rumor has it that the Flash runtime has such an implementation. See also <a href=\"https:\/\/github.com\/jrmuizel\/full-scene-rasterizer\/\">Jeff Muizelaar's full-scene rasterizer<\/a> which is open-source. This is however quite hard to implement.<\/p>\n<h1>What about games?<\/h1>\n<p>So how do games manage to render so much complex content at interactive frame rates?\nFor a large part the answer is that games almost always use the GPU for graphics tasks. GPU's have been historically designed and optimized specifically for the needs of the games industry. It would be great if we could leverage these hardware level optimizations when working with 2D content.<\/p>\n<p>Now saying that something's going to be fast because it uses the GPU is certainly not enough. It is very easy to do slow things with a GPU, especially when trying to port CPU code over. Rather than try to adapt a CPU algorithm to the GPU let's try to reformulate our 2D rendering problem in a way that corresponds to the type of inputs GPUs typically get.<\/p>\n<p><img alt=\"3D rendering\" src=\"https:\/\/nical.github.io\/images\/rustfest\/3d.svg\"><\/p>\n<p>The vast majority of 3D content in interactive applications is made of triangle meshes. The GPU has dedicated hardware for dealing with triangles which makes this primitive very appealing for us. Perhaps if we turn vector shapes into flat triangle meshes (conceptually like a 3D mesh with z = 0) we can get somewhere, and that's the direction I took with lyon.\nThere are other approaches to rendering vector graphics on the GPU. As I mentioned earlier I don't believe in a one-size-fits-all solution, however I am pretty confident about geometry-based approaches (leveraging the triangle rasterizer) for the use cases I care most about.<\/p>\n<p>Another interesting feature of the GPU's rasterization pipeline is the depth buffer which contains the depth of each pixel in screen-space. This allows games to render opaque objects in any order and reject pixels that are further behind if something closer to the viewer has already been rendered at that location.\nThis is a convenient trick for correctness but it is also a great tool to reduce memory bandwidth, since by rendering opaque objects front to back, one can minimize the amount of time pixels are written to and greatly reduce memory bandwidth (remember that memory bandwidth was a big issue for CPU rasterization). Transparent objects are then rendered back to front since painting order actually matters for them.<\/p>\n<p><img alt=\"z-buffer\" src=\"https:\/\/nical.github.io\/images\/rustfest\/zbuffer.png\"><\/p>\n<p>The illustration above was not in the rustfest presentation but perhaps it will help understanding what I am getting at with the depth buffer savings. This is a trick we use in WebRender that consists in rendering opaque shapes in front to back order with the depth buffer enabled to avoid touching pixels many times.\nThe memory bandwidth savings are actually greater than they seem thanks to smart optimizations implemented in the hardware that allow it to quickly discard entire blocks of pixels at a time before computing their color and writing them to memory.<\/p>\n<h1>Rendering 2D graphics like a 3D game<\/h1>\n<p>Lyon in it's current state is not a 2D rendering engine. It is mainly a way to take vector graphics primitives such as paths, and turn them into triangle meshes in a format that is straightforward to render on the GPU (but lyon doesn't implement the GPU bits at this point). The process of turning paths into triangle meshes is called <em>tessellation<\/em> (some also use the word <em>triangulation<\/em>).<\/p>\n<p><img alt=\"Lyon logo as a triangle mesh\" src=\"https:\/\/nical.github.io\/images\/lyon-logo-tessellated.png\"><\/p>\n<p>If there is a beautiful thing about leveraging the GPU's triangle rasterization pipeline, is that since rendering becomes similar to a video game, we can use the graphics hardware exactly the way it has been meant to be used and benefit from many years of rendering tricks and optimizations from the games industry.<\/p>\n<p>The front to back depth buffer trick I mentioned earlier is not actually something implemented in lyon. It is just a very common optimization in 3D game engines which applies naturally when rendering paths tessellated using lyon. It is also a technique we use in <a href=\"https:\/\/github.com\/servo\/webrender\">webrender<\/a> to great effects, and (spoiler alert) it's also <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a>'s most significant optimization for large paths.<\/p>\n<p>This is only one of the many tricks that we can learn from games. Game developers have come up with interesting approaches to anti-aliasing, various graphics effects, animation, handling thousands of individual objects and many more challenges which we can apply to our own needs.<\/p>\n<h1>\u00c0 suivre...<\/h1>\n<p>This was part two. We had a superficial look at 2D rendering on the CPU and I argued that there are some benefits to picking a games-like approach to rendering on the GPU.\nIn the next post we will delve into lyon's tessellation algorithm itself.<\/p>","category":{"@attributes":{"term":"lyon, rust"}}},{"title":"RustFest Paris - Part 1 - Intro","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/rustfest-paris-01.html","rel":"alternate"}},"published":"2018-06-18T00:00:00+02:00","updated":"2018-06-18T00:00:00+02:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2018-06-18:\/posts\/rustfest-paris-01.html","summary":"<blockquote>\n<p>RustFest organizer: \"Are you ready?\"<\/p>\n<p>Me: \"Almost.\"<\/p>\n<p>(reinstalling Xorg on my laptop 20 minutes before the talk because the window manager would not start)<\/p>\n<\/blockquote>\n<p>I gave a talk about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a> at <a href=\"https:\/\/paris.rustfest.eu\/\">RustFest Paris<\/a>.<\/p>\n<p>The recordings are already online, so you can watch it <a href=\"https:\/\/app.media.ccc.de\/v\/rustfest18-7-vector_graphics_rendering_on_the_gpu_in_rust_with_lyon\">here<\/a> or on <a href=\"https:\/\/www.youtube.com\/watch?v=2Ng5kpDirDI&amp;list=PL85XCvVPmGQgdqz9kz6qH3SI_hp7Zb4s1&amp;index=7\">YouTube<\/a> if you prefer \u2026<\/p>","content":"<blockquote>\n<p>RustFest organizer: \"Are you ready?\"<\/p>\n<p>Me: \"Almost.\"<\/p>\n<p>(reinstalling Xorg on my laptop 20 minutes before the talk because the window manager would not start)<\/p>\n<\/blockquote>\n<p>I gave a talk about <a href=\"https:\/\/github.com\/nical\/lyon\">lyon<\/a> at <a href=\"https:\/\/paris.rustfest.eu\/\">RustFest Paris<\/a>.<\/p>\n<p>The recordings are already online, so you can watch it <a href=\"https:\/\/app.media.ccc.de\/v\/rustfest18-7-vector_graphics_rendering_on_the_gpu_in_rust_with_lyon\">here<\/a> or on <a href=\"https:\/\/www.youtube.com\/watch?v=2Ng5kpDirDI&amp;list=PL85XCvVPmGQgdqz9kz6qH3SI_hp7Zb4s1&amp;index=7\">YouTube<\/a> if you prefer.<\/p>\n<p><img alt=\"lets talk about vector graphics svg\" src=\"https:\/\/nical.github.io\/images\/rustfest\/intro.svg\"><\/p>\n<p>Even though I didn't feel super good about the flow of my speech this time around, I think that the talk was well received and the last minute \"let's fix my window manager\" episode didn't turn into a disaster.<\/p>\n<p>It motivated me to write a series of short blog posts about the content of the talk, and explain in more details the information which I was delivering in a hurry in the hope that I wouldn't blow up the talk's allocated time slice. Most of the images in this series of posts are slides from the presentation (made in SVG with Inkscape), but there will be additional content too.<\/p>\n<ul>\n<li><a href=\"rustfest-paris-01.html\">Part 1 - Intro<\/a><\/li>\n<li><a href=\"rustfest-paris-02.html\">Part 2 - Path rendering challenges<\/a><\/li>\n<li>Part 3 - Lyon's path tessellation algorithm<\/li>\n<li>Part 4 - Other GPU rendering approaches.<\/li>\n<\/ul>\n<p>This post is the introduction of the talk, wherein I introduce vector graphics and try to get the audience somewhat excited about it. Things will get technical in the follow-up posts.<\/p>\n<h1>RustFest<\/h1>\n<p>Before I delve into the talk, I'd like to thank the organizers for their great work on RustFest. I can only begin to imagine how stressful and exhausting it can be to organize such an event and I believe it paid off. I had a great time and I believe the other attendees did as well.<\/p>\n<h1>Raster graphics and vector graphics<\/h1>\n<p>Before I delve into lyon, let's get the terminology straight. Raster graphics is what typically comes to mind when thinking about images: a uniform grid of pixels where the color of each pixel is specified independently. Working with uniform grids has a lot of nice properties, for example having random-access in the content of the image to sample the color at a particular point, and being able to perform complex operations that sort of rely on random access like convolution filters.<\/p>\n<p>On the other hand raster images force authors to think about the resolution at which content is produced versus resolution at which it is presented (the output resolution of a screen for example), and they don't always happen to line up perfectly. So what happens when a 800x450 pixels image has to fill a 2560x1440 pixels screen? In most cases the image will look either blurrier or pixelated. At high resolutions, raster images occupy a lot of space. Image compression formats (png, jpeg and more modern successors) do their best to mitigate that in clever ways but size remains a limiting factor when dealing with large amounts of high resolution raster images, be it in terms of disk pass, or network bandwidth.<\/p>\n<p><img alt=\"slide raster vs vector\" src=\"https:\/\/nical.github.io\/images\/rustfest\/rstr-vctr.svg\"><\/p>\n<p>Fortunately, specifying 2D content pixel by pixel is not the only choice we have at our disposal. In a lot of cases we can author and distribute not the resulting image but the steps to produce it. In very broad terms this is what I refer to when talking about vector graphics.<\/p>\n<p>Think of the SVG format which can be produced with Inkscape or illustrator. With vector graphics instead of specifying a grid of pixel colors you deal in terms of squares, circles, shapes, polygons, b\u00e9zier curves, which you can fill and stroke with different types of patterns such as solid colors and gradients. Of course these shapes will eventually get rasterized into a raster image since that's what your screen understands, but the description of vector graphics allows to a great extent to be resolution-independent and happens to be very compact (since specifying a red square requires a small amount of data no matter how many pixels this square will eventually cover).<\/p>\n<p>Beyond SVG, I consider HTML\/CSS to be a vector graphics format, since it is built around the idea of describing how to display 2D content rather than specifying each pixel individually.<\/p>\n<p>The little shape in the image above doesn't look like much but add many more and you can end up with complex drawings like the famous GhostScript tiger which inevitably appears in any presentation on the topic of vector graphics.<\/p>\n<p><img alt=\"tiger\" src=\"https:\/\/nical.github.io\/images\/rustfest\/tiger.svg\"><\/p>\n<h1>Vector graphics everywhere<\/h1>\n<p>Today graphical applications all make use of vector graphics. Fonts are almost always described with vector formats, user interfaces, just like web pages need to be described in a way that adapts to various layouts and resolutions, a problem that vector graphics lends itself to addressing naturally.<\/p>\n<p><img alt=\"ui slide\" src=\"https:\/\/nical.github.io\/images\/rustfest\/ui.svg\"><\/p>\n<p>Using a vector format to describe maps avoids spending a lot of network bandwidth on all of these pixels and lets you zoom in and out of a map without seeing a blurry mess (unless the application is unable to render the map at interactive frame rate and choses to show you a scaled version of the previous frame while it renders the new one).<\/p>\n<p><img alt=\"maps\" src=\"https:\/\/nical.github.io\/images\/rustfest\/map.svg\"><\/p>\n<p>Using vector graphics in games can be useful as well. Today, 3D and 2D games come with gigabytes of assets, a huge part of it being fairly high resolution textures. This can be very inconvenient when attempting to distribute games over the network or even just fitting the game alongside the other installed apps in a relatively small drive.\nSome games could also take advantage of the resolution-independence to present content at different scales for gameplay purposes or to enhance the story telling.<\/p>\n<p><img alt=\"rpg\" src=\"https:\/\/nical.github.io\/images\/rustfest\/rpg.svg\"><\/p>\n<h1>Vector graphics at 60 frames per seconds<\/h1>\n<p>Turns out that rendering a screen-full of complex vector graphics at an interactive frame rate is challenging. Whether it is on a laptop or a phone, Screens tend to have a <em>lot<\/em> of pixels. Filling this many pixels with interesting content means a fair amount of arithmetic, and involves a lot of memory accesses. To make things worse, the drawing model for 2D content is typically based on the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Painter%27s_algorithm\">painter's algorithm<\/a> which consists in drawing back to front, and this content is usually built upon many overlapping layers. Take a closer look at the tiger above to see what I mean. pixels tend to be written to many times (this is called overdraw), which amplifies the cost of rendering at a high resolution.<\/p>\n<p><img alt=\"screens\" src=\"https:\/\/nical.github.io\/images\/rustfest\/screen.svg\"><\/p>\n<p>As a result of that a lot of applications tend to consider rendering complex vector graphics to be too expensive for high frequency updates and either bake 2D content into textures before releasing the product (a lot of games do that) or architect their rendering tech around hiding this cost, for example by rendering to intermediate surfaces at a low frequency while these surfaces are composited to the screen at a higher frequency, which allows some types of animations stay at a solid 60fps (web browsers in particular do this).<\/p>\n<h1>\u00c0 suivre...<\/h1>\n<p>That's it for part one. In the next post we'll look at how games approach the problem of redrawing the entire screen with complex content at interactive frame rates. We'll see that we can take advantage of these solutions and apply them to rendering 2D vector graphics as well.<\/p>","category":{"@attributes":{"term":"lyon, rust"}}},{"title":"Introduction to lyon: 2D vector graphics rendering on the GPU in rust","link":{"@attributes":{"href":"https:\/\/nical.github.io\/posts\/lyon-intro.html","rel":"alternate"}},"published":"2018-01-22T00:00:00+01:00","updated":"2018-01-22T00:00:00+01:00","author":{"name":"Nical"},"id":"tag:nical.github.io,2018-01-22:\/posts\/lyon-intro.html","summary":"<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p><a href=\"https:\/\/github.com\/nical\/lyon\">Lyon<\/a> is a side-project that I have been working on for quite a while. The goal is to play with rendering 2D vector graphics on the GPU, and it's been a lot of fun so far. I haven't talked a lot about it online (except for a couple of reddit \u2026<\/p>","content":"<p><a href=\"https:\/\/crates.io\/crates\/lyon\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon\/badge.svg\"><\/a><\/p>\n<p><a href=\"https:\/\/github.com\/nical\/lyon\">Lyon<\/a> is a side-project that I have been working on for quite a while. The goal is to play with rendering 2D vector graphics on the GPU, and it's been a lot of fun so far. I haven't talked a lot about it online (except for a couple of reddit threads a year or two ago) so I figured it would be a good topic to get this blog started.<\/p>\n<p><img alt=\"The logo\" src=\"https:\/\/nical.github.io\/images\/lyon-logo.svg\"><\/p>\n<p>In this post I'll talk very briefly about tessellators (lyon's biggest feature) and show a few code snippets to illustrate some of the things you can do with lyon today.<\/p>\n<h2>Tessellation<\/h2>\n<p>Path tessellation (or triangulation), in a nutshell, is taking a path (for example a <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Path2D\/Path2D\">canvas<\/a> or <a href=\"https:\/\/www.w3.org\/TR\/SVG\/paths.html#PathData\">SVG<\/a> path) and approximating it with a set of triangles (like the way we usually represent 3d models but in 2d). While the output of the tessellator is customizable, lyon is pretty much designed for generating vertex and index buffers, which anyone working with low level graphics APIs should be familiar with. As a result we obtain geometry in a format that is very easy to work with on the GPU using the same techniques used for 3D graphics.<\/p>\n<p><img alt=\"tessellated shape\" src=\"https:\/\/nical.github.io\/images\/lyon-logo-tessellated.png\"><\/p>\n<h2>Monotone decomposition<\/h2>\n<p>So how do we go about tessellating a path? The three most common algorithms are <a href=\"https:\/\/www.geometrictools.com\/Documentation\/TriangulationByEarClipping.pdf\">ear-clipping<\/a>, <a href=\"http:\/\/www0.cs.ucl.ac.uk\/staff\/m.slater\/Teaching\/CG\/1997-98\/Solutions\/Trap\/\">trapezoidal decomposition<\/a> and monotone decomposition. In lyon I went for the latter.<\/p>\n<p>Traditionally this algorithm is performed in three passes over the geometry:<\/p>\n<ul>\n<li>The first step is to partition the shape in non-self-intersecting shapes (usually using the <a href=\"https:\/\/en.wikipedia.org\/wiki\/Bentley%E2%80%93Ottmann_algorithm\">Bentley-Ottmann algorithm<\/a>),<\/li>\n<li>then partition these into y-monotone shapes,<\/li>\n<li>and finally tessellate these y-monotone shapes into triangles.<\/li>\n<\/ul>\n<p>I want to come back to this in greater details in another post, but I'll just mention here that lyon's fill tessellator is a bit different from the typical implementation of monotone tessellation in the way it represents paths, and runs the steps above in single pass instead of three. Diverging from the traditional implementations seems to pay off since some <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/53b6eb48f6c01e1ff8cf6c0ce4010c9019d63e39\/bench\/tess\/src\/main.rs#L154\">early measurements<\/a> show lyon to be a bit more than twice as fast as <a href=\"https:\/\/github.com\/memononen\/libtess2\">libtess2<\/a>. Take this with a grain of salt, I do need to measure a much wider range of test cases before I can boast about anything, but it's encouraging and there are still a lot of low hanging fruits on the performance side of things.<\/p>\n<h2>Let's look at some code<\/h2>\n<p>The easiest way to show off some of what lyon can do for you is to look at some code snippets:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">extern<\/span><span class=\"w\"> <\/span><span class=\"k\">crate<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span>::<span class=\"n\">math<\/span>::<span class=\"n\">point<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span>::<span class=\"n\">path<\/span>::<span class=\"n\">default<\/span>::<span class=\"n\">Path<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span>::<span class=\"n\">path<\/span>::<span class=\"n\">builder<\/span>::<span class=\"o\">*<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span>::<span class=\"n\">tessellation<\/span>::<span class=\"o\">*<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">fn<\/span> <span class=\"nf\">main<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Build a Path.<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">move_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">quadratic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">cubic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">close<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">path<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Let&#39;s use our own custom vertex type instead of the default one.<\/span>\n<span class=\"w\">    <\/span><span class=\"cp\">#[derive(Copy, Clone, Debug)]<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">struct<\/span> <span class=\"nc\">MyVertex<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">position<\/span>: <span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">],<\/span><span class=\"w\"> <\/span><span class=\"n\">normal<\/span>: <span class=\"p\">[<\/span><span class=\"kt\">f32<\/span><span class=\"p\">;<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"p\">]<\/span><span class=\"w\"> <\/span><span class=\"p\">};<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Will contain the result of the tessellation.<\/span>\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">VertexBuffers<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">tessellator<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">FillTessellator<\/span>::<span class=\"n\">new<\/span><span class=\"p\">();<\/span>\n\n<span class=\"w\">    <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"c1\">\/\/ Compute the tessellation.<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">tessellator<\/span><span class=\"p\">.<\/span><span class=\"n\">tessellate_path<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">            <\/span><span class=\"n\">path<\/span><span class=\"p\">.<\/span><span class=\"n\">path_iter<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">            <\/span><span class=\"o\">&amp;<\/span><span class=\"n\">FillOptions<\/span>::<span class=\"n\">default<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">            <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">BuffersBuilder<\/span>::<span class=\"n\">new<\/span><span class=\"p\">(<\/span>\n<span class=\"w\">                <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">geometry<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">                <\/span><span class=\"o\">|<\/span><span class=\"n\">vertex<\/span><span class=\"w\"> <\/span>: <span class=\"nc\">FillVertex<\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                    <\/span><span class=\"n\">MyVertex<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">                        <\/span><span class=\"n\">position<\/span>: <span class=\"nc\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">position<\/span><span class=\"p\">.<\/span><span class=\"n\">to_array<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">                        <\/span><span class=\"n\">normal<\/span>: <span class=\"nc\">vertex<\/span><span class=\"p\">.<\/span><span class=\"n\">normal<\/span><span class=\"p\">.<\/span><span class=\"n\">to_array<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">                    <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">                <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">            <\/span><span class=\"p\">),<\/span>\n<span class=\"w\">        <\/span><span class=\"p\">).<\/span><span class=\"n\">unwrap<\/span><span class=\"p\">();<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ The tessellated geometry is ready to be uploaded to the GPU.<\/span>\n<span class=\"w\">    <\/span><span class=\"fm\">println!<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot; -- {} vertices {} indices&quot;<\/span><span class=\"p\">,<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">geometry<\/span><span class=\"p\">.<\/span><span class=\"n\">vertices<\/span><span class=\"p\">.<\/span><span class=\"n\">len<\/span><span class=\"p\">(),<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">geometry<\/span><span class=\"p\">.<\/span><span class=\"n\">indices<\/span><span class=\"p\">.<\/span><span class=\"n\">len<\/span><span class=\"p\">()<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<p>Et voil\u00e0! With a fairly small amount of code you can create a path and generate the vertex\/index buffers that you will be able to easily render on the GPU with glium, gfx-rs, vulkano, OpenGL, or what have you.<\/p>\n<p>From there to pixels on your screen, it can be very simple or very complicated, that's really up to your rendering engine. You can have a look at <a href=\"https:\/\/github.com\/nical\/lyon\/tree\/master\/examples\">the examples<\/a> in the repository to get an idea. Lyon doesn't provide a renderering engine (yet), although it is something that I want to explore eventually.<\/p>\n<h2>What else is there in lyon?<\/h2>\n<p>Lyon's fill tessellator is by far where most of the work went so far. But there are a bunch of other goodies too. There is a stroke tessellator that supports most SVG stroke properties (line caps, joins, etc.), and some specialized fill and stroke tessellators for common\/simpler shapes (circles, rounded rectangles, convex polygons, polylines etc.).<\/p>\n<p>Lyon is split into a few crates, in a way that is transparent for people who use the main crate, but helps with taming compile times and makes it possible for people to hand-pick certain features with minimal dependencies if they wish to.<\/p>\n<h3>lyon::geom<\/h3>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_geom\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_geom\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_geom\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_geom\/badge.svg\"><\/a><\/p>\n<p>Lyon's <a href=\"https:\/\/docs.rs\/lyon_geom\">geom<\/a> module implements a lot of fun math for curve and line segments in 2D (splitting, flattening, intersecting, measuring, etc.) on top of euclid.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">curve<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">QuadraticBezierSegment<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">from<\/span>: <span class=\"nc\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">ctrl<\/span>: <span class=\"nc\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">to<\/span>: <span class=\"nc\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">3.0<\/span><span class=\"p\">),<\/span>\n<span class=\"p\">};<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"p\">(<\/span><span class=\"n\">c1<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">c2<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">curve<\/span><span class=\"p\">.<\/span><span class=\"n\">split<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.2<\/span><span class=\"p\">);<\/span>\n\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">line<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Line<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span>: <span class=\"nc\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">vector<\/span>: <span class=\"nc\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">3.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.5<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">};<\/span>\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">intersection<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">curve<\/span><span class=\"p\">.<\/span><span class=\"n\">line_intersections<\/span><span class=\"p\">(<\/span><span class=\"o\">&amp;<\/span><span class=\"n\">line<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/...<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"n\">curve<\/span><span class=\"p\">.<\/span><span class=\"n\">flattened_for_each<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">|<\/span><span class=\"n\">point<\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ Approximates the curve with a sequence of line segments such<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ that the approximation is never more than 0.01 away from the<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ theoretical curve.<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">approximation<\/span><span class=\"p\">.<\/span><span class=\"n\">push<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">});<\/span>\n<\/code><\/pre><\/div>\n\n<p>If you only need this and like minimal dependencies, just do <code>extern crate lyon_geom;<\/code> instead of <code>use lyon::geom;<\/code>.<\/p>\n<h3>lyon::path<\/h3>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_path\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_path\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_path\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_path\/badge.svg\"><\/a><\/p>\n<p>Lyon's <a href=\"https:\/\/docs.rs\/lyon_path\">path<\/a> module contains path-related data structures and algorithms.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"k\">use<\/span><span class=\"w\"> <\/span><span class=\"n\">lyon<\/span>::<span class=\"n\">path<\/span>::<span class=\"n\">builder<\/span>::<span class=\"o\">*<\/span><span class=\"p\">;<\/span>\n\n<span class=\"c1\">\/\/ The default builder, it supports segments, b\u00e9zier curves and arcs in<\/span>\n<span class=\"c1\">\/\/ absolute coordinates<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">move_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">5.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">quadratc_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">3.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">close<\/span><span class=\"p\">();<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">path1<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ This builder offers the full set of SVG path commands, and translates<\/span>\n<span class=\"c1\">\/\/ them into absolute coordinates since the default path data structure<\/span>\n<span class=\"c1\">\/\/ doesn&#39;t support relative coordinates.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">().<\/span><span class=\"n\">with_svg<\/span><span class=\"p\">();<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">move_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">relative_line_to<\/span><span class=\"p\">(<\/span><span class=\"n\">vector<\/span><span class=\"p\">(<\/span><span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">smooth_relative_cubic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">vector<\/span><span class=\"p\">(<\/span><span class=\"mf\">3.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">vector<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">5.0<\/span><span class=\"p\">));<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">path2<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ This one automatically flattens the path (approximates curves with<\/span>\n<span class=\"c1\">\/\/ a sequence of line_to commands) using 0.01 as tolerance threshold<\/span>\n<span class=\"c1\">\/\/ to build the approximation.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">().<\/span><span class=\"n\">flattened<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">);<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">move_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">));<\/span>\n<span class=\"n\">builder<\/span><span class=\"p\">.<\/span><span class=\"n\">cubic_bezier_to<\/span><span class=\"p\">(<\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.0<\/span><span class=\"p\">),<\/span><span class=\"w\"> <\/span><span class=\"n\">point<\/span><span class=\"p\">(<\/span><span class=\"mf\">2.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">2.0<\/span><span class=\"p\">));<\/span>\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">path<\/span><span class=\"p\">.<\/span><span class=\"n\">build<\/span><span class=\"p\">().<\/span><span class=\"n\">path_iter<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"k\">match<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">PathEvent<\/span>::<span class=\"n\">MoveTo<\/span><span class=\"p\">(<\/span><span class=\"n\">to<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"cm\">\/*...*\/<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">PathEvent<\/span>::<span class=\"n\">LineTo<\/span><span class=\"p\">(<\/span><span class=\"n\">to<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"cm\">\/*...*\/<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">PathEvent<\/span>::<span class=\"n\">Close<\/span><span class=\"p\">()<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"cm\">\/*...*\/<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">other<\/span><span class=\"w\"> <\/span><span class=\"o\">=&gt;<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\"> <\/span><span class=\"fm\">panic!<\/span><span class=\"p\">(<\/span><span class=\"s\">&quot;unexpected curve segment {:?}&quot;<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">other<\/span><span class=\"p\">);<\/span><span class=\"w\"> <\/span><span class=\"p\">}<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ These can be composed, you get the idea...<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">().<\/span><span class=\"n\">with_svg<\/span><span class=\"p\">().<\/span><span class=\"n\">flattened<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ While the builder adapters APIs provide &quot;push&quot;-style conversions<\/span>\n<span class=\"c1\">\/\/ between various path formats, the same kind of operations are<\/span>\n<span class=\"c1\">\/\/ provided in a &quot;pull&quot;-style API with iterator adapters from the<\/span>\n<span class=\"c1\">\/\/ lyon::path::iterator module.<\/span>\n\n<span class=\"c1\">\/\/ This path stores some curves, and the events are flattened on the<\/span>\n<span class=\"c1\">\/\/ fly by the iterator.<\/span>\n<span class=\"k\">for<\/span><span class=\"w\"> <\/span><span class=\"n\">event<\/span><span class=\"w\"> <\/span><span class=\"k\">in<\/span><span class=\"w\"> <\/span><span class=\"n\">path2<\/span><span class=\"p\">.<\/span><span class=\"n\">path_iter<\/span><span class=\"p\">().<\/span><span class=\"n\">flattened<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">)<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"c1\">\/\/ ...<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div>\n\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"c1\">\/\/ Place some dots at a regular interval along a path.<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">pattern<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">RegularPattern<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">callback<\/span>: <span class=\"o\">|<\/span><span class=\"n\">position<\/span>: <span class=\"nc\">Point<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">_tangent<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"n\">_distance<\/span><span class=\"o\">|<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span>\n<span class=\"w\">        <\/span><span class=\"n\">dots<\/span><span class=\"p\">.<\/span><span class=\"n\">push<\/span><span class=\"p\">(<\/span><span class=\"n\">position<\/span><span class=\"p\">);<\/span>\n<span class=\"w\">    <\/span><span class=\"p\">},<\/span>\n<span class=\"w\">    <\/span><span class=\"n\">interval<\/span>: <span class=\"mf\">3.0<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"c1\">\/\/ Place dots 3.0 appart from one another.<\/span>\n<span class=\"p\">};<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">start_offset<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">;<\/span>\n<span class=\"n\">path<\/span><span class=\"p\">.<\/span><span class=\"n\">path_iter<\/span><span class=\"p\">().<\/span><span class=\"n\">flattened<\/span><span class=\"p\">(<\/span><span class=\"mf\">0.01<\/span><span class=\"p\">).<\/span><span class=\"n\">walk<\/span><span class=\"p\">(<\/span><span class=\"n\">start_offset<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"k\">mut<\/span><span class=\"w\"> <\/span><span class=\"n\">pattern<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<p>I would like to evolve this crate into a sort of swiss-army-knife of path manipulations, similar to the features <a href=\"https:\/\/github.com\/paperjs\/paper.js\/\">paperjs<\/a> offers, for example applying boolean operations to paths, computing convex hulls, etc.<\/p>\n<p>Like before, if you only want to play with paths without tessellating themyou can do <code>extern crate lyon_path;<\/code> instead of <code>use lyon::path;<\/code>.<\/p>\n<h3>lyon::svg<\/h3>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_svg\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_svg\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_svg\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_svg\/badge.svg\"><\/a><\/p>\n<p>This module reexports the (very good) <a href=\"https:\/\/docs.rs\/svgparser\">svgparser crate<\/a> and uses it to provide a simple to build a path from an SVG path syntax:<\/p>\n<div class=\"highlight\"><pre><span><\/span><code><span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">builder<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">Path<\/span>::<span class=\"n\">builder<\/span><span class=\"p\">().<\/span><span class=\"n\">with_svg<\/span><span class=\"p\">();<\/span>\n<span class=\"kd\">let<\/span><span class=\"w\"> <\/span><span class=\"n\">path<\/span><span class=\"w\"> <\/span><span class=\"o\">=<\/span><span class=\"w\"> <\/span><span class=\"n\">svg<\/span>::<span class=\"n\">path_utils<\/span>::<span class=\"n\">build_path<\/span><span class=\"p\">(<\/span><span class=\"n\">svg_builder<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"o\">&amp;<\/span><span class=\"s\">&quot;M 0 0 L 10 0 L 10 10 L 0 10 z&quot;<\/span><span class=\"p\">);<\/span>\n<\/code><\/pre><\/div>\n\n<h3>lyon_tess2<\/h3>\n<p><a href=\"https:\/\/crates.io\/crates\/lyon_extra\"><img alt=\"crate\" src=\"https:\/\/meritbadge.herokuapp.com\/lyon_tess2\"><\/a>\n<a href=\"https:\/\/docs.rs\/lyon_extra\"><img alt=\"doc\" src=\"https:\/\/docs.rs\/lyon_tess2\/badge.svg\"><\/a> -<\/p>\n<p>The lyon_tess2 crate is a very recent addition. It provides an alternative fill tessellator that wraps the <a href=\"https:\/\/github.com\/memononen\/libtess2\">libtess2<\/a> C library. I use it mostly to have something to compare lyon against, but as the two tessellators don't have the exact same feature set it can be useful to others as well.<\/p>\n<h3>The command-line app<\/h3>\n<p>The repository contains command-line application that you can use to tessellate SVG paths in your favorite terminal, render paths, flattend paths, fuzz the tessellators, find bugs, generate reduced test-cases, and maybe soon make coffee. The app could be used, for example as a tool in an art building pipeline for a game engine. It's definitely great for debugging lyon.<\/p>\n<div class=\"highlight\"><pre><span><\/span><code>lyon\/cli\/<span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cargo<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>--<span class=\"w\">  <\/span>show<span class=\"w\"> <\/span>-i<span class=\"w\"> <\/span>..\/assets\/logo.path<span class=\"w\"> <\/span>--fill<span class=\"w\"> <\/span>--stroke<span class=\"w\"> <\/span>--tolerance<span class=\"w\"> <\/span><span class=\"m\">0<\/span>.01\n<\/code><\/pre><\/div>\n\n<p><img alt=\"screenshot\" src=\"https:\/\/nical.github.io\/images\/lyon-cli-screenshot.png\"><\/p>\n<div class=\"highlight\"><pre><span><\/span><code>lyon\/cli\/<span class=\"w\"> <\/span>$<span class=\"w\"> <\/span>cargo<span class=\"w\"> <\/span>run<span class=\"w\"> <\/span>--<span class=\"w\">  <\/span>tessellate<span class=\"w\"> <\/span><span class=\"s2\">&quot;M 0 0 L 1 0 L 1 1 L 0 1 Z&quot;<\/span><span class=\"w\"> <\/span>--fill\nvertices:<span class=\"w\"> <\/span><span class=\"o\">[(<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span><span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"o\">)<\/span>,<span class=\"w\"> <\/span><span class=\"o\">(<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span><span class=\"o\">)]<\/span>\nindices:<span class=\"w\"> <\/span><span class=\"o\">[<\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">0<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">1<\/span>,<span class=\"w\"> <\/span><span class=\"m\">2<\/span>,<span class=\"w\"> <\/span><span class=\"m\">3<\/span><span class=\"o\">]<\/span>\n<\/code><\/pre><\/div>\n\n<h2>What's next?<\/h2>\n<p>There are many things that I'd like to see happening in the project, and it will certainly take a long time for most of them to concretise as time is a scarse resource.<\/p>\n<h3>Polish the fill tessellator<\/h3>\n<p>The fill tessellator has grown into something that I am quite happy about. It is not perfect, I definitely want to keep improving its robustness and finish implementing for the non-zero <a href=\"https:\/\/www.w3.org\/TR\/SVG\/painting.html#FillRuleProperty\">fill rule<\/a>, but it's already robust enough for many use cases. For example <a href=\"http:\/\/ggez.rs\">ggez<\/a>, the rust crate to make good games easily, uses it to render polygons, and I know that a few other projects use it to make games and even to render openstreetmaps data.<\/p>\n<h3>A new tessellator<\/h3>\n<p>I want to start working on a new fill tessellator optimized for curves and able to produce a resolution-independent tessellation, probably using trapezoidal partioning like <a href=\"https:\/\/github.com\/pcwalton\/pathfinder\">pathfinder<\/a>. The new tessellator will work best with curves but will not be as good for polygons as a monotone tessellator, so the current tessellator is definitely here to stay.<\/p>\n<h3>A high level renderer on top of lyon<\/h3>\n<p>This was my initial goal when the project started forever ago. As it turns out tessellation was a fascinatingly and hard topic and I decided to focus on it for a while. It would be great to play with a 2D renderer for interactive content (like games and <a href=\"https:\/\/beesandbombs.tumblr.com\/\">creative coding<\/a>) and see what a 2D API designed for your GPU would look like (as opposed to GPU backends for APIs that were designed for CPUs a decade or two ago for static content, which is the state of most 2D APIs these days).<\/p>\n<h3>Documentation<\/h3>\n<p>There was a big documentation push a year ago and it was worth it. Let's do this again.<\/p>\n<h3>Maybe the next feature is going to be your idea<\/h3>\n<p>Or even your next pull request, Who knows?<\/p>\n<h2>Big thanks to all contributors<\/h2>\n<p>Now is a good time to underline that I didn't do all of this work alone. I want to thank again all the <a href=\"https:\/\/github.com\/nical\/lyon\/wiki\/Contributors#contributors\">awesome individuals<\/a> who submitted contributions, big and small, to the project. This project is too large for a single person's spare time, and seeing people come and give a hand is the most rewarding and motivating thing. Also thanks a lot to everyone who is using lyon and reporting bugs!<\/p>\n<p>Want to join the fun? Check out the <a href=\"https:\/\/github.com\/nical\/lyon\/blob\/master\/CONTRIBUTING.md\">contribution guidelines<\/a>, get started on the <a href=\"https:\/\/github.com\/nical\/lyon\/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22\">easier issues<\/a>, and don't hesitate to ask any question on <a href=\"https:\/\/gitter.im\/lyon-rs\/Lobby\">gitter<\/a> or irc in #rust-gamedev.\nI want this project to be as fun and welcoming as possible and I would love it to be more of a team effort than a one man show. If you are running into issues contribting, <a href=\"https:\/\/github.com\/nical\/lyon\/issues\/32\">let me know<\/a>.<\/p>\n<p><img alt=\"lyon stickers photo\" src=\"https:\/\/nical.github.io\/images\/lyon-stickers.jpg\"><\/p>\n<p>There are lyon stickers which is the ultimate proof that the project is cool.<\/p>","category":{"@attributes":{"term":"lyon, rust"}}}]}