Saturday, 9 April 2022

Tokenisation

In this post I demonstrate how one can take a character input stream and generate tokens. Tokens generated can be used for another stage. The next stage might be to compile your own language, to parse CSV files. My tokeniser simply serves as a starting point.

In This Post


Top

What is tokenisation

Simply put, tokenisation, takes a character input stream and outputs tokens.

Tokens might include numbers, identifiers that may be part of a programming language, and so on. Essentially, a tokeniser groups characters into more meaningful constructs.

Assume a given character stream contains the characters

int x = 22

A tokeniser would recognise 'int' as an identifier (or word). The same can be said about 'x'. The '=' (Equals) symbol would be recognised as a special symbol. The digits '22' would be recognised as a number. In short, the tokenised output for the supplied text might be...

Identifier:Identifier:Special:Number

Top

Tokenisation Project

The project is a NET 6.0 console application. The default namespace is Lex.V1.

Token Types

Token types, (numbers,identifiers, special characters, etc) are listed as an enumeration. This ensures client(s) (e.g. parser) can switch on token types required.


namespace Lex.V1
{
  public enum TokenType
  {
    Eof,
    Error,

    IsValidToken,

    Comma,
    LeftParen,
    RightParen,
    LeftBrace,
    RightBrace,
    Colon,
    Semicolon,

    Equals,
    EqualsEquals,

    Plus,
    PlusEquals,
    PlusPlus,

    Identifier,
    Integer,
  }
}
Top

The Tokeniser Class


using System.Text;

namespace Lex.V1
{
  /// <summary>
  /// Class to turn a character stream into tokens.
  /// </summary>
  public class Tokeniser
  {
    private const char Eof = char.MinValue;

    private readonly TextReader _reader;
    private readonly StringBuilder _text = new();
    private char _char;

    public UInt64 Integer { get; private set; }

    public string Text =>
      _text.ToString();

    /// <summary>
    /// Need a way to read characters from a text stream.
    /// The TextReader class seems suitable.
    /// </summary>
    /// <param name="reader"></param>
    public Tokeniser(TextReader reader)
    {
      _reader = reader;

      // Require lookahead of one character.
      _char = ReadChar();
    }

    /// <summary>
    /// Eat whitespace and return next token.
    /// Return Eof, if at end of character stream.
    /// </summary>
    public TokenType Next()
    {
      // Ignore whitespace.
      if (char.IsWhiteSpace(_char))
        EatWhitespace();

      if (_char == Eof)
        return TokenType.Eof;

      // Clear text for each token run.
      _text.Clear();

      // Identifiers are most common, try them first.
      if (char.IsLetter(_char) || ('_' == _char))
        return BuildIdentifier();

      // Check if digit and parse a number.
      if (char.IsDigit(_char))
        return BuildNumber();

      // default token type is an error.
      TokenType tt = TokenType.Error;

      // Generate token types from characters that are not identifiers or numbers.
      switch (_char)
      {
        case Eof: return TokenType.Eof;
        case '(': return Special(TokenType.LeftParen);
        case ')': return Special(TokenType.RightParen);
        case '{': return Special(TokenType.LeftBrace);
        case '}': return Special(TokenType.RightBrace);
        case ',': return Special(TokenType.Comma);
        case ';': return Special(TokenType.Semicolon);
        case ':': return Special(TokenType.Colon);

        case '+':
          tt = Special(TokenType.Plus);
          if (_char == '=')
            return Special(TokenType.PlusEquals);
          if (_char == '+')
            return Special(TokenType.PlusPlus);
          return tt;

        case '=':
          tt = Special(TokenType.Equals);
          if (_char == '=')
            return Special(TokenType.EqualsEquals);
          return tt;
      }

      _text.Append(_char);
      return TokenType.Error;
    }

    private char ReadChar()
    {
      int result = _reader.Read();
      return (-1 == result) ? Eof : (char)result;
    }

    private void EatWhitespace()
    {
      while (char.IsWhiteSpace(_char))
        _char = ReadChar();
    }

    private TokenType BuildIdentifier()
    {
      while (char.IsLetter(_char) || char.IsDigit(_char) || ('_' == _char))
      {
        _text.Append(_char);
        _char = ReadChar();
      }
      return TokenType.Identifier;
    }

    /// <summary>
    /// Just supporting integers for now.
    /// </summary>
    private TokenType BuildNumber()
    {
      Integer = 0;
      while (char.IsDigit(_char))
      {
        Integer *= 10;
        Integer += (UInt64)(_char - '0');
        _char = ReadChar();
      }
      return TokenType.Integer;
    }

    private TokenType Special(TokenType tt)
    {
      _text.Append(_char);
      _char = ReadChar();
      return tt;
    }
  }
}
Top

Test program

The test program contains sample text to tokenise.


namespace Lex.V1
{
  public sealed class Test
  {
    const string Text =
    "int Add(int v1, int v2)\n" +
    "{\n" +
    "  return v1 + v2;\n" +
    "}\n" +
    "\n" +
    "int Main()\n" +
    "{\n" +
    "  int x = 2000 + 46;\n" +
    "  int y = 4096;\n" +
    "  int z = 1;" +
    "  z++;" +
    "  return Add(x, y);\n" +
    "}";

    public static void Run()
    {
      // Load text and loop until erroror end of stream.
      using StringReader sr = new(Text);
      Tokeniser tokeniser = new(sr);
      TokenType tt = tokeniser.Next();

      Console.WriteLine(Text);

      while (tt > TokenType.IsValidToken)
      {
        Console.WriteLine($"{tokeniser.Text} 	: {tt}");
        tt = tokeniser.Next();
      }

      if (tt == TokenType.Error)
        Console.WriteLine($"Error: {tokeniser.Text}");
    }
  }
}
Top

Driver Program

The following code runs the tokeniser, The code is located in program.cs. Due to latest C# compiler, no need for Program class or Main method, it is implied.


Lex.V1.Test.Run();
Top

Sample Output

Click/select image to see details

Saturday, 26 March 2022

Pixel Graphics Winforms

In an older post I illustrated how one can achieve decent pixel-based graphics. Following further research, I built upon the original idea. In this post, I achieve render times of about 11 milliseconds. For 60 FPS one must render each frame in about 16.7 milliseconds.

Top

Background

In the early days of Windows, an application could fully control the graphics display. Early games took advantage of this and essentially bypassed the operating system. Modern Windows due to its multitasking nature, no longer allows an application to "own" any resources outright. Resources are shared, including graphical data. Personally, I think the operating system should have a "Game Mode" setting, where only critical processes, threads, etc are run. I mean, does anyone want to run multiple apps whilst running a game?

Modern games use the graphics card(GPU) to output graphics. Data is sent to the GPU, leaving the CPU to perform CPU-bounds tasks (updating player position, score and so on). This is great if your app has access to DirectX, Direct 3D, OpenGL. However, if your app is unable to access such technology, and you are bound by simple Winforms technology...Read on!

Top

Winforms Graphics Basics

Each Window is assigned a graphics context. This usually arises in a Window's OnPaint event. Paint messages are classed as low priority messages, and as such are posted rather than sent. A sent message yields an immediate return, posted messages will yield a result in the future. The above is based upon ealier versions of Windows, though I doubt much has changed. Regardless, the OnPaint and supplied Graphics context is what is of interest here.

Top

Memory

C# as a rule manages memory. One can allocate memory (not directly) by creating new classes, structures etc. The memory required for such items will be released when the class/struct instance is no longer required. The CLR runtime can also relocate memory as and when required. When dealing with bitmaps, the latter is not ideal. Relocating memory for large bitmaps is expensive in terms of CPU time.

It is possible to allocate memory outside of the CLR. Doing so ensures that the CLR will never try to reclaim the memory. Put another way, you will be responsible for memory management. Almost in C++ land!

Manual memory management is a must for fast pixel graphics.

Top

Image Processing Pipeline

The basic pipeline is as follows...

  • Create an array to hold image information
  • Create a bitmap that uses memory from 1st step
  • Update array to reflect image information (Bitmap points to array memory so is automatically updated)
  • Blit bitmap to main form or relevant window
  • Repeat until app ends
Top

Multithreading/async programming

>My own research proved that adding threads or using asynchronous programming did not yield better results.

A Windows message loop generally doesn't play well with other threads. Typically, additional threads, at some point must communicate results with the main UI thread. This requires thread synchronisation techniques, which tend to be quite expensive. Performing most operations on the same thread seems to give best results.

That said, updating non UI elements may be worthwhile performing on separate thread(s). For example, whilst the UI thread is blitting current content, another thread might update values for the next scene.

Top

Achieving Optimal Paint Results

As mentioned, Windows posts a WM_PAINT message to a window, when an application window needs re-painting. One can invoke the WM_PAINT, and hence cause window repainting by issuing an Invalidate command. This may be followed by an Update command to perform immediate repainting.

I found that the best way to do this is to override the Application.OnIdle event. In the handler, one can just call invalidate. This will post the WM_PAINT message to the window. Once painting has occurred, the idle event will be raised again. This essentially causes a forever painting loop whilst still being responsive to other events.

The Code

The project is a .NET Windows Application targeting .NET Framework 4.8. No 3rd party libraries are used.


  using System;
  using System.Drawing;
  using System.Drawing.Imaging;
  using System.Runtime.InteropServices;
  
  namespace FastGraphics
  {
    /// <summary>
    /// Uses pinned memory and direct array access to manipulate bitmap bits.
    /// Pinned memory is not owned by the CLR, so, it is important to free when done.
    /// </summary>
    public sealed class FastBitmap : IDisposable
    {
      private GCHandle _pinnedMemoryHandle;
      private IntPtr _pinnedMemoryAddress;    
  
      public int Width { get; private set; }
      public int Height { get; private set; }
      public uint[] Pixels { get; private set; }
      public Bitmap Image { get; private set; }
  
      public FastBitmap(int width, int height)
      {
        // Pixels is an array that may be used to modify pixel data.
        // Typical formula is ((y*width)+x) = Alpha | Colour;
        // Uses 4 bytes per pixel (Alpha, Red, Green and Blue channels, each 8 bits)
        Pixels = new uint[width * height];
  
        // Inform OS that pixel allocated array is pinned and not subject to normal garbage collection.
        _pinnedMemoryHandle = GCHandle.Alloc(Pixels, GCHandleType.Pinned);
  
        // Obtain the pinned memory address, required to create bitmap for use by .NET app.
        _pinnedMemoryAddress = _pinnedMemoryHandle.AddrOfPinnedObject();
  
        // Set pixel format and calculate scan line stride.
        PixelFormat format = PixelFormat.Format32bppArgb;
        int bitsPerPixel = ((int)format & 65280) >> 8;
        int bytesPerPixel = (bitsPerPixel + 7) / 8;
        int stride = 4 * ((width * bytesPerPixel + 3) / 4);
        Image = new Bitmap(width, height, stride, PixelFormat.Format32bppArgb, _pinnedMemoryAddress);
        Width = width;
        Height = height;      
      }
  
      public void Draw(Graphics target) =>
        target.DrawImage(Image, 0, 0);
  
      public void Dispose()
      {
        Image.Dispose();
  
        if (_pinnedMemoryHandle.IsAllocated)
          _pinnedMemoryHandle.Free();
  
        _pinnedMemoryAddress = IntPtr.Zero;
        Pixels = Array.Empty<uint>();
        Width = 0;
        Height = 0;
      }
    }
  }
  

    using System;
    using System.Windows.Forms;
    
    namespace FastGraphics
    {
      internal static class Program
      {
        [STAThread]
        static void Main()
        {
          Application.EnableVisualStyles();
          Application.SetCompatibleTextRenderingDefault(false);
    
          try
          {
            Form1 form = new Form1();
            Application.Idle += (s, e) => form.OnIdle();
            Application.Run(form);
          }
          catch (Exception ex)
          {
            MessageBox.Show(ex.Message);
          }
        }
      }
    }

      using System;
      using System.Drawing.Drawing2D;
      using System.Windows.Forms;
      
      namespace FastGraphics
      {
        public partial class Form1 : Form
        {
          private FastBitmap _fastBitmap;
          private float _offset = 0;
      
          private uint _renderTimeInMilliseconds;
      
          public Form1()
          {
            InitializeComponent();
          }
      
          /// <summary>
          /// Update on-screen text that displays render time in miliiseconds.
          /// </summary>
          public void UpdateRenderTimeText()
          {
            label1.Text = _renderTimeInMilliseconds.ToString();
          }
      
          /// <summary>
          /// Dispose of existing fast bitmap (if exists)
          /// Create new fast bitmap based upon client rectangle.
          /// </summary>
          private void CreateFastBitmap()
          {
            _fastBitmap?.Dispose();
            _fastBitmap = new FastBitmap(ClientRectangle.Width, ClientRectangle.Height);
          }
      
          public void OnIdle()
          {
            Invalidate();
            UpdateRenderTimeText();
          }
      
          // Resizing form changes drawing area.
          // Resize fast bitmap accordingly.
          protected override void OnResize(EventArgs e)
          {
            CreateFastBitmap();
          }
      
          /// <summary>
          /// Override OnPaintBackground to do nothing.
          /// The OnPaint will perform all drawing.
          /// </summary>
          /// <param name="e"></param>
          protected override void OnPaintBackground(PaintEventArgs e)
          {
          }
      
          /// <summary>
          /// Magic happens in OnPaint.
          /// 1. Render raw pixel data (Fast bitmap)
          /// 2. Due to the nature of fast bitmap, its image will reflect pixel data.
          /// 3. Draw fast bitmap image to this form's window.
          /// 4. Time all of this so we can determine time taken to render a frame.
          /// Optional - set interpolation mode.
          /// </summary>
          /// <param name="e"></param>
          protected override void OnPaint(PaintEventArgs e)
          {
            DateTime startTime = DateTime.UtcNow;
            e.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
            RenderRawPixels();
            _fastBitmap.Draw(e.Graphics);
            this.BackgroundImage = _fastBitmap.Image;
            DateTime endTime = DateTime.UtcNow;
            _renderTimeInMilliseconds = (uint)(endTime - startTime).Milliseconds;
          }
      
          /// <summary>
          /// RenderRawPixels is called for each onPaint.    
          /// </summary>
          private void RenderRawPixels()
          {
            int rowAddress = 0;
            int width = _fastBitmap.Width;
            int height = _fastBitmap.Height;
            uint[] pixels = _fastBitmap.Pixels;
      
            for (int y = 0; y < height; y++)
            {
              float yF = (float)y;
              for (int x = 0; x < width; x++)
              {
                float xF = (float)x;
      
                float f =
                  ((xF * xF * xF * yF) / 16384) +
                  ((xF * yF * yF * yF) / 16384) +
                  ((xF * yF * _offset) / 16384);
                f *= _offset;
                f /= 65536;
                f /= 8192;
      
                uint alpha = 4278190080;
                // Alpha component tends to double rendering time
                // Setting to 0xFF000000 will ensure the above renders solid colours.
                // Uncomment the code below to introduce alpha component.
                //uint alpha = (uint)(
                //  (x * y) -
                //  (y * _offset)) /
                //  1024;
                //alpha <<= 24;
                //alpha &= 0xff000000;
      
      
                pixels[rowAddress + x] = alpha | (uint)(f * 16777215);
              }
              rowAddress += width;
            }
            BackgroundImage = _fastBitmap.Image;
            _offset += 0.005;
          }
      
          /// <summary>
          /// upon closing this form, we must dispose the fast bitmap.
          /// </summary>
          /// <param name="e"></param>
          protected override void OnClosed(EventArgs e)
          {
            _fastBitmap.Dispose();
            base.OnClosed(e);
          }
        }
      }

        namespace FastGraphics
        {
          partial class Form1
          {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
        
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
              if (disposing && (components != null))
              {
                components.Dispose();
              }
              base.Dispose(disposing);
            }
        
            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
              this.label1 = new System.Windows.Forms.Label();
              this.SuspendLayout();
              // 
              // label1
              // 
              this.label1.BackColor = System.Drawing.Color.Black;
              this.label1.ForeColor = System.Drawing.Color.White;
              this.label1.Location = new System.Drawing.Point(-2, -1);
              this.label1.Name = "label1";
              this.label1.Size = new System.Drawing.Size(43, 18);
              this.label1.TabIndex = 0;
              this.label1.Text = "Time";
              this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
              // 
              // Form1
              // 
              this.AutoScaleDimensions = new System.Drawing.SizeF(6, 13);
              this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
              this.ClientSize = new System.Drawing.Size(800, 450);
              this.Controls.Add(this.label1);
              this.DoubleBuffered = true;
              this.Name = "Form1";
              this.Text = "Form1";
              this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
              this.ResumeLayout(false);
        
            }
        
            #endregion
            public System.Windows.Forms.Label label1;
          }