generate-font.ps1 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Font file format generator script.
  2. param (
  3. [Parameter(Mandatory)][string]$inputFile,
  4. [Parameter(Mandatory)][string]$outputFile
  5. )
  6. function Get-UInt16AsBytes() {
  7. [OutputType([Array])]
  8. param (
  9. [Parameter(Mandatory)][uint16]$Value
  10. )
  11. $hi = ($Value -shr 8) -band 0xFF
  12. $lo = $Value -band 0xFF
  13. return [Array]@($lo, $hi)
  14. }
  15. $inputFileContent = Get-Content -Path $inputFile -Raw
  16. $fontFile = New-Item -Name $outputFile -ItemType File -Force
  17. $fileStream = $fontFile.OpenWrite()
  18. try {
  19. # Font info
  20. if ($inputFileContent -match "FontInfo\s*=\s*{\s*`"(.+)`",\s*(\d+).*\s*('.').*\s*('.').*\s*(\d+)") {
  21. $fileStream.WriteByte([Byte]$Matches[1].Length) # Font name length
  22. $fileStream.Write([System.Text.Encoding]::ASCII.GetBytes($Matches[1]), 0, $Matches[1].Length) # Font name
  23. $fileStream.WriteByte([Byte]$Matches[2]) # Character height
  24. $fileStream.WriteByte([Byte][Char]$Matches[3][1]) # Start character
  25. $fileStream.WriteByte([Byte][Char]$Matches[4][1]) # End character
  26. $fileStream.WriteByte([Byte]$Matches[5]) # Width, in pixels, of space character
  27. } else {
  28. throw "Unable to find FontInfo data"
  29. }
  30. # Font bitmaps
  31. if ($inputFileContent -match 'Bitmaps\[\]\s*=\s*\{([^}]+)\}') {
  32. $bitmapsRaw = $Matches[1];
  33. $bitmapsMatch = $bitmapsRaw | Select-String -Pattern '0x[0-9a-zA-Z]{2}' -AllMatches
  34. $bitmapBytes = $bitmapsMatch.Matches.Value | ForEach({ [byte]$_ })
  35. $length = [uint16]$bitmapBytes.Length
  36. $fileStream.Write((Get-UInt16AsBytes -Value $length), 0, 2) # Bitmap array length
  37. $fileStream.Write($bitmapBytes, 0, $length) # Bitmap data
  38. } else {
  39. throw "Unable to find Bitmap data"
  40. }
  41. # Font descriptors
  42. if ($inputFileContent -match 'Descriptors\[\]\s*=\s*\{([\w\W]+?)\};') {
  43. $descriptorsRaw = $Matches[1];
  44. $descriptorsMatch = $descriptorsRaw | Select-String -Pattern '\{\s*(\d+),\s*(\d+)\s*\}' -AllMatches
  45. $fileStream.WriteByte([Byte]$descriptorsMatch.Matches.Length) # Descriptors array length
  46. foreach ($match in $descriptorsMatch.Matches) {
  47. $fileStream.WriteByte([Byte]$match.Groups[1].Value) # Character width
  48. $offset = [uint16]$match.Groups[2].Value
  49. $fileStream.Write((Get-UInt16AsBytes -Value $offset), 0, 2) # Character offset
  50. }
  51. } else {
  52. throw "Unable to find Descriptors data"
  53. }
  54. } finally {
  55. $fileStream.Dispose()
  56. }