This is a slightly updated version of my first Forth VM implementation from 2015, originally written in JavaScript, now updated to TypeScript. Charlie is named in honour of Charles Moore, inventor of Forth.
Several parts of the VM and core vocabulary are based on @phaendal's mkforth4-js, which evolved in parallel at roughly the same time span and was highly educational. Other parts are inspired by Factor, Popr and other concatenative languages.
The VM & REPL (10KB total) are available online via forth.thi.ng. The project has been online since 2015, but was semi-broken due to CSS layout issues (now fixed).
Related projects resulting from this experiment:
- WebAudio multi-track synth & fx livecoding (from scratch)
- Forth-to-GLSL shader transpiler
- Mini text adventure (directed graph)
- Closures & destructuring
- Vector algebra
- Lisp style cons
- Prime numbers
- Unit conversion
- ASCII art
- FizzBuzz
The following libraries and demos are included (also available in the online REPL):
- lib/audio.fs
- lib/bench.fs
- lib/canvas.fs
- lib/glsl.fs
- lib/list.fs
- lib/math.fs
- lib/swizzle.fs
- lib/synth.fs
The above lib/glsl.fs library contains a Forth -> GLSL cross-compiler, based on word inlining and emulating a stack machine via multiple variables.
The concept was inspired by Brad Nelson's Forth Haiku, however here (as an exercise) the cross-compiler is entirely written in Forth itself...
Demo source: demo/webgl.fs
Usage in the REPL:
( this includes the cross-compiler automatically )
"demo/webgl.fs" include*
Some small examples (more are included in the demo source, also see lib/glsl for available functions):
IMPORTANT: All shader code must be wrapped by glsl> ... ;;
Liquid paint (ported from GLSL)
glsl>
: ti 0.3 * t + ;
: amp 0.6 swap / * ;
: col 3 * sin 0.5 * 0.5 + ;
: i ( x y i -- x' y' i' )
>r over over r@ * r@ ti + sin r@ amp + 1 + -rot
swap r@ * r@ 10 + ti + sin r@ amp + 1.4 - r> 1 + ;
: i5 i i i i i ;
: i10 i5 i5 ;
x 2 * y 2 *
1 i10 i10 i10
drop over over
+ sin -rot col swap col
;; reset
Disco floor (based on Forth Haiku):
glsl>
: stripes 9.5 * sin ;
: fade t * sin * ;
x stripes y stripes *
2 fade
dup 2 fade
dup 3 fade
;; reset
Source: demo/popcorn.fs
Usage in the REPL:
"demo/popcorn.fs" include*
Once all lib files are loaded (give it a few seconds to be sure)...
popcorn
git clone https://github.com/thi-ng/charlie.git
cd charlie
yarn start # start dev server
yarn build # production build (written to /out)