unit TextMesh;

interface

uses
  OpenGl,
  Frost.GL,
  Frost.GameObjects,
  Frost.Renderers,
  Frost.Font,
  DefaultFont,
  _PNG,
  _Geometry;

type

TTextMesh = class(TComponent)
  private
    FFont: TFont;
    FText: WideString;
    FAlign: TTextAlign;
    FMeshRenderer: TMeshRenderer;
    procedure SetText(Text: WideString);  
    procedure SetAlign(Align: TTextAlign);
  public
    procedure OnStart(); override;
    property Text: WideString read FText write SetText;    
    property Align: TTextAlign read FAlign write SetAlign;
  end;

implementation

{$REGION 'CreateFlatMesh'}
function CreateFlatMesh(Size: Single = 1.2): TMesh;
var
  Vertex:   TVertexes;
  Normals:  TNormals;
  Textures: TTextures;
  Faces: TFaces;
  S: Single;
begin
  S := Size;
  SetLength(Vertex, 4);
  SetLength(Textures, 4);
  SetLength(Normals, 4);
  SetLength(Faces, 2);
  Vertex[0 ] := Vector3( S, -S,  S);
  Vertex[1 ] := Vector3( S,  S,  S);
  Vertex[2 ] := Vector3(-S,  S,  S);
  Vertex[3 ] := Vector3(-S, -S,  S);

  Normals[0 ] := Vector3( 0,  0,  1);
  Normals[1 ] := Vector3( 0,  0,  1);
  Normals[2 ] := Vector3( 0,  0,  1);
  Normals[3 ] := Vector3( 0,  0,  1);

  Textures[0 ] := Vector2(1, 1);
  Textures[1 ] := Vector2(1, 0);
  Textures[2 ] := Vector2(0, 0);
  Textures[3 ] := Vector2(0, 1);

  Faces[ 0] := Face( 0, 1, 2);
  Faces[ 1] := Face( 0, 2, 3);

  Result := TMesh.Create(Faces, Vertex, Textures, Normals);
  SetLength(Vertex, 0);
  SetLength(Textures, 0);
  SetLength(Normals, 0);
  SetLength(Faces, 0);
end;
{$ENDREGION}

procedure TTextMesh.OnStart();
begin
  if FFont = nil then
    FFont := TDefaultFont.Create();
  FMeshRenderer := TMeshRenderer.Create(GameObject);
  FMeshRenderer.Material := FFont.Material;  
  FText := 'LABEL';
  FAlign := MiddleCenter;
  SetText(FText);
end;

procedure TTextMesh.SetText(Text: WideString);
begin
  if (Text <> FText) then
  begin
    FText := Text;
    FMeshRenderer.Mesh := FFont.CreateTextMesh(FText, FAlign);
  end;
end;
 
procedure TTextMesh.SetAlign(Align: TTextAlign);
begin
  if (Align <> FAlign) then
  begin
    FAlign := Align;
    FMeshRenderer.Mesh := FFont.CreateTextMesh(FText, FAlign);
  end;
end;

end.
