almost working gl font renderer

This commit is contained in:
Chris Forbes
2010-02-25 20:49:16 +13:00
parent 88423b158a
commit f7656d44a4
13 changed files with 170 additions and 118 deletions

View File

@@ -25,7 +25,6 @@ namespace OpenRa.FileFormats.Graphics
IVertexBuffer<Vertex> CreateVertexBuffer( int length );
IIndexBuffer CreateIndexBuffer( int length );
ITexture CreateTexture( Bitmap bitmap );
IFont CreateFont( string filename );
IShader CreateShader( Stream stream );
Size WindowSize { get; }

View File

@@ -177,7 +177,7 @@ namespace OpenRa
buttons.Clear();
renderer.Device.DisableScissor();
renderer.RegularFont.DrawText("RenderFrame {0} ({2:F1} ms)\nTick {1} ({3:F1} ms)\n".F(
renderer.RegularFont.DrawText( rgbaRenderer, "RenderFrame {0} ({2:F1} ms)\nTick {1} ({3:F1} ms)\n".F(
Game.RenderFrame,
Game.orderManager.FrameNumber,
PerfHistory.items["render"].LastValue,
@@ -326,7 +326,7 @@ namespace OpenRa
if (map == currentMap)
DrawDialogBackground(itemRect, "panel");
renderer.RegularFont.DrawText(map.Map.Title, new int2(r.Left + 60, y), Color.White);
renderer.RegularFont.DrawText(rgbaRenderer, map.Map.Title, new int2(r.Left + 60, y), Color.White);
var closureMap = map;
AddButton(itemRect, _ => { currentMap = closureMap; mapPreviewDirty = true; });
}
@@ -444,11 +444,11 @@ namespace OpenRa
}
var f = renderer.BoldFont;
f.DrawText("Name", new int2(r.Left + 40, r.Top + 50), Color.White);
f.DrawText("Color", new int2(r.Left + 140, r.Top + 50), Color.White);
f.DrawText("Faction", new int2(r.Left + 220, r.Top + 50), Color.White);
f.DrawText("Status", new int2(r.Left + 290, r.Top + 50), Color.White);
f.DrawText("Spawn", new int2(r.Left + 390, r.Top + 50), Color.White);
f.DrawText(rgbaRenderer, "Name", new int2(r.Left + 40, r.Top + 50), Color.White);
f.DrawText(rgbaRenderer, "Color", new int2(r.Left + 140, r.Top + 50), Color.White);
f.DrawText(rgbaRenderer, "Faction", new int2(r.Left + 220, r.Top + 50), Color.White);
f.DrawText(rgbaRenderer, "Status", new int2(r.Left + 290, r.Top + 50), Color.White);
f.DrawText(rgbaRenderer, "Spawn", new int2(r.Left + 390, r.Top + 50), Color.White);
var y = r.Top + 80;
foreach (var client in Game.LobbyInfo.Clients)
@@ -481,17 +481,19 @@ namespace OpenRa
shpRenderer.Flush();
f = renderer.RegularFont;
f.DrawText(client.Name, new int2(r.Left + 40, y), Color.White);
f.DrawText(rgbaRenderer, client.Name, new int2(r.Left + 40, y), Color.White);
lineRenderer.FillRect(RectangleF.FromLTRB(paletteRect.Left + Game.viewport.Location.X + 5,
paletteRect.Top + Game.viewport.Location.Y + 5,
paletteRect.Right + Game.viewport.Location.X - 5,
paletteRect.Bottom+Game.viewport.Location.Y - 5),
Player.PlayerColors[client.PaletteIndex].c);
lineRenderer.Flush();
f.DrawText(client.Country, new int2(r.Left + 220, y), Color.White);
f.DrawText(client.State.ToString(), new int2(r.Left + 290, y), Color.White);
f.DrawText((client.SpawnPoint == 0)? "-" : client.SpawnPoint.ToString(), new int2(r.Left + 410, y), Color.White);
f.DrawText(rgbaRenderer, client.Country, new int2(r.Left + 220, y), Color.White);
f.DrawText(rgbaRenderer, client.State.ToString(), new int2(r.Left + 290, y), Color.White);
f.DrawText(rgbaRenderer, (client.SpawnPoint == 0) ? "-" : client.SpawnPoint.ToString(), new int2(r.Left + 410, y), Color.White);
y += 30;
rgbaRenderer.Flush();
}
var typingBox = new Rectangle(r.Left + 20, r.Bottom - 47, r.Width - 40, 27);
@@ -740,7 +742,7 @@ namespace OpenRa
shpRenderer.DrawSprite(optionsButton.Image, optionsDrawPos, "chrome");
shpRenderer.Flush();
renderer.RegularFont.DrawText("Options", new int2((int)(optionsButton.Image.size.X - renderer.RegularFont.Measure("Options").X) / 2, -2), Color.White);
renderer.RegularFont.DrawText(rgbaRenderer, "Options", new int2((int)(optionsButton.Image.size.X - renderer.RegularFont.Measure("Options").X) / 2, -2), Color.White);
}
void DrawOptionsMenu()
@@ -803,6 +805,8 @@ namespace OpenRa
if (Game.chat.isChatting)
RenderChatLine(Tuple.New(Color.White, "Chat:", Game.chat.typing),
new int2(typingArea.X + 10, typingArea.Y + 6));
rgbaRenderer.Flush();
renderer.Device.DisableScissor();
renderer.Device.EnableScissor(chatLogArea.Left, chatLogArea.Top, chatLogArea.Width, chatLogArea.Height);
@@ -811,14 +815,16 @@ namespace OpenRa
chatpos.Y -= 20;
RenderChatLine(line, chatpos);
}
rgbaRenderer.Flush();
renderer.Device.DisableScissor();
}
void RenderChatLine(Tuple<Color, string, string> line, int2 p)
{
var size = renderer.RegularFont.Measure(line.b);
renderer.RegularFont.DrawText(line.b, p, line.a);
renderer.RegularFont.DrawText(line.c, p + new int2(size.X + 10, 0), Color.White);
renderer.RegularFont.DrawText(rgbaRenderer, line.b, p, line.a);
renderer.RegularFont.DrawText(rgbaRenderer, line.c, p + new int2(size.X + 10, 0), Color.White);
}
void TickPaletteAnimation()
@@ -1064,12 +1070,12 @@ namespace OpenRa
void DrawRightAligned(string text, int2 pos, Color c)
{
renderer.BoldFont.DrawText(text, pos - new int2(renderer.BoldFont.Measure(text).X, 0), c);
renderer.BoldFont.DrawText(rgbaRenderer, text, pos - new int2(renderer.BoldFont.Measure(text).X, 0), c);
}
void DrawCentered(string text, int2 pos, Color c)
{
renderer.BoldFont.DrawText(text, pos - new int2(renderer.BoldFont.Measure(text).X / 2, 0), c);
renderer.BoldFont.DrawText(rgbaRenderer, text, pos - new int2(renderer.BoldFont.Measure(text).X / 2, 0), c);
}
void DrawProductionTooltip(World world, string unit, int2 pos)
@@ -1077,12 +1083,12 @@ namespace OpenRa
var tooltipSprite = ChromeProvider.GetImage(renderer, chromeCollection, "tooltip-bg");
var p = pos.ToFloat2() - new float2(tooltipSprite.size.X, 0);
rgbaRenderer.DrawSprite(tooltipSprite, p, "chrome");
rgbaRenderer.Flush();
var info = Rules.Info[unit];
var buildable = info.Traits.Get<BuildableInfo>();
renderer.BoldFont.DrawText(buildable.Description, p.ToInt2() + new int2(5, 5), Color.White);
renderer.BoldFont.DrawText(rgbaRenderer, buildable.Description, p.ToInt2() + new int2(5, 5), Color.White);
DrawRightAligned( "${0}".F(buildable.Cost), pos + new int2(-5,5),
world.LocalPlayer.Cash + world.LocalPlayer.Ore >= buildable.Cost ? Color.White : Color.Red);
@@ -1100,15 +1106,17 @@ namespace OpenRa
{
var prereqs = buildable.Prerequisites
.Select( a => Description( a ) );
renderer.RegularFont.DrawText("Requires {0}".F( string.Join( ", ", prereqs.ToArray() ) ), p.ToInt2(),
renderer.RegularFont.DrawText(rgbaRenderer, "Requires {0}".F(string.Join(", ", prereqs.ToArray())), p.ToInt2(),
Color.White);
}
if (buildable.LongDesc != null)
{
p += new int2(0, 15);
renderer.RegularFont.DrawText(buildable.LongDesc.Replace( "\\n", "\n" ), p.ToInt2(), Color.White);
renderer.RegularFont.DrawText(rgbaRenderer, buildable.LongDesc.Replace( "\\n", "\n" ), p.ToInt2(), Color.White);
}
rgbaRenderer.Flush();
}
static string Description( string a )
@@ -1201,7 +1209,7 @@ namespace OpenRa
pos += new int2(5, 5);
renderer.BoldFont.DrawText(sp.Info.Description, pos, Color.White);
renderer.BoldFont.DrawText(rgbaRenderer, sp.Info.Description, pos, Color.White);
var timer = "Charge Time: {0}".F(FormatTime(sp.RemainingTime));
DrawRightAligned(timer, pos + new int2((int)tooltipSprite.size.X - 10, 0), Color.White);
@@ -1209,8 +1217,10 @@ namespace OpenRa
if (sp.Info.LongDesc != null)
{
pos += new int2(0, 25);
renderer.RegularFont.DrawText(sp.Info.LongDesc.Replace("\\n", "\n"), pos, Color.White);
renderer.RegularFont.DrawText(rgbaRenderer, sp.Info.LongDesc.Replace("\\n", "\n"), pos, Color.White);
}
rgbaRenderer.Flush();
}
public void SetCurrentTab(string produces)

View File

@@ -34,12 +34,12 @@ namespace OpenRa.Graphics
try
{
var shp = new Dune2ShpReader(FileSystem.OpenWithExts(filename, exts));
return shp.Select(a => SheetBuilder.Add(a.Image, a.Size)).ToArray();
return shp.Select(a => SheetBuilder.SharedInstance.Add(a.Image, a.Size)).ToArray();
}
catch (IndexOutOfRangeException) // This will occur when loading a custom (RA-format) .shp
{
var shp = new ShpReader(FileSystem.OpenWithExts(filename, exts));
return shp.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray();
return shp.Select(a => SheetBuilder.SharedInstance.Add(a.Image, shp.Size)).ToArray();
}
}

View File

@@ -43,7 +43,7 @@ namespace OpenRa.Graphics
public ITexture PaletteTexture;
public readonly IFont RegularFont, BoldFont;
public readonly SpriteFont RegularFont, BoldFont;
public Size Resolution { get { return device.WindowSize; } }
@@ -56,8 +56,11 @@ namespace OpenRa.Graphics
RgbaSpriteShader = device.CreateShader(FileSystem.Open("shaders/chrome-rgba.fx"));
WorldSpriteShader = device.CreateShader(FileSystem.Open("shaders/chrome-shp.fx"));
RegularFont = device.CreateFont( "FreeSans.ttf" );
BoldFont = device.CreateFont( "FreeSansBold.ttf" );
// RegularFont = device.CreateFont( "FreeSans.ttf" );
// BoldFont = device.CreateFont( "FreeSansBold.ttf" );
RegularFont = new SpriteFont(this, "FreeSans.ttf", 14);
BoldFont = new SpriteFont(this, "FreeSansBold.ttf", 14);
}
IGraphicsDevice CreateDevice( Assembly rendererDll, int width, int height, bool windowed, bool vsync )

View File

@@ -22,24 +22,31 @@ using System.Drawing;
namespace OpenRa.Graphics
{
static class SheetBuilder
class SheetBuilder
{
public static SheetBuilder SharedInstance;
public static void Initialize(Renderer r)
{
SharedInstance = new SheetBuilder(r, TextureChannel.Red);
}
public SheetBuilder(Renderer r, TextureChannel ch)
{
renderer = r;
current = null;
rowHeight = 0;
channel = null;
initialChannel = ch;
}
public static Sprite Add(byte[] src, Size size)
public Sprite Add(byte[] src, Size size)
{
Sprite rect = AddImage(size);
Sprite rect = Allocate(size);
Util.FastCopyIntoChannel(rect, src);
return rect;
}
public static Sprite Add(Size size, byte paletteIndex)
public Sprite Add(Size size, byte paletteIndex)
{
byte[] data = new byte[size.Width * size.Height];
for (int i = 0; i < data.Length; i++)
@@ -48,18 +55,19 @@ namespace OpenRa.Graphics
return Add(data, size);
}
static Sheet NewSheet() { return new Sheet( renderer, new Size( Renderer.SheetSize, Renderer.SheetSize ) ); }
Sheet NewSheet() { return new Sheet( renderer, new Size( Renderer.SheetSize, Renderer.SheetSize ) ); }
static Renderer renderer;
static Sheet current = null;
static int rowHeight = 0;
static Point p;
static TextureChannel? channel = null;
Renderer renderer;
Sheet current = null;
int rowHeight = 0;
Point p;
TextureChannel? channel = null;
TextureChannel initialChannel;
static TextureChannel? NextChannel(TextureChannel? t)
TextureChannel? NextChannel(TextureChannel? t)
{
if (t == null)
return TextureChannel.Red;
return initialChannel;
switch (t.Value)
{
@@ -72,7 +80,7 @@ namespace OpenRa.Graphics
}
}
static Sprite AddImage(Size imageSize)
public Sprite Allocate(Size imageSize)
{
if (current == null)
{

View File

@@ -0,0 +1,103 @@
using System;
using System.Drawing;
using System.Linq;
using OpenRa.FileFormats;
using Tao.FreeType;
using System.Runtime.InteropServices;
namespace OpenRa.Graphics
{
class SpriteFont
{
int size;
public SpriteFont(Renderer r, string name, int size)
{
this.size = size;
if (0 != FT.FT_New_Face(library, name, 0, out face))
throw new InvalidOperationException("FT_New_Face failed");
FT.FT_Set_Pixel_Sizes(face, 0, (uint)size);
glyphs = new Cache<char, GlyphInfo>(CreateGlyph);
// setup a 1-channel SheetBuilder for our private use
if (builder == null) builder = new SheetBuilder(r, TextureChannel.Alpha);
// precache glyphs for U+0020 - U+007f
for (var n = (char)0x20; n < (char)0x7f; n++)
if (glyphs[n] == null)
throw new InvalidOperationException();
}
public void DrawText(SpriteRenderer r, string text, float2 location, Color c)
{
location.Y += size; // baseline vs top
var p = location;
foreach (var s in text)
{
if (s == '\n')
{
location.Y += size;
p = location;
continue;
}
var g = glyphs[s];
r.DrawSprite(g.Sprite, p + g.Offset, "chrome");
p.X += g.Advance;
}
r.Flush();
}
public int2 Measure(string text)
{
return new int2((int)text.Split( '\n' ).Max( s => s.Sum(a => glyphs[a].Advance)), size);
}
Cache<char, GlyphInfo> glyphs;
IntPtr face;
GlyphInfo CreateGlyph(char c)
{
var index = FT.FT_Get_Char_Index(face, (uint)c);
FT.FT_Load_Glyph(face, index, FT.FT_LOAD_RENDER);
var _face = (FT_FaceRec)Marshal.PtrToStructure(face, typeof(FT_FaceRec));
var _glyph = (FT_GlyphSlotRec)Marshal.PtrToStructure(_face.glyph, typeof(FT_GlyphSlotRec));
var s = builder.Allocate(new Size(_glyph.metrics.width >> 6, _glyph.metrics.height >> 6));
var g = new GlyphInfo
{
Sprite = s,
Advance = _glyph.metrics.horiAdvance >> 6,
Offset = { X = -_glyph.bitmap_left, Y = -_glyph.bitmap_top }
};
// todo: sensible blit, rather than just `white box`
for (var j = 0; j < s.size.Y; j++)
for (var i = 0; i < s.size.X; i++)
s.sheet.Bitmap.SetPixel(i + s.bounds.Left, j + s.bounds.Top, Color.White);
s.sheet.Texture.SetData(s.sheet.Bitmap);
return g;
}
static SpriteFont()
{
FT.FT_Init_FreeType(out library);
}
static IntPtr library;
static SheetBuilder builder;
}
class GlyphInfo
{
public float Advance;
public int2 Offset;
public Sprite Sprite;
}
}

View File

@@ -42,7 +42,7 @@ namespace OpenRa.Graphics
static Sprite[] LoadSprites(string filename)
{
var shp = new ShpReader(FileSystem.OpenWithExts(filename, exts));
return shp.Select(a => SheetBuilder.Add(a.Image, shp.Size)).ToArray();
return shp.Select(a => SheetBuilder.SharedInstance.Add(a.Image, shp.Size)).ToArray();
}
public static Sprite[] LoadAllSprites(string filename) { return sprites[filename]; }

View File

@@ -42,7 +42,7 @@ namespace OpenRa.Graphics
Size tileSize = new Size( Game.CellSize, Game.CellSize );
var tileMapping = new Cache<TileReference, Sprite>(
x => SheetBuilder.Add(world.TileSet.GetBytes(x), tileSize));
x => SheetBuilder.SharedInstance.Add(world.TileSet.GetBytes(x), tileSize));
Vertex[] vertices = new Vertex[4 * map.Height * map.Width];
ushort[] indices = new ushort[6 * map.Height * map.Width];

View File

@@ -65,11 +65,8 @@
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Tao.FreeType, Version=2.3.5.0, Culture=neutral, PublicKeyToken=e499629dc69cd531, processorArchitecture=MSIL" />
<Reference Include="Tao.OpenAl, Version=1.1.0.1, Culture=neutral, PublicKeyToken=a7579dda88828311, processorArchitecture=MSIL" />
<Reference Include="ISE.FreeType, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1b34ab585684d5ea">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\thirdparty\ISE.FreeType.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Chat.cs" />
@@ -93,6 +90,7 @@
<Compile Include="Graphics\ChromeProvider.cs" />
<Compile Include="Graphics\MappedImage.cs" />
<Compile Include="Graphics\Minimap.cs" />
<Compile Include="Graphics\SpriteFont.cs" />
<Compile Include="Network\Connection.cs" />
<Compile Include="Orders\PowerDownOrderGenerator.cs" />
<Compile Include="Effects\Missile.cs" />

View File

@@ -90,7 +90,7 @@ namespace OpenRa.Traits
{
cachedTheater = world.Map.Theater;
sprites = new Cache<TileReference, Sprite>(
x => SheetBuilder.Add(world.TileSet.GetBytes(x),
x => SheetBuilder.SharedInstance.Add(world.TileSet.GetBytes(x),
new Size(Game.CellSize, Game.CellSize)));
}

View File

@@ -50,7 +50,7 @@ namespace OpenRa
for (int j = 0; j < Game.CellSize; j++)
data[i * Game.CellSize + j] = ((i + j) % 4 < 2) ? (byte)0 : paletteIndex;
return SheetBuilder.Add( data, new Size(Game.CellSize,Game.CellSize) );
return SheetBuilder.SharedInstance.Add(data, new Size(Game.CellSize, Game.CellSize));
}
public void Draw( World world )

View File

@@ -28,7 +28,6 @@ using Tao.Cg;
using Tao.OpenGl;
using OpenRa.FileFormats.Graphics;
using Tao.Sdl;
using ISE;
[assembly: Renderer( typeof( OpenRa.GlRenderer.GraphicsDevice ))]
@@ -265,11 +264,6 @@ namespace OpenRa.GlRenderer
return new Shader( this, stream );
}
public IFont CreateFont( string filename )
{
return new Font( this, filename );
}
#endregion
}
@@ -453,63 +447,4 @@ namespace OpenRa.GlRenderer
bitmap.UnlockBits(bits);
}
}
class Font : IFont
{
const int RenderedFontSize = 48;
const float emHeight = 14f; /* px */
GraphicsDevice dev;
FTFontGL font;
public Font( GraphicsDevice dev, string filename )
{
this.dev = dev;
int Errors;
font = new FTFontGL(filename, out Errors);
if (Errors > 0)
throw new InvalidOperationException("Error(s) loading font");
font.ftRenderToTexture(RenderedFontSize, 192);
font.FT_ALIGN = FTFontAlign.FT_ALIGN_LEFT;
}
public void DrawText( string text, int2 pos, Color c )
{
pos.Y += (int)(emHeight);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPushMatrix();
Gl.glLoadIdentity();
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPushMatrix();
Gl.glLoadIdentity();
Gl.glOrtho(0, dev.WindowSize.Width, 0, dev.WindowSize.Height, 0, 1);
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glTranslatef(pos.X, dev.WindowSize.Height - pos.Y, 0);
Gl.glScalef(emHeight / RenderedFontSize, emHeight / RenderedFontSize, 1);
font.ftBeginFont(false);
Gl.glColor4f(c.R / 255f, c.G / 255f, c.B / 255f, c.A / 255f);
font.ftWrite(text);
font.ftEndFont();
Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glPopMatrix();
Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glPopMatrix();
GraphicsDevice.CheckGlError();
}
public int2 Measure( string text )
{
return new int2((int)(font.ftExtent(ref text) / 3), (int)emHeight);
}
}
}

View File

@@ -31,10 +31,6 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="ISE.FreeType, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1b34ab585684d5ea, processorArchitecture=x86">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\thirdparty\ISE.FreeType.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>