
Writing a winning 4K intro in Rust - Dowwie
https://www.codeslow.com/2020/07/writing-winning-4k-intro-in-rust.html
======
smabie
I love the demo scene, but the culture is kind of strange. Like I've been
fooling around with the C64, and all the tools (emulators, debuggers, and etc)
are hosted on source forge, or sometimes this random ftp. The author of the
debugger I'm using proudly proclaims that he only works on it when he's fucked
up on drugs after parties. The documentation of some tools has lewd ascii art,
and etc etc.

I appreciate the anti-corporate vibe and at the same time wish they were a
little more professional. Whatever you think, they're true 80s style cyberpunk
hackers!

~~~
drxzcl
"On the one hand, I found a program that does exactly what we need. On the
other hand, not-quite-dressed anime characters..."

I've had this exact conversation with coworkers before.

~~~
unfunco
I recently explained to someone in an interview that I chose Puppet over
Ansible circa 2014 because by default, Ansible used to output success or
failure messages using cowsay.

~~~
cdmckay
Funny, that would make me want to use Ansible more.

------
fernly
TIL: about the Demoscene[1], "an international computer art subculture focused
on producing demos: self-contained, sometimes extremely small, computer
programs that produce audio-visual presentations. The purpose of a demo is to
show off programming, visual art, and musical skills. Demos and other
demoscene productions are shared at festivals known as demoparties, voted on
by those who attend, and released online."

[1]
[https://en.wikipedia.org/wiki/Demoscene](https://en.wikipedia.org/wiki/Demoscene)

~~~
joan_kode
I'm surprised someone on HN since 2012 would learn about the demoscene today!
Then again, it's true that the demoscene "keeps to itself", it's always been
quite the bubble. I'm not sure how that community could do some outreach, but
I believe a lot more people would find it interesting.

~~~
saagarjha
Something something lucky 10,000

~~~
Perseids
For those not in the know, this is an xkcd reference:
[https://xkcd.com/1053/](https://xkcd.com/1053/)

It's a citation I want to give out surprisingly often.

~~~
rhn_mk1
Important to keep in mind the 10000 is in relation to the population of USA.
On the scale of the whole world it's more like lucky 200000.

------
doctor_eval
I learned programming on the TRS80, and didn’t know about the demo scene until
I was already too busy with other parts of my life; I think I first saw a demo
on the Amiga.

I always feel like I missed out on something transcendental. I think I would
have leaned a huge amount. Instead I had to settle with hacking NewDOS/80
binaries.

I have a huge amount of technical respect for the people who do this stuff.

~~~
nkozyra
I grew up on BBS (started dialing at age ~6)

There were only two types of programming that intimidated me so much I
wouldn't even try: people writing languages from scratch and the demo scene
people. I just sat back and said "nope, I'll never get there."

~~~
doctor_eval
Haha! I wrote a logo inspired language to do graphics programming. It was an
interpreter written in BASIC. You didn’t miss much :)

I also wrote a BBS, so go figure...

------
Torkel
I tried to share the link to this via fb messenger, and it blocked it because
it "goes against our Community Standards".

A while back the same happened to pouet
([https://twitter.com/pouetdotnet/status/1249453524758528000](https://twitter.com/pouetdotnet/status/1249453524758528000)).

Demoscene stuff seems to be good at triggering the filters :)

------
dwaltrip
That intro was very cool! Does anyone have pointers for a fullstack web dev
who is interested in the demoscene (or computer generated art in general)?

I've actually played around a bit with rust [1] (I understand it probably
isn't ideal for demoscence), but I haven't really done any graphics
programming before. I get the feeling it is a pretty deep rabbit hole.

[1] [https://github.com/dwaltrip/advent-of-
code-2019-rust](https://github.com/dwaltrip/advent-of-code-2019-rust)

~~~
laurentlb
In this intro and in almost every modern 4kB intro, the graphics are made in a
shader. To play with shaders, I'd recommend you to look at
[https://www.shadertoy.com/](https://www.shadertoy.com/). Check also Inigo
Quilez's website ([https://www.iquilezles.org/](https://www.iquilezles.org/)),
it has a lot of fascinating content.

~~~
dwaltrip
Thanks for the links! Very helpful

------
int_19h
Kinda surprised about iterators not getting optimized so well. Even in higher-
level languages, this is a commonly utilized optimization opportunity - e.g.
the C# compiler will replace a foreach-loop over an array with an identical
(but faster) for-loop.

~~~
gavinray
There are tricks/an art to Rust's iterator semantics.

One example I know of is that when trying to calculate a dot product, you can
improve the generated code and elide the bounds check only by a very
particular syntax:

    
    
        // Must slice to equal lengths, and then bounds checks are eliminated!
        let len = cmp::min(xs.len(), ys.len());
        let mut xs = &xs[..len];
        let mut ys = &ys[..len];
        let mut s = 0.;
        for i in 0..xs.len() {
            s += xs[i] * ys[i];
        }
    

[https://users.rust-lang.org/t/how-to-zip-two-slices-
efficien...](https://users.rust-lang.org/t/how-to-zip-two-slices-
efficiently/2048/10)

[https://github.com/rustsim/nalgebra/blob/b1b18d17ee64d3fd28b...](https://github.com/rustsim/nalgebra/blob/b1b18d17ee64d3fd28b67ac581d28af4d20ec817/src/base/blas.rs#L334-L342)

~~~
bad-apple
Does it still elide the bounds check if you replace the first three lines with

    
    
        assert_eq!(xs.len(), ys.len());
    
    ?

------
justinclift
Looks nifty. Seems to only compile on Win though:

    
    
      $ xargo run
      For more information about this error, try `rustc --explain E0463`.
      error: could not compile `winapi`.
    

Still, probably good for interest/learning from. :)

~~~
Yuioup
Hm so it's leveraging the Windows API. I thought demos were supposed to be
bare-metal.

~~~
dbrgn
Using the OS is allowed. As far as I know, one of the reasons why there are
more Windows demos than for example Linux, is that Windows provides more
graphics/sound APIs out-of-the-box while on Linux the OS itself does less
you'd have to utilize libraries (which is kind of cheating when doing a 4k
demo).

I think it could be summarized as "write a demo for the target platform as
efficiently as possible". Doesn't necessarily need to be bare metal, there are
JS demos that run in the browser as well. In that case the browser (with all
its APIs) is the target platform.

------
RobLach
This is important art.

~~~
Recurecur
I really enjoyed the artistic part. I wonder if the author was trying to evoke
a Martian atmosphere with the color choices. The contrast of the spheres with
the columns was very nice as well...the perfect, beautiful spheres ascending
into the sky...

I'm not sure if the author is reading this thread, but thanks! :-)

------
zerr
As author mentions, it is non-idiomatic Rust with lots of unsafe's, basically
writing C code with Rust compiler.

~~~
Polylactic_acid
This is not true. Unsafe only disables a few safety features. There are still
a bunch left on so unsafe rust is still more safety checked than C.

~~~
Jhsto
Care to elaborate? What are such safety features?

~~~
Ygg2
The grandparent is wrong. Unsafe doesn't disable safety functions. From the
big book of Rust Unsafety:

The only things that are different in Unsafe Rust are that you can:

\- Dereference raw pointers

\- Call unsafe functions (including C functions, compiler intrinsics, and the
raw allocator)

\- Implement unsafe traits

\- Mutate statics

\- Access fields of unions

[https://doc.rust-lang.org/stable/nomicon/what-unsafe-
does.ht...](https://doc.rust-lang.org/stable/nomicon/what-unsafe-does.html)

The point is, unsafely calling `get_unchecked` is what's bypassing the range
check feature. Not Unsafe itself.

------
hellofunk
I'm a little confused about what's happening here... Rust can run in an OpenGL
shader ?!

~~~
ohazi
This is old and may not even compile anymore, but it's short enough to give
you an idea of what's going on.

[https://github.com/ohazi/opengl-demo-rust](https://github.com/ohazi/opengl-
demo-rust)

GLSL shaders are usually either loaded from files or stored as strings in your
programming language of choice. The OpenGL library or bindings will usually
have some facility to compile those programs and then send them to the GPU,
along with textures, geometry, etc.

------
pan69
Always amazed by what people are capable of doing in 4K.

The music vibe reminds a bit of Brian Eno's Under Stars track from the Apollo
album:

[https://www.youtube.com/watch?v=dcWwtQmAt7E](https://www.youtube.com/watch?v=dcWwtQmAt7E)

------
mmastrac
Cool projects Some Rust macro magic could probably clean up some of that
bounds checking.

------
albertzeyer
Does someone know what the problem is with the intrinsics? Or is there a
problem? The author states that this breaks his debug build for some reason.

~~~
lasagnaphil
I think the author called _mm_load_ps() on a pointer that isn’t 16-bit
aligned. Either change that to _mm_loadu_ps() (which also works on unaligned
pointers but incurs a performance penalty), or make sure your object is
aligned when doing the heap allocation (there’s a STL function called
aligned_alloc() in C++, probably there’s something similar in Rust)

~~~
Twirrim
Why would that only fail on debug builds and not release builds, though? That
seems really strange to me

~~~
cptroot
Debug and release builds probably call slightly different sets of methods, so
they might end up with slightly different heaps. That might be enough to cause
a difference in offset between the builds.

------
readams
How do they view the use of libraries in this competition? Do the libraries
count toward your 4K?

~~~
bane
Basically it has to run on a fairly clean Windows machine. The competition
will usually publish the specifications of the machine ahead of time and
what's on it. What you enter has to fit entirely within the bounds of the
competition, but can use anything else on the machine if it's available. So
you could enter say, a 4kb entry, and use a bunch of Windows .dlls for icons
or something as artwork, but you couldn't enter a 4kb executable and 100MB of
libraries and other stuff.

For some languages where this is _really_ hard to achieve, they'll carve out a
separate category for a language if they think there will be enough entries.
e.g. a Java category where the entry fits with the space limit, but can use
any other library in the default Java classpath, even though that's very very
big. Likewise for different operating systems (Linux, MacOS competitions).

There's been a fantastic resurgence in retrohardware and a category called
"old school/skool" for entries that have to run in MS-DOS -- which can be
ultra hard as you have to code up a lot more of the runtime libraries like
music, graphics rendering pipelines, etc.

------
pjmlp
It looks just great! Congratulations on winning it.

------
classics2
It’s hard to rationalize calling it a “4K demo” when you’re allowed to call
OpenGL.

------
Snelius
Yea, every rust programming is a challenge ;)

