Some Bits: Nelson's log

4 posts in August 2021

2d noise functions

Somehow I’ve done generative art experiments for 30 years without every really understanding noise functions. I mean I’ve certainly used some but never directly, generally by incorporating someone else’s noise-derived textures or something. So here’s some notes.

Noise functions

Processing’s noise function is probably how most generative artists first encounter noise. It is straight up Perlin noise, the classic 1985 algorithm. It’s defined for any number of dimensions but let’s just focus on 2D noise for now. You give it an x, y and it gives back a random number 0-1. The key feature of Perlin noise is it’s smooth; two x, y points near each other will have a similar value. Note there’s an implicit scale in Perlin noise; is (100, 100) “near” (0, 0)? Or do you have to go as close as (10, 10) or (1, 1)? This scale factor is not very interesting but you do want to dial in a scale that has features of the size you want. Perlin noise implementations often provide other tuning like how many octaves to calculate and how much each contributes.

https://64.media.tumblr.com/b62a80853b5aa8509c95c25cf3dc9b6d/tumblr_inline_pc0ohslzM81seaucq_500.png
Top: Perlin. Bottom: Simplex. Source

Perlin noise has a problem in that it’s somewhat directional; you can see horizontal and vertical artifacts in the top 4 images above. (Taken from this blog post). The bottom 4 images are similar treatments of OpenSimplex noise. Simplex noise is a different algorithm Ken Perlin made in 2001; see here for an explication. Unfortunately Simplex noise has some worry about a patent (expires January 2022!). So that’s why there’s OpenSimplex: it has similar features but was designed to be avoid the patent. (Patents on math: so stupid.) In addition to being isotropic both kinds of simplex noise are also faster to calculate.

FastNoise is really a collection of different noise functions with an emphasis on fast implementations. Includes Perlin, Simplex, and a bunch of other choices. The project is ambitiously multi-language and has several iterations as the author has supported SIMD first and then rewritten everything as FastNoise 2. Note the author Jordan Peck works on No Man’s Sky, one of the most ambitious procedurally generated videogames out there. It’s full of noise functions.

There’s a bunch of other noise functions out there too. Worley noise, Fractal noise, Gabor noise... It’s like after Perlin got an Oscar for his noise function everyone wanted their own ;-) There’s also a lot of work in making fast implementations, running on GPUs, etc. I’m getting in the weeds now so I’m just going to look at some simple things to use with Python implementations.

Python implementations

perlin-noise, a basic Python implementation of Perlin noise. Works with any number of dimensions.

OpenSimplex has a nice Python implementation with tests and everything. It defines 2d, 3d, and 4d functions.

noise, a native code implementation of Perlin noise and true Simplex noise. 1-3 dimensions for Perlin, 2-4 for Simplex. Also includes a GLSL implementation for shaders that I did not test. This code is mostly 9 years old! But there’s no reason that should matter for something this simple. Note it has no API support for setting a seed. You can override the entire random integer function though which would let you also control seeding.

pyfastnoisesimd is a SIMD optimized, parallelized implementation of FastNoise. There’s no simple API for generating a single sample; it’s designed to generate large grids of numbers all at once (very quickly).

I’m currently using OpenSimplex in my projects, mostly because it’s the first library I found. It’s easy to use and fast enough for me.

Benchmarks

I don’t really much care about speed in my applications but I was curious, so here’s some simple timeit statistics to generate a single 2d noise sample.

Constant
50000000 loops, best of 5: 0.00469 usec per loop
math.random()
10000000 loops, best of 5: 0.0359 usec per loop
OpenSimplex
100000 loops, best of 5: 2.34 usec per loop
perlin-noise with 6 octaves
5000 loops, best of 5: 90.6 usec per loop
noise.pnoise2
5000000 loops, best of 5: 0.1 usec per loop
noise.snoise2
5000000 loops, best of 5: 0.0844 usec per loop

So there you have it. About 0.1 microseconds per sample for the C implementations, 2.3 for OpenSimplex (Python), 90 for Perlin (Python). To it it another way, that’s roughly 10M samples a second for the C code. For comparison pyfastnoisesimd says it’s a few nanoseconds / sample, or 200M+ samples / second.

Using noise for art

Noise functions are just random number generators; how do you make art with them? Ha, as if there were a simple answer to that question.

I did make one simple demo that a zillion people have done; making a grid of OpenSimplex noise and then visualizing the number with a short line segment rotated by the noise value. You have to fiddle the scaling to get it to look interesting. Here’s a result that looks pretty nice plotted, although drawing all ~5900 line segments took 90 minutes.

Another classic plotter use of noise is to draw “flow fields”. It’s a simple physics simulation; you drop a particle at a point and then interpret the noise value as an angle of force. Then you draw the trace of the particle as its buffeted around your grid. I’ll probably do that next, it’s a classic with a lot of interpretations.

Seeds

An aside on seeds. It’s nice to use words as seeds instead of numbers. There’s a zillion ways to do that but one easy way to turn a string into an int is zlib.crc32(seed.encode('utf-8')). Note that’s a 32 bit int; 64 would be nicer. Oddly there are precious few 64 bit checksum and hash functions, I don’t think any are installed into Python by default.

Benchmark script

#!/bin/bash
TIMEIT='python3 -m timeit -p -u usec '

echo 'Constant'
$TIMEIT '0.13'

echo 'math.random()'
$TIMEIT -s 'import random' 'random.random()'

echo 'OpenSimplex'
$TIMEIT -s 'from opensimplex import OpenSimplex; os = OpenSimplex()' 'os.noise2d(1.1,1.1)'

echo 'perlin-noise with 6 octaves'
$TIMEIT -s 'from perlin_noise import PerlinNoise; pn = PerlinNoise(octaves=6)' 'pn.noise([1.1, 1.1])'

echo 'noise.pnoise2'
$TIMEIT -s 'from noise import pnoise2' 'pnoise2(1.1, 1.1)'

echo 'noise.snoise2'
$TIMEIT -s 'from noise import snoise2' 'snoise2(1.1, 1.1)'

Windows and High DPI / Retina

It’s better than it used to be!

I’ve been thinking how nice it’d be to have a higher DPI screen. My current monitor is 109 dpi which is just low enough that I can run things at 100% scaling and it’s all readable. (Sometimes I bump the font size up +1 on things). But I’d love to get a 200 dpi or higher screen so everything looks crisper. This works great on MacOS but historically has been a mess on Windows, in large part because sometimes you are running 20 year old code that is rendering pixels on its own and is totally DPI unaware. But things have improved.

The testing below is with Windows 21H1. I learned a lot from this blog post which explains how to configure Windows high DPI, in particular how to override settings on a per-app basis. I haven’t needed to do that but it’s nice that it’s an option.

I set Windows to 125% scaling and tried a bunch of things. For me my metric of “works OK” is “readable” and “works right” is “readable and not blurry”. Example blurry window to the right. (Note that the app itself works right; only the installer is blurry.)

Most of the apps I use just worked right. A few had to be restarted; they were blurry or in the case of Steam just didn’t work right at all. A few apps were slightly blurry: not “pixel scaled 125% blurry” but more like “awkward font size”, maybe just something not quite optimized. A few older apps worked but were blurry like 125% pixel scaling: Audacity 2.3.3, NZBGet 21.1 (Win UI), SFTP Net Drive. The only thing that was consistently blurry was NSIS, the Nullsoft installer system a lot of software use. There might be a fix package builders can use. Don’t much care anyway, you run an installer once and forget about it. I didn’t test very many games, most games are fully doing their own thing with rendering anyway so I expect they are unaffected by the DPI setting in Windows.

I was honestly surprised at how much did work perfectly. So that impressed me. 125% scaling works almost everywhere in Windows now. None of it feels quite perfect and there are some rough edges but then that’s typical of the Windows UI experience in general. It’s fine and totally usable.

Microsoft has put more thought into display scaling than I reazlied. This helpful developer doc shows the evolution; there was reasonable support starting in Windows 8.1. Windows 10 1703 stabilized on “Per-Monitor V2” with various APIs. The part that surprises me is “Desktop applications must tell Windows if they support DPI scaling”: without that Windows just bitmap-scales and makes for bluriness. I’m surprised almost all the apps I tried are apparently DPI scaling aware. It seems to work even with very old Win32 APIs, you don’t have to use fancy new UWP apps to get scaling. This guide makes it sound not very hard to write basic scaling-aware apps although it does take some extra work to do it nicely.

There is a way to inspect the scaling-awareness of running apps. Oddly a couple of apps (Everything, the PowerToys launcher) say they are “System” status which means basically unaware and yet they look right on my screen. There are a few apps that are fully “Unaware” but they are mostly things like Steam that seem to have their own bizarre rendering for everything.

One thing I can’t tell easily is if the apps are non-blurry because they aren’t scaling at all. I think PingInfoView may be like that; it says it’s “System” scaling but the window was non blurry and the font seemed too small. But the difference from 125% to 100% is not easy to be sure about. I’d care a lot more if I’m running at 200%.

I wish I had a simple program that called the various APIs for inspecting display characteristics and just showed me the info. I guess I could write one.

Higher DPI monitors

Anyway the software mostly seems to work. Now I need the hardware. I currently have a 34″ 3440x1440 monitor that I bought for about $1000. I like it very much. It’s 31 x 13 inches for 109 dpi. There are a bunch of higher density displays but they get pretty pricy.

The Dell UltraSharp 32″ 8K gives you 7680 x 4320 at , the calculator says that’s 275 dpi. $3750 is a little more than I had in mind though.

5K monitors may be more reasonable. Here’s a couple, the first is pretty much a straight DPI upgrade on my existing screens ize.

LG 34″ 163 dpi, 5120x2160, 32″X14″, $1224.
LG 27″ 218 dpi, 5120x2880, 24″x15″, $1600.

Newegg has a lot of choices for 4k gaming monitors, some 16 at 3840x2160 (for a 16x9 aspect ratio).

Looking at this another way... a 43″ 3840x2160 monitor is a pretty common size for $1300 or so. That’s 105dpi, so basically I’d get a bigger monitor at the same dpi. Not interested. To go higher density there’s 32″ 3840x2160. That gives 138 dpi, or about 25% more pixel density. These monitors are 27″x15″ and I’d definitely the loss of width.

What would be a clear DPI upgrade on what I have now is a 5120 x 2160 monitor. That gets me back to that LG 34, I think it’s the closest to a direct dot density upgrade. It’s one of only two monitors in this size; the other is the MSI PS341WU.

The other thing I should consider is pixel depth; 10 bits is common now although I don’t know of any software supports it. And also refresh rate; I like my GSync up to 100Hz. The LG 34″ that looks like a good match for me is 10 bit and supports 75 Hz. No indication of GSync or FreeSync support though. The MSI monitor is 60Hz only.

Just for fun, Apple’s Pro Display XDR is 6016 x 3384 for 218 dpi at $5000 (!). The screen is 28 x 16″. I can’t find anyone selling another brand with this panel.

Bottom line, the LG 34WK95U-W looks like the best option for me and a fairly unique one at that. $1224 on Amazon is not a lot but I don’t think it’s a big enough upgrade to warrant replacing my existing monitor.

Dyson Sphere Program

I just finished a first playthrough of a really great early access game, Dyson Sphere Program. I don’t normally talk about games here but this game is so much like programming it seems relevant. Also it’s pretty and it’s fun.

DSP is a Factorio clone. Or to be more fair, a “factory automation game” since it’s now kind of a genre. But DSP is a lot like Factorio and it’s quite apparent when you play.

The big innovation is that it’s a lot more beautiful, as the screenshot above demonstrates. Full 3d graphics. And it’s not just a gimmick; not only does it look great but it performs well. And you even play in 3d a bit, the conveyor belts can be woven at different altitudes letting you make some nice bus designs. Also planets are actually spheres which has some implications.

The other big change is that it’s a multi-planet game. You start out building a factory on a single planet but there’s resources you’ll need to go to another planet in your system for and later on, you’ll bring in rare resources from other stars. Honestly this doesn’t add a lot of complexity but it does add some beauty and variety. (There’s a good Factorio mod called SpaceX that creates something similar.)

And the third big change is there’s a grand goal, swallowing the sun in a Dyson Sphere to generate power. You can see my nearly completed sphere rising over the planet in the picture above. The Sphere gives a purpose to all the construction that’s a bit more tangible than Factorio’s “build a rocket”. Also it’s real pretty and makes a useful power resource when it’s complete.

One nice improvement in DSP is a lot of quality of life stuff, UI improvements that make building things easier. OTOH the game is still in early access - the blueprint system only was released a week ago and has some rough edges. One of my favorite features is the devops dashboard, er, the production monitoring graphs. Here’s some details of the growth of my empire over the 65 hours it took me to win.

The game is really impressively implemented. It’s simulating a lot of individual components. And rendering them in 3d. It runs smooth on my fairly high end PC with a 1080Ti GPU. I read somewhere the Dyson sphere components themselves, tens of thousands, are being simulated with GPU code. Makes sense. Folks complain that this part greatly slows their PC but I didn’t have any trouble at all; maybe an artifact of how beefy a GPU they have.

The game is still early access and is missing some things I’d like to see. Some UI for monitoring and controlling the logistics network would be nice, it plays a bigger role in DSP than Factorio. It’d also be nice to have more game systems to design; there’s no analog to fluids or trains, for instance. Also the DSP folks have promised to add some defense / military aspect of the game. I’m fine with a peaceful builder but it could be interesting to have the challenge. Finally there’s no multiplayer, not even one promised, that seems like a mistake to me.

There’s a small but active mod scene for the game. No official mod support yet but the game is in Unity which is fairly amenable to hacking. There’s a few resources for writing your own mods. One point of confusion; there’s a global scoreboard called the Milky Way and various rumors that some mods keep you out of it. I asked on the Discord and was told there’s no whitelist or anything. Instead the game has its own cheat protection, it inspects its own data structures and if something modified them (say, a mod) then you are disqualified. That means info-only mods are OK and it’s determined by behavior. Unfortunately there’s no published list or info on which mods are allowed or not, you have to guess.

It’s a good game!

GAN art

My friend Tom has been playing with GAN art, AI generated images. Thanks to him I was able to try out a working system; you just provide a text input prompt and out pops some art. I don’t really know how it works, something along these lines apparently. keywords: VQGAN, CLIP. The results are awfully neat though.

Update: you can play with it yourself in this notebook. No support provided, sorry.

Anyway I played around with it. Literally all I did was provide some text prompts, all the art is coming from the software. Which raises an interesting question about artistic input. I give the large majority of the credit to the folks who developed these techniques and trained the networks. But there’s a lot of skill in tuning the systems (something I think Tom is expert at). Of course the original image input creators have an influence too but when your input set is literally all images on the Internet, well, the credit gets a bit diffuse. A lot of these images are kinda samey but by no means are all of them. I imagine there’s a lot of latitude in how you train and tune these things.

Technical notes: it’s a giant pile of Python software with PyTorch as a big piece, also OpenAI CLIP. It’s running on Google Colab with a GPU at a free level so presumably a modest amount of compute resources. The small images take about 5 minutes to generate, the slightly bigger ones take 10.

Here’s the images I made. This is all of them, so you can see failures as well as success. I’m putting the ones I like first.

Known Unknowns

De Chirico landscape
Yves Tanguy
Australian aborigine art
church pixel art
Gay Orgy
Gay Orgy #2
Homosexual Party
Statue of Narcissus
Malevich square
Classic male nude bathing
Water slides
Rotten banana
Dyson sphere
Has Anyone Really Been Far Even as Decided to Use Even Go Want to do Look More Like?
When the moon hits your eye like a big pizza pie