unit MainFm;
(*
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 *)

// This example illustrates the following features:
//  * Drawing with 2D canvas to a "drawable" texture. By drawing to another texture, which retains its
//    contents between the frames, it is possible to produce a "motion blur" looking effect.

interface

uses
{$IFDEF MSWINDOWS}
  PXT.Controls,
{$ELSE}
  OpenGLContext,
{$ENDIF}
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ComCtrls, ExtCtrls, PXT.Types, PXT.Graphics;

type
  TMainForm = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FRenderingControl: TWinControl;
    FDisplaySize: TPoint2i;
    FDisplayScale: Single;

    FDevice: TDevice;
    FSwapChain: TSwapChain;
    FCanvas: TCanvas;
    FTextRenderer: TTextRenderer;
    FTimer: TTimer;

    FTextureCanvasMSAA: TTexture;
    FTextureCanvas: TTexture;
    FTextureMotion: TTexture;
    FTextureMotionCopy: TTexture;

    procedure RenderingControlResize(Sender: TObject);
    procedure RenderingControlPaint(Sender: TObject);
    procedure ApplicationIdle(Sender: TObject; var Done: Boolean);
    procedure CreateTextures;
    procedure DestroyTextures;
    procedure CreateRenderingControl;
  public
  end;

var
  MainForm: TMainForm;

implementation
{$R *.lfm}

uses
  Math, PXT.Headers;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  CreateRenderingControl;
  FDisplaySize := Point2i(ClientWidth, ClientHeight);
  FDisplayScale := PixelsPerInch / 96.0;
  try
  {$IFDEF MSWINDOWS}
    FDevice := TDevice.Create;
  {$ELSE}
    // On Linux, using TOpenGLContext control from LCL.
    FDevice := TDevice.CreateWrapped(TDeviceTechnology.OpenGL);
  {$ENDIF}

    FSwapChain := TSwapChain.Create(FDevice,
      {$IFDEF MSWINDOWS}TRenderingControl(FRenderingControl).WindowHandle{$ELSE}0{$ENDIF},
      FDisplaySize);

    FCanvas := TCanvas.Create(FDevice);
    FTextRenderer := TTextRenderer.Create(FCanvas, Point2i(256, 256), TPixelFormat.LA8);
    FTimer := TTimer.Create;

    CreateTextures;
  except
    on E: EAfterwarpException do
    begin
      MessageDlg(E.Message, mtError, [mbOK], 0);
      Application.Terminate;
      Exit;
    end;
  end;
  Application.OnIdle := ApplicationIdle;
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
  DestroyTextures;
  FTimer.Free;
  FTextRenderer.Free;
  FCanvas.Free;
  FSwapChain.Free;
  FDevice.Free;
end;

procedure TMainForm.RenderingControlResize(Sender: TObject);
begin
  if FSwapChain.Handle <> nil then
  begin
    FDisplaySize := Point2i(FRenderingControl.Width, FRenderingControl.Height);
    FSwapChain.Resize(FDisplaySize);

    DestroyTextures;
    try
      CreateTextures;
    except
      on E: EAfterwarpException do
      begin
        MessageDlg(E.Message, mtError, [mbOK], 0);
        Application.Terminate;
      end;
    end;
  end;
end;

procedure TMainForm.RenderingControlPaint(Sender: TObject);
var
  LFontParams: TFontParameters;
  LTechString: string;
  LFullQuad, LTexCoords: TQuad;
  LHalfTargetSize: TPoint2f;
  LFlipped: Boolean;
  LKappa, LSize: Single;
  LTicks: Double;
begin
  FDisplayScale := PixelsPerInch / 96.0;
  LTicks := GetSystemTicks * 60.0 / 1000000.0;

  LFullQuad := Quad(0.0, 0.0, FDisplaySize.X, FDisplaySize.Y);
  LFlipped :=
    (FDevice.Technology = TDeviceTechnology.OpenGL) or
    (FDevice.Technology = TDeviceTechnology.OpenGL_ES);

  LTexCoords := TQuad.Unity;
  if LFlipped then
    LTexCoords := LTexCoords.Flip;

  LHalfTargetSize := TPoint2f(FDisplaySize) * 0.5;

  FTextureCanvasMSAA.Clear;
  FTextureCanvasMSAA.BeginScene;
  try
    FCanvas.BeginScene;
    try
      FCanvas.ContextState := TCanvasContextState.FlatScene;

      LKappa := LTicks * 0.0274;
      LSize := Min(FDisplaySize.X, FDisplaySize.Y);

      FCanvas.Tape(LHalfTargetSize, Point2f(LSize * 0.25, LSize * 0.25), Point2f(LSize * 0.3, LSize * 0.4),
        LKappa, LKappa + 1.25 * Pi + Sin(LTicks * 0.024751) * 0.5 * PI, 128,
        ColorRect($FFFF0000, $FF00FF00, $FF0000FF, $FFFFFFFF), TBlendingEffect.Copy);

      LKappa := LKappa - LTicks * 0.0132;

      FCanvas.Tape(LHalfTargetSize, Point2f(LSize * 0.02, LSize * 0.01), Point2f(LSize * 0.12, LSize * 0.1),
        LKappa, LKappa + 1.5 * Pi + Cos(LTicks * 0.024751) * 0.5 * PI, 64,
        ColorRect($FFFF00FF, $FF00FFFF, $FFFFFF00, $FFFFFFFF), TBlendingEffect.Copy);
    finally
      FCanvas.EndScene;
    end;
  finally
    FTextureCanvasMSAA.EndScene;
  end;
  // Resolve MSAA to non-MSAA texture.
  FTextureCanvas.Copy(FTextureCanvasMSAA, 0, TPoint2i.Zero, 0, TIntRect.Zero);

  // Draw a kind of motion-blur effect.
  FTextureMotion.BeginScene;
  try
    FCanvas.BeginScene;
    try
      FCanvas.SamplerState := TCanvasSamplerState.Create(TTextureFilter.Linear, TTextureFilter.Linear);
      FCanvas.ContextState := TCanvasContextState.FlatScene;

      // Copy previous scene, englarged and slightly rotated.
      FCanvas.Attributes := [TCanvasAttribute.ColorAdjust, TCanvasAttribute.Cubic];
      FCanvas.Quad(FTextureMotionCopy, TQuad.Rotated(LHalfTargetSize, FDisplaySize, -0.01, 1.02),
        LTexCoords, $FE80807E, TBlendingEffect.Copy);

      // Add the "motion scene" on our working surface.
      FCanvas.Attributes := [];
      FCanvas.Quad(FTextureCanvas, LFullQuad, LTexCoords, MakeColorAlphaF(0.875));
    finally
      FCanvas.EndScene;
    end;
  finally
    FTextureMotion.EndScene;
  end;
  FTextureMotionCopy.Copy(FTextureMotion, 0, TPoint2i.Zero, 0, TIntRect.Zero);

  // Render on the form.
  FSwapChain.BeginScene;
  try
    FDevice.Clear([TClearLayer.Color], FloatColor($FFE1E2E6));

    FCanvas.BeginScene;
    try
      // Blend motion texture with background.
      FCanvas.SamplerState := TCanvasSamplerState.Default;
      FCanvas.ContextState := TCanvasContextState.FlatScene;

      FCanvas.Quad(FTextureMotion, LFullQuad, LTexCoords, TColorRect.White);

      // Draw technology string.
      FCanvas.ContextState := TCanvasContextState.FlatText;

      LFontParams := TFontParameters.Create('Segoe UI', 16.0 * FDisplayScale, TFontWeight.SemiBold);
      LFontParams.Effect.BorderType := TFontBorder.SemiHeavy;
      LFontParams.Effect.BorderBrightness := 1.0;
      LFontParams.Effect.FillBrightness := 0.0;
      LFontParams.Effect.ShadowBrightness := 0.75;
      LFontParams.Effect.ShadowOpacity := 1.0;
      FTextRenderer.FontParameters := LFontParams;

      FTextRenderer.DrawAligned(Point2f(12.0 * FDisplayScale, 4.0 * FDisplayScale),
        Utf8String('FPS: ' + IntToStr(Round(FTimer.FrameRate))), ColorPair($A0FFFFFF),
        TTextAlignment.Start, TTextAlignment.Start);

      if FDevice.Technology = TDeviceTechnology.Direct3D then
        LTechString := 'Direct3D (' + IntToStr(FDevice.TechVersion shr 8) + '.' +
          IntToStr((FDevice.TechVersion shr 4) and $0F) + '), features: '
      else
        LTechString := 'OpenGL (' + IntToStr(FDevice.TechVersion shr 8) + '.' +
          IntToStr((FDevice.TechVersion shr 4) and $0F) + '+), features: ';

      LTechString := LTechString + IntToStr(FDevice.TechFeatureVersion shr 8) + '.' +
        IntToStr((FDevice.TechFeatureVersion shr 4) and $0F);

      FTextRenderer.DrawAligned(Point2f(FDisplaySize.X - 12.0 * FDisplayScale, FDisplaySize.Y -
        4.0 * FDisplayScale), Utf8String(LTechString), ColorPair($A0FFFFFF),
        TTextAlignment.Ending, TTextAlignment.Ending);
    finally
      FCanvas.EndScene;
    end;
  finally
    FSwapChain.EndScene;
  end;
  FTimer.Update;
{$IFNDEF MSWINDOWS}
  TOpenGLControl(FRenderingControl).SwapBuffers;
{$ENDIF}
end;

procedure TMainForm.ApplicationIdle(Sender: TObject; var Done: Boolean);
begin
  FRenderingControl.Invalidate;
  Done := False;
end;

procedure TMainForm.CreateTextures;
var
  LParameters: TTextureParameters;
begin
  FillChar(LParameters, SizeOf(TTextureParameters), 0);
  LParameters.Width := FDisplaySize.X;
  LParameters.Height := FDisplaySize.Y;
  LParameters.Attributes := TTextureAttribute.Drawable or TTextureAttribute.PremultipliedAlpha;
  LParameters.Format := TPixelFormat.RGBA16;
  LParameters.Multisamples := 8;

  FTextureCanvasMSAA := TTexture.Create(FDevice, LParameters);

  LParameters.Multisamples := 0;

  FTextureCanvas := TTexture.Create(FDevice, LParameters);
  FTextureMotion := TTexture.Create(FDevice, LParameters);
  FTextureMotionCopy := TTexture.Create(FDevice, LParameters);
end;

procedure TMainForm.DestroyTextures;
begin
  FTextureMotionCopy.Free;
  FTextureMotion.Free;
  FTextureCanvas.Free;
  FTextureCanvasMSAA.Free;
end;

procedure TMainForm.CreateRenderingControl;
begin
{$IFDEF MSWINDOWS}
  FRenderingControl := TRenderingControl.Create(nil);
  FRenderingControl.Parent := Self;
  FRenderingControl.Align := alClient;
  FRenderingControl.Width := 256;
  FRenderingControl.Height := 256;

  with FRenderingControl as TRenderingControl do
  begin
    OnPaint := RenderingControlPaint;
    OnResize := RenderingControlResize;
  end;
{$ELSE}
  FRenderingControl := TOpenGLControl.Create(nil);
  FRenderingControl.Parent := Self;
  FRenderingControl.Align := alClient;
  FRenderingControl.Width := 256;
  FRenderingControl.Height := 256;

  with FRenderingControl as TOpenGLControl do
  begin
    OpenGLMajorVersion := 3;
    OpenGLMinorVersion := 3;
    DepthBits := 0;
    OnPaint := RenderingControlPaint;
    OnResize := RenderingControlResize;

    MakeCurrent;
  end;
{$ENDIF}
end;

end.
