Tuesday, April 23, 2013

Intro to tonal harmonic theory Part 1: Why are there 12 semitones?


Why do we have 12 notes in an octave?


Disclaimer:


This is not a definitive source. Please forgive all the links to wikipedia. I studied physics, electronics and computer science. My understanding of music isn't the same as someone formally trained in, say, western classical music, though I understand enough of it to get by. This represents more an attempt to get across an intuition I've had about the question "Why do we have 12 notes in an octave?". It also acts as a means to test my intuition by actually implementing it. So, I won't bother with historical references, not only because they don't interest me, but since the confirmation to this post is in the code (which is still a work in progress, so I make no claims, etc...) hopefully running in front of you ( if you have the right browser... sorry). I leave the historical referencing and digging to wikipedians and people who are more passionate about that kind of thing. I'm more interested in the types of truths one can confirm through simulation... and music happens to be filled with those...


Introduction


In this post I present an interactive harp using an iterative construction method following a version of the Pythagorean construction method. The construction method will be presented visually rather than mathematically. The source is here if you are interested in the mathematics.

From using the interactive harp it should become clear why there are 12 semi-tones in the modern "chromatic" scale, and some further discussion will show how they became "tempered".

Note though that using some other scheme, or just arbitrarily, you could divide an octave up however you want, with as many notes spaced however you want...

This post specifically deals with the question of the origins of the tempered 12-tone chromatic scale which is most prevalent at any music store or almost standard in any music production software... and to provide an intuitive grasp on the physical origins of the modern tempered 12-tone chromatic scale.

The interactive harp


What follows is a harp made with strings that are "ideal"... meaning strings that might only exist by virtue of mathematics (so no problem for synths). The important attribute of ideal strings is that their harmonics are "perfect"... meaning; the 3rd harmonic is exactly a 3rd of the fundamental wavelength. Real Life strings actually have a 3rd harmonic which is dependant on the mass distribution properties of the string, and is not exactly a 3rd... but more on this later.

Also, these ideal strings are all under equal tension, so only their length need be considered: i.e. Longer strings have a "lower" fundamental (or 1st harmonic), and shorter ones have a "higher" fundamental.

The figure below is playable on browsers that support the Web-Audio-API (Currently only desktop versions of Chrome and Safari).


The figure above starts off as a pretty boring harp. The harp was constructed by taking some base string, and constructing 2 more strings whose fundamentals are the same as the base string's 2nd and 3rd harmonics... which in this case is simply 1/2 and 1/3 of the base length.

The choice of colours for the strings is arbitrary (in this case the hue value is incremented in 12 steps). The string's colour's is mainly a visual means to identify "new" pitches. You will notice that the 1st and 2nd strings are the same colour... this is because 2nd harmonics are so fundamental to music theory that they are assigned the same pitch. The 2nd harmonic also signifies what is known in western music theory as an "octave". Therefore, only the 3rd string will get a new colour... and is therefore the only "new" pitch. Historically, the 2nd harmonic and 3rd harmonic produce the interval referred to as a "5th".

Time to play...


Select a desired western base note with the "Base note" to be the largest string on the harp. Note though that in RL, we can select any base note with any frequency, and the results will look the same. The origins of the western naming scheme is hinted at in the interactive harp, but we'll go more into that in part 2.

What the buttons do:

  • The figure can be reset to its initial state by pressing the "Clear" button.
  • The "Iterate" button does all the magic... but it is quite easy to follow. Basically, it takes any newly coloured string, and doubles the length of that string until it falls within the initial octave's range (the first two red strings). Using the new long string's length as reference, another string is constructed which is a 3rd of that length. This final string will have a new colour, and will be the input for the next time you press the "iterate" button.
  • The "Draw Ln=L0.2n/12; n=0..31 ("tempered" scale with 32 notes)" button does what it says... draws the "tempered" scale as reference. The tempered chromatic scale is what you will commonly find with non-sliding modern instruments (fretted guitar, piano, flute, bassoon, etc...). Specifically here I followed the conventions of concert pitch... which means I arbitrarily specified A4 to be 440Hz. There was no other reason for this choice than to make it relevant to western music theory. More on tempering later.
  • The "Show Note Values" button displays the western pitch codes: (A, A#, B, C, C#, etc..)
  • The "Pentatonic Scale" button resets the harp and iterates 4 times. This produces the well-known and cross-cultural pentatonic scale. The pentatonic scale also contains the musically fundamental major and minor chords, but more on this in part 2.
  • The "Octatonic Scale" button resets the harp and iterates 6 times. This produces the well-known family of major scales (i.e. the Major, Natural Minor, Mixolydian and Dorian scales).
  • The "Non-tempered 12-tone Scale" button resets the harp and iterates 11 times. This produces the well-known chromatic scale. This specific scale is a sub-set of just intonation tuning. You can press the tempered scale button to compare the difference. More on tempering in the discussion.
  • The "Many iterations later" button resets the harp and iterates 52 times. This is to show the limit of this construction method. Any more iterations will over-step the initial chromatic set-up( Non-tempered 12-tone Scale).

Discussion


This version of the Pythagorean construction method can conceivably be performed visually or by ear. Given some basis string, this iterative method will eventually cycle back to somewhere very close to the initial string after 11 iterations (not counting the set-up as an iteration); dividing an octave into 12 (almost logarithmically equal) semitones. Repeated iterations will repeat this cycle every 12 iterations after that until it becomes a bit of a mess... So, in short, the reason there are 12 semitones, is because of the 3rd harmonic... A iterative construction based on the 3rd harmonic will produce 12 distinct bands which appear to "loop" back every 12 iterations. This construction will produce a pattern consistent with the circle of 5ths ( remember, the 3rd harmonic produces a interval on the harp historically referred to as a 5th (More on intervals in part 2))..

Small mathematical detour and tempering...

In Real Life, a string's 3rd harmonic is dependent on many factors, and generally isn't "perfect". Generally the factors string manufacturers take into consideration are tension, length, diameter and mass (length, diameter and mass = mass distribution.). So, is there some different 3rd harmonic that would make this iterative process cause the 11th iteration to loop exactly back to the beginning? The answer is in the definition of the semitone.

The semitone:
An octave is a doubling or halving of length or frequency... so, an "octave" isn't a length, or anything physical. It is a ratio. What we've been doing here is dividing lengths by 2 or 3, and sometimes multiplying by 2. So, the semitone is therefore some value, which if we multiplied some original value by that value 12 times, it would produce exactly 2 times the original value.
So, lets say x is the magic semitone value, then x*x*x*x*x*x*x*x*x*x*x*x*L = x12L = 2L,
or simply, x12 = 2.
Therefore the semitone ratio, x = 21/12.

In 12-toned set-up, the 3rd harmonic would occupy the 19th string from the base string. For 12 equal semitones to exist, instead of the upper 5th being the base note times 3, it should rather be the base note multiplied by our semitone ratio, x, 19 times. Which is x19, or 219/12, which on your calculator would give 2.99661415 (rounded to 8 digits). Notice how that number is damn near 3.

Now, since you can't get a string with a 3rd harmonic which is "perfect", this at least gives one a physically attainable target. By tailoring mass distribution properties on strings and getting close to this target, manufacturers are "tempering" the string to fit into the 12-tone tempered chromatic scale, resulting in superior harmonising. Historical experimentation into the tempered scale often only considered the tuning of the instrument, but modern manufacturing takes into account the physical manifestation of harmonising (tempered string vs. tempered scale), which in essence is resonance. But more on that in part 2.




Thursday, March 14, 2013

Guitar scales interactive.

Hi there.
While I'm making my way back to HTML5 game dev, I thought I'd share some work I did on musical theory.
This is a small interactive HTML5 Canvas guitar scales generator written in JavaScript. For standard guitar set-up, the Tuning Base Note should be set to "E" and the tuning to "Standard".
The scales wrap around, so the pattern doesn't often start on the BaseNote/Key/Root. It basically shows you all notes on the guitar that exist within the chosen scale.
As a exercise, guitarists familiar with bar-chords will can try find the three major chords, the three minor chords and the one diminished chord existing within the E major scale.

Guitar scales

BaseNote/Key/Root:
Scale:
Handedness:
Tuning:
Tuning Base Note:

© Copyright by Petrus J. Pretorius. All rights reserved.

Tuesday, March 13, 2012

Game-play concept for Rogue-Like project.

EDIT(7 July 2013): Code moved to github: https://github.com/zskilz/manband
github.io page not up yet, sorry, been busy. To play download the zip and open manband.html in Chrome or FireFox (Requires webGL).

Ok, so making a fully fledged Rogue-like in three weeks was a bit unrealistic... but considering I didn't know three.js when I started, I think I did ok, though unfortunately I'm one day late on delivering something playable (on Chrome at least).

Here is what is missing, or buggy, from the game-play experience:
  • EDIT: Firefox, weapon sprites not showing... 
  • There is a bug where the  bites from small zombies are ineffectual - I know why, and I will fix later.
  • Inventory management. 
  • The ammo indicator needs a reload display to let you know when you can shoot.
  • Improved passive AI to help avoid structures.
  • Flocking, for group behaviour.
  • Group commands with the right click.
  • A proper map with multiple arenas.
  • Game events - for dialogue, death-screens, etc.
  • Help screen with legend.
The graphics are very debug, but I make no excuses for this... The focus is still game-play. I will only focus on polish once the game-play is to my satisfaction. 

So there you have it. Deadlines are silly, and silly people like me always tend to over-estimate their abilities. To complete the above list I now guess would take maybe another week... but then again it could be two, or three!

Quite a bit of work went into this project so far, and if you cruise the code you'll notice that many parts are still in development and left dangling uselessly, hoping to be used soon. So, much of what you don't see, has some place-holder code waiting to be implemented... but then again lots of code is just plain not there yet.

Next up: As a priority, I will do some bug fixes, and add any improvements to the inventory system since currently the weapon with the highest damage points gets automatically selected, which means that you need to reload and try avoid some pickups to try others. Also, a reset button is desperately needed.

After the important fixes, I suspect the pace of development will slow down since I need to spend more time on polishing my personal website, and to focus on getting possible financing so I can hopefully make games for a living...

Anyway, go check out the game-play demo here

That link again: https://github.com/zskilz/manband

Saturday, March 10, 2012

Game challenge 2 update.

TL;DR: My grand Rogue-like game idea is turning into a zombie shooter... NOOOOooooooo!

I've bitten off more than I can chew and as of today, I broke the combat system, the loot system is in a primitive state, and the team artificial intelligence is, well... let's just say you can't call it intelligent.

I'm busy fixing the combat system to be more projectile friendly... If I don't get it to work I can fall back to the melee-only system whose implementation I'm not happy with. I aim to have a playable demo up on monday, but it will be the equivalent of the 1st week of the 1st project in terms of being presentable. The focus will be on core game-play concepts.

The following sacrifices will have to be made to the great deity of Keeping-timely-dead-lines:

  • Player vs. world only - the AI is still too dumb. 
  • Loot will be kept in it's primitive fps-pickup style of functioning... and since it's single-player, no point in rushing the team loot management.
  • Since the AI is dumb, you going to have zombies, because zombies are dumb... sorry.
  • If any other characters appear, they'll be about as bright as the zombies.
There is currently a nice fluidity to the game-play I hope players will appreciate; in spite of the lack of inspired  graphical representation.



Monday, March 5, 2012

Something completely different

TL;DR: The new project is coming along... one week left!

So, I'm getting along with my Rogue-like project which is currently consuming most of my time. Things are looking better but the game-play isn't near the point where a public presentation is wise. The initial set of characters will be tiny and you can expect about four types of weapons and three types of armour as loot. Coins might make an appearance, but only as upkeep for your army, acting as a pacing mechanism to add urgency. The upkeep rate will also be proportional to difficulty level.

I have settled on microphysics.js to temporarily provide dynamics. I will need more time to properly research physics library options for html5 development. The options are varied and solutions that use CPU or OpenCL acceleration would be preferable.

Anyway, there's the work-in-progress screen-shot and I apologise because it isn't very pretty :
The brave adventurer surrounded by dogs.
Progress on Rogue-like with working title "manband":

  • Adapted terrain example to generate the arenas using Perlin noise. (I'd like to spend more time in a future post on this...)
  • An arena can be defined with a small set of parameters, enabling random generation or defining tile-sets in a JSON file.
  • Basic character class with RPG-related stats.
What's next?
  • microphysics.js sphere/AABB limitation limits structure placement to axis-aligned orientation only. 
  • Terrain dynamics will have to be faked - abstracting dynamics to spheres-on-a-plane and setting the sprite heights directly from the terrain's data.
  • Character dynamics and passive AI.
  • Loot management.
I plan to use dat.gui for tweaking character parameters during testing and for the loot management system.

Till next time...

Bump in page-views.

TL;DR: Some people came to look at my blog, and now I'm blogging about it...  yeah.

My blog received a welcome boost in views when kineticjs referenced my first personal game challenge which used their library... Thank you kineticjs.

What this whole experience has opened my eyes to is the power of market-specific references. Being referenced on a site that deals with specialist information attracts a considerably larger audience than posting about it on google+ or facebook if you're not known in your field.

Meanwhile, in unrelated news...

Thursday, February 23, 2012

Graphics test.

TL;DR: Canvas character sprite experiment here.

Since I haven't set up my server to properly serve the compiled JavaScript as static files yet, I'm not getting any 304 codes when serving my JavaScript files. This is a problem since the above demo relies on three.js, which takes up about 200kb (webGL+Extras)... Quite a bit to load, and I should really get the compiled files in the right place on my server so they can be loaded statically, and give a 304 if a cached version is found on the browser. This will mean only the first page load will be slow. Consequent loads will be much quicker.

It's also for this reason that I would not dare include the script references in this blog, since it would just slow down the loading of the blog way too much.

Anyway, go check out my experiment.... It shows what any Rogue-like needs... lots of character(s)! Ha ha, ha... ha.

A warning to other programmers writing graphics tests: The problem with writing graphics tests is that they can become quite hypnotic, and if you're not careful you can spend almost as much time staring at it like a mesmerized fool as you do actually implementing it...