text stringlengths 14 6.51M |
|---|
(* StackADS: SWa, 2020-04-15 *)
(* --------- *)
(* Stack abstract data structure. *)
(* ========================================================================= *)
UNIT StackADS;
INTERFACE
PROCEDURE Push(value: INTEGER);
FUNCTION Pop: INTEGER;
FUNCTION Empty: BOOLEAN;
IMPLEMENTATION
CONST
MAX = 100;
VAR
top: INTEGER;
data: ARRAY [1..MAX] OF INTEGER;
PROCEDURE Push(value: INTEGER);
BEGIN (* Push *)
IF (top = MAX) THEN BEGIN
WriteLn('ERROR: stack full');
HALT;
END; (* IF *)
top := top + 1;
data[top] := value;
END; (* Push *)
FUNCTION Pop: INTEGER;
VAR
value: INTEGER;
BEGIN (* Pop *)
IF (top = 0) THEN BEGIN
WriteLn('ERROR: stack empty');
HALT;
END; (* IF *)
value := data[top];
top := top - 1;
Pop := value;
END; (* Pop *)
FUNCTION Empty: BOOLEAN;
BEGIN (* Empty *)
Empty := (top = 0);
END; (* Empty *)
BEGIN (* StackADS *)
top := 0;
END. (* StackADS *)
|
unit ufrmMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Math.Vectors, FMX.MaterialSources, FMX.Controls3D, FMX.Objects3D,
FMX.Viewport3D, FMX.Ani, FMX.Controls.Presentation, FMX.StdCtrls;
type
TfrmMain = class(TForm)
Viewport3D1: TViewport3D;
Sphere1: TSphere;
TextureMaterialSource1: TTextureMaterialSource;
FloatAnimation1: TFloatAnimation;
lblBrand: TLabel;
Dummy1: TDummy;
Camera1: TCamera;
btnResetCamera: TButton;
procedure Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure Viewport3D1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
procedure Viewport3D1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure btnResetCameraClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FMouseDown: TPointF;
FLastDistance: Integer;
FOriginalRotationAngleX: Single;
FOriginalRotationAngleY: Single;
FOriginalZoom: Single;
public
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
// TfrmMain
// ============================================================================
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FOriginalRotationAngleX := Dummy1.RotationAngle.X;
FOriginalRotationAngleY := Dummy1.RotationAngle.Y;
FOriginalZoom := Camera1.Position.Z;
end;
// ----------------------------------------------------------------------------
procedure TfrmMain.btnResetCameraClick(Sender: TObject);
begin
Dummy1.RotationAngle.Point := TPoint3D.Zero;
Dummy1.RotationAngle.X := FOriginalRotationAngleX;
Dummy1.RotationAngle.Y := FOriginalRotationAngleY;
Camera1.Position.Z := FOriginalZoom;
end;
// ----------------------------------------------------------------------------
procedure TfrmMain.Viewport3D1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
var
LDelta: Single;
begin
if EventInfo.GestureID = igiZoom then
begin
if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags) then
FLastDistance := EventInfo.Distance;
LDelta := (EventInfo.Distance - FLastDistance) / 40;
Camera1.Position.Z := Camera1.Position.Z + LDelta;
FLastDistance := EventInfo.Distance;
end;
end;
// ----------------------------------------------------------------------------
procedure TfrmMain.Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
FMouseDown := PointF(X, Y);
end;
// ----------------------------------------------------------------------------
procedure TfrmMain.Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
begin
if ssLeft in Shift then
begin
Dummy1.RotationAngle.X := Dummy1.RotationAngle.X -
((Y - FMouseDown.Y) * 0.3);
Dummy1.RotationAngle.Y := Dummy1.RotationAngle.Y +
((X - FMouseDown.X) * 0.3);
FMouseDown := PointF(X, Y);
end;
end;
// ----------------------------------------------------------------------------
procedure TfrmMain.Viewport3D1MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
begin
Camera1.Position.Z := Camera1.Position.Z + WheelDelta / 40;
end;
end.
|
unit FindFilesUnit;
//////////////////////////////////////////////////////////////////////////////
// //
// Description: File and directory handling routines //
// //
// BuildRecursiveDirList //
// Takes a root directory and returns a string list of all that //
// directory's subdirectories, recursively //
// //
// FindFiles //
// Looks for files in the passed in string list with the passed in //
// extension and returns the list of files of that extension, full paths //
// included //
// //
//////////////////////////////////////////////////////////////////////////////
interface
uses
Classes;
function BuildRecursiveDirList(sRoot: String): TStringList;
function FindFiles(slDirs: TStringList; sExtension: String): TStringList;
implementation
uses
FileCtrl, SysUtils, Forms;
function BuildRecursiveDirList(sRoot: String): TStringList;
//////////////////////////////////////////////////////////////
// Preconditions : //
// sRoot is a valid directory //
// //
// Output : //
// Sorted StringList of subdirectories starting from sRoot //
// Result StringList must be destroyed by owner //
//////////////////////////////////////////////////////////////
var
sDir: String;
slTemp,
slResult: TStringList;
iCheck: integer;
srSearch: TSearchRec;
begin
try
slResult := TStringList.Create;
try
slTemp := TStringList.Create;
///////////////////////////////////////////////////////////
// Initialize starting directory for search string lists //
///////////////////////////////////////////////////////////
slTemp.Add(IncludeTrailingBackslash(sRoot));
slResult.Add(IncludeTrailingBackslash(sRoot));
while slTemp.Count > 0 do
begin
////////////////////////////////////
// Start working with a directory //
////////////////////////////////////
sDir := slTemp[0];
////////////////////////////////////////////////////////////////
// "Pop" current scanning directory so we don't scan it again //
////////////////////////////////////////////////////////////////
slTemp.Delete(0);
////////////////////////////////////////////////////////
// Find files - we'll sort for more directories below //
////////////////////////////////////////////////////////
// TODO: can we get away with faDirectory instead of faAnyFile ?
// iCheck := FindFirst(sDir + '*.*', faAnyFile, srSearch);
iCheck := FindFirst(sDir + '*.*', faDirectory, srSearch);
while iCheck = 0 do
begin
/////////////////////////////////////////////////////
// Directory found? Add it to the lists //
// slTemp for further recursive directory checking //
// slResult as a directory that exists //
/////////////////////////////////////////////////////
if ((srSearch.Name <> '.') and (srSearch.Name <> '..'))
{and ((srSearch.Attr and faDirectory) <> 0)} then
begin
slTemp.Add(IncludeTrailingBackslash(sDir + srSearch.Name));
slResult.Add(IncludeTrailingBackslash(sDir + srSearch.Name));
end; // if ((srSearch.Name <> '.') and (srSearch.Name <> '..')) and ((srSearch.Attr and faDirectory) <> 0)
//////////////////////////////////
// Find the next file/directory //
//////////////////////////////////
iCheck := FindNext(srSearch);
//////////////////////
// Prevent hang-ups //
//////////////////////
Application.ProcessMessages;
end;
FindClose(srSearch);
end; // while slTemp.Count > 0
if slResult.Count > 0 then
slResult.Sort;
Result := slResult;
finally
FreeAndNil(slTemp);
end; // try..finally slTemp.Create
except on E:Exception do
Raise Exception('Unable to build subdirectory list starting from ' + sRoot
+ ':' + #10#13 + E.Message);
end; // try..except
end;
function FindFiles(slDirs: TStringList; sExtension: String): TStringList;
///////////////////////////////////////////////////////////
// Preconditions : //
// slDirs contains a list of valid directories //
// sExtension is a valid file extension, ex: .jpg //
// //
// Output : //
// StringList of file names found in slDirs directories //
// where extension is the same as sExtension //
// Result StringList must be destroyed by owner //
///////////////////////////////////////////////////////////
var
i,
iCheck: integer;
slResult: TStringList;
srSearch: TSearchRec;
begin
if slDirs.Count <= 0 then
begin
Result := nil;
Exit;
end;
try
slResult := TStringList.Create;
for i := 0 to slDirs.Count - 1 do
begin
iCheck := FindFirst(slDirs[i] + '*' + sExtension, faAnyFile, srSearch);
while iCheck = 0 do
begin
slResult.Add(slDirs[i] + srSearch.Name);
iCheck := FindNext(srSearch);
Application.ProcessMessages;
end;
FindClose(srSearch);
end; // for i := 0 to slDirs.Count - 1
if slResult.Count > 0 then
slResult.Sort;
Result := slResult;
except on E:Exception do
Raise Exception.Create('Failure to find ' + sExtension + ' files.' + #10#13 + E.Message);
end; // try..except
end;
end.
|
unit DX.Messages.Dialog.Listener;
interface
uses
System.Classes, System.SysUtils, System.Messaging, DX.Messages.Dialog;
type
TMessageDialogListenerBase = class (TObject)
strict private
class var FInstance: TMessageDialogListenerBase;
strict protected
procedure Listener(const ASender: TObject; const AMessage: TMessage); virtual;
procedure ShowMessageDialog(const AMessageRequest: TMessageDialogRequest); virtual; abstract;
public
constructor Create; virtual;
class destructor Destroy;
destructor Destroy; override;
class procedure Register;
class procedure Unregister;
end;
implementation
uses
System.UITypes;
{ TMessageDialogListenerBase }
constructor TMessageDialogListenerBase.Create;
begin
inherited;
TMessageManager.DefaultManager.SubscribeToMessage(TMessageDialogRequest, Listener);
end;
destructor TMessageDialogListenerBase.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TMessageDialogRequest, Listener, true);
inherited;
end;
class destructor TMessageDialogListenerBase.Destroy;
begin
Unregister;
end;
procedure TMessageDialogListenerBase.Listener(const ASender: TObject; const AMessage: TMessage);
var
LMessage: TMessageDialogRequest;
begin
if AMessage is TMessageDialogRequest then
begin
LMessage := TMessageDialogRequest(AMessage);
ShowMessageDialog(LMessage);
end;
end;
class procedure TMessageDialogListenerBase.Register;
begin
FInstance := Create;
end;
class procedure TMessageDialogListenerBase.Unregister;
begin
FreeAndNil(FInstance);
end;
end.
|
////////////////////////////////////////////
// Кодировка и расчет CRC для приборов Логика СПТ-961
////////////////////////////////////////////
unit Devices.Logica.SPT961;
interface
uses Windows, GMGlobals, GMConst, Classes, SysUtils, Devices.ReqCreatorBase;
function LogicaSPT961_CheckCRC(buf: array of Byte; Len: int): bool;
type
TSPT961AnswerType = (logicaAnswerNone, logicaAnswerValue, logicaAnswerTimeArray);
TSPT961ReqCreator = class(TDevReqCreator)
protected
FNC, DataDLEHead, DataDLESet, DAD: string;
Chn: int;
Prm: int;
IdxStart, IdxCount: int;
archDT1, archDT2: TDateTime;
ArchType: TGMArchType;
BufSend: array[0..1024] of Byte;
LengthSend: int;
function FromExtData(const Extdata: string; archType: T485RequestType = rqtSPT961): bool;
procedure CommonPrm();
procedure IndexPrm();
procedure ArchStructure();
procedure ArchData();
procedure TimeArray();
function ResultString(): string;
function ArrayTypePrmNumber(): int;
procedure MakeBuf();
function EncodeNumber(n: int): string;
function InternalResultString(): string;
function EncodeDT(dt: TDateTime): string;
function EncodeChnAndPrm(nPrm: int): string;
procedure AddArchReqToSendBuf(ID_Prm: int; ExtData: string; archType: T485RequestType);
property SAD: string read DAD; // адрес главного модуля не контролируем, всегда берем равным номеру самого прибора
public
class function ExtractFromExtData(const Extdata: string; archType: T485RequestType; var Chn, Prm: int): bool;
procedure AddRequests(); override;
end;
TSPT961AnswerParser = class
private
FArchive: TValuesCollection;
FValue: double;
FResDevNumber: int;
FResType: TSPT961AnswerType;
Buf: ArrayOfByte;
Len: int;
FResPrm: int;
FResChn: int;
procedure InitResult;
function FindMarker(Start, Marker: int): int;
function ParseHeader(posDLE, posFF: int): bool;
function ExtractChnAndParam(pos: int): bool;
function NextWord(marker: int; var pos: int; var res: string): bool;
function ParseBody: bool;
function ParseValue: bool;
function ParseTimeArray: bool;
function ParseTimeArrayString(const str: string): bool;
function ParseTimeArrayDT(const s: string): TDateTime;
public
property Archive: TValuesCollection read FArchive;
property Value: double read FValue;
property ResType: TSPT961AnswerType read FResType;
property ResDevNumber: int read FResDevNumber;
property ResChn: int read FResChn;
property ResPrm: int read FResPrm;
function Parse(ABuf: ArrayOfByte; ALen: int): bool;
function CheckInitialRequest(ReqDetails: TRequestDetails; PrmExtData: string): bool;
constructor Create();
destructor Destroy(); override;
end;
implementation
uses DateUtils, IEC_2061107, ProgramLogFile, ArchIntervalBuilder, GMSqlQuery, Generics.Collections, Math, Devices.Logica.Base;
function LogicaSPT961_CheckCRC(buf: array of Byte; Len: int): bool;
var CRC: WORD;
n: int;
begin
Result := false;
if Len < 3 then Exit;
// в начале могут быть левые символы FF, их отбросим
n := 0;
while (n < Len) and (buf[n] <> IEC_DLE) do
inc(n);
if n >= Len then Exit;
CRC := Logica_CalcCRC(buf, Len - 2, n + 2);
Result := (buf[Len - 2] = CRC div 256) and (buf[Len - 1] = CRC mod 256);
end;
{ SPT961RequestCreator }
function TSPT961ReqCreator.EncodeDT(dt: TDateTime): string;
var dd, mm, yy, hh, nn, ss, zz: WORD;
begin
DecodedateTime(dt, yy, mm, dd, hh, nn, ss, zz);
Result := strIEC_HT + EncodeNumber(dd) + strIEC_HT + EncodeNumber(mm) + strIEC_HT + EncodeNumber(yy) +
strIEC_HT + EncodeNumber(hh) + strIEC_HT + EncodeNumber(nn) + strIEC_HT + EncodeNumber(ss) ; // dd mm yy hh nn ss
end;
function TSPT961ReqCreator.EncodeChnAndPrm(nPrm: int): string;
begin
Result := strIEC_HT + EncodeNumber(Chn) + strIEC_HT + EncodeNumber(nPrm);
end;
procedure TSPT961ReqCreator.ArchData;
begin
FNC := '18'; // 18 - чтение архива
DataDLESet := EncodeChnAndPrm(ArrayTypePrmNumber()) + strIEC_FF + EncodeDT(archDT1) + strIEC_FF;
MakeBuf();
end;
procedure TSPT961ReqCreator.TimeArray;
begin
FNC := '0E'; // 0E - временной массив
// даты с-по в обратном порядке!
DataDLESet := EncodeChnAndPrm(Prm) + strIEC_FF + EncodeDT(archDT2) + strIEC_FF + EncodeDT(archDT1) + strIEC_FF;
MakeBuf();
end;
procedure TSPT961ReqCreator.ArchStructure;
begin
FNC := '19'; // 19 - структура архива
DataDLESet := EncodeChnAndPrm(ArrayTypePrmNumber()) + strIEC_FF;
MakeBuf();
end;
function TSPT961ReqCreator.ArrayTypePrmNumber: int;
begin
case ArchType of
gmarchHour: Result := 65530;
gmarchDay: Result := 65532;
gmarchMonth: Result := 65534;
else Result := 0;
end;
end;
procedure TSPT961ReqCreator.CommonPrm;
begin
FNC := '1D'; // 1D - чтение обычного параметра
DataDLESet := EncodeChnAndPrm(Prm) + strIEC_FF;
MakeBuf();
end;
function TSPT961ReqCreator.EncodeNumber(n: int): string;
var i: int;
s: string;
begin
s := IntToStr(n);
for i := 1 to Length(s) do
Result := Result + IntToHex(Ord(s[i]), 2) + ' ';
Result := Trim(Result);
end;
procedure TSPT961ReqCreator.IndexPrm;
begin
FNC := '0C'; // 0C - чтение индексного параметра
DataDLESet := strIEC_HT + EncodeNumber(Chn) + strIEC_HT + EncodeNumber(Prm) +
strIEC_HT + EncodeNumber(IdxStart) + strIEC_HT + EncodeNumber(IdxCount) + strIEC_FF;
MakeBuf();
end;
function TSPT961ReqCreator.InternalResultString: string;
begin
Result := strIEC_DLE + strIEC_SOH + DAD + SAD + strIEC_DLE + strIEC_ISI + FNC + DataDLEHead;
Result := Trim(StringReplace(Result, ' ', ' ', [rfReplaceAll]));
end;
procedure TSPT961ReqCreator.MakeBuf;
var n: int;
buf: ArrayOfByte;
begin
DAD := ' ' + IntToHex(FReqDetails.DevNumber, 2) + ' ';
DataDLEHead := strIEC_DLE + strIEC_STX + DataDLESet + strIEC_DLE + strIEC_ETX;
buf := TextNumbersStringToArray(InternalResultString());
n := Length(buf);
WriteBuf(BufSend, 0, buf, n);
LogicaSPBUS_CRC(BufSend, n);
LengthSend := n + 2;
end;
function TSPT961ReqCreator.ResultString: string;
begin
Result := ArrayToString(bufSend, LengthSend, false, true);
end;
function TSPT961ReqCreator.FromExtData(const Extdata: string; archType: T485RequestType = rqtSPT961): bool;
begin
Result := ExtractFromExtData(Extdata, archType, Chn, Prm);
end;
class function TSPT961ReqCreator.ExtractFromExtData(const Extdata: string;
archType: T485RequestType; var Chn, Prm: int): bool;
var n1, n2, c: int;
sl: TStringList;
begin
Result := false;
sl := TStringList.Create();
try
sl.Delimiter := ' ';
sl.DelimitedText := Trim(Extdata);
if sl.Count < 2 then Exit;
Val(sl[0], n1, c);
if (c > 0) or (n1 < 0) then Exit;
Val(sl[1], n2, c);
if (c > 0) or (n2 < 0) then Exit;
if archType >= rqtSPT961_DAY then // проверим третий аргумент в любом случае, даже если нам надо что-то дальше
begin
if sl.Count < 3 then Exit;
Val(sl[2], n2, c);
if (c > 0) or (n2 < 0) then Exit;
end;
if archType = rqtSPT961_HOUR then
begin
if sl.Count < 4 then Exit;
Val(sl[3], n2, c);
if (c > 0) or (n2 < 0) then Exit;
end;
Chn := n1;
Prm := n2;
Result := true;
finally
sl.Free();
end;
end;
procedure TSPT961ReqCreator.AddArchReqToSendBuf(ID_Prm: int; ExtData: string; archType: T485RequestType);
var q: TGMSqlQuery;
uptime: TDatetime;
step: Cardinal;
archTable: string;
lst: TList<ArchReqInterval>;
a: ArchReqInterval;
rqtp: T485RequestType;
intrvBuilder: TArchIntervalBuilder;
begin
// даем максимальную разбежку по времени СПТ в 5 мин
// тогда за 5 мин уже запишутся полноценные часовки и суточные
if MinuteOf(Now()) < 5 then Exit;
case archType of
rqtSPT961_DAY:
begin
uptime := Floor(Now());
archTable := 'ArchDay';
step := UTC_DAY;
rqtp := rqtSPT961_DAY;
end;
rqtSPT961_HOUR:
begin
uptime := Floor(Now()) + HourOf(Now()) * OneHour;
archTable := 'ArchHour';
step := UTC_HOUR;
rqtp := rqtSPT961_HOUR;
end;
else Exit;
end;
q := TGMSqlQuery.Create();
try
try
if not FromExtData(ExtData, archType) then Exit;
// начальные даты отсутствующих интервалов за последний месяц
q.SQL.Text := Format('select UTime from %sRequestStartDate(%d, %d) order by 1',
[archTable, ID_Prm, NowGM() - 20 * UTC_DAY]);
q.Open();
// Сгруппируем
intrvBuilder := TArchIntervalBuilder.Create(q);
lst := intrvBuilder.BuildIntervalList(step, 5);
try
for a in lst do
begin
if UTCtoLocal(a.UTime1) > uptime then break;
// В lst нам вернутся начальные даты. А прибор оперирует конечными.
archDT1 := UTCtoLocal(a.UTime1 + step);
archDT2 := Min(uptime, UTCtoLocal(a.UTime2 + step + UTC_MINUTE));
TimeArray();
FReqDetails.ID_Prm := ID_Prm;
FReqDetails.Priority := rqprArchives;
AddBufRequestToSendBuf(BufSend, LengthSend, rqtp);
end;
finally
lst.Free();
intrvBuilder.Free();
end;
except
on e: Exception do
ProgramLog().AddException('AddSPT961ArchReqToSendBuf - ' + e.Message);
end;
finally
q.Free();
end;
end;
procedure TSPT961ReqCreator.AddRequests();
var q: TGMSqlQuery;
begin
q := TGMSqlQuery.Create();
q.SQL.Text := 'select *, Abs(NowGM() - coalesce(LastArchDay, 0)) as DayReqAge, Abs(NowGM() - coalesce(LastArchHour, 0)) as HourReqAge ' +
#13#10' from Params p' +
#13#10' join Devices d on p.ID_Device = d.ID_Device ' +
#13#10' left outer join ParamStates ps on p.ID_Prm = ps.ID_Prm ' +
#13#10' where p.ID_Device = ' + IntToStr(FReqDetails.ID_Device) + ' and ID_PT > 0 order by ID_Src, N_Src';
try
q.Open();
while not q.Eof do
begin
if FromExtData(q.FieldByName('ExtData').AsString, rqtSPT961) then
begin
CommonPrm();
FReqDetails.Priority := rqprCurrents;
FReqDetails.ID_Prm := q.FieldByName('ID_Prm').AsInteger;
AddBufRequestToSendBuf(BufSend, LengthSend, rqtSPT961);
if (q.FieldByName('DayReqAge').AsInteger > UTC_HOUR) // суточные - раз в час
and (q.FieldByName('ID_Src').AsInteger in [SRC_AI, SRC_CNT_DI]) then
begin
AddArchReqToSendBuf(FReqDetails.ID_Prm, q.FieldByName('ExtData').AsString, rqtSPT961_DAY);
end;
if (q.FieldByName('HourReqAge').AsInteger > 10 * UTC_MINUTE) // часовки - каждые 10 мин
and (q.FieldByName('ID_Src').AsInteger in [SRC_AI, SRC_CNT_DI]) then
begin
AddArchReqToSendBuf(FReqDetails.ID_Prm, q.FieldByName('ExtData').AsString, rqtSPT961_HOUR);
end;
end;
q.Next();
end;
except
on e: Exception do
ProgramLog().AddException('TSPT961ReqCreator.AddRequests - ' + e.Message);
end;
q.Free();
end;
{ TSPT961RequestParser }
procedure TSPT961AnswerParser.InitResult();
begin
FResType := logicaAnswerNone;
FResDevNumber := -1;
FArchive.Clear();
end;
function TSPT961AnswerParser.FindMarker(Start, Marker: int): int;
var i: int;
begin
Result := -1;
for i := Start to Len - 1 do
begin
if buf[i] = Marker then
begin
Result := i;
Exit;
end;
end;
end;
function TSPT961AnswerParser.NextWord(marker: int; var pos: int; var res: string): bool;
var next: int;
begin
next := FindMarker(pos + 1, marker);
Result := next > pos;
if Result then
begin
res := string(ReadString(buf, pos + 1, next - pos - 1));
pos := next;
end;
end;
function TSPT961AnswerParser.ExtractChnAndParam(pos: int): bool;
var next, c: int;
s: string;
begin
Result := false;
if buf[pos] <> IEC_HT then Exit;
next := pos;
if not NextWord(IEC_HT, next, s) then Exit;
Val(s, FResChn, c);
if c > 0 then Exit;
//inc(next);
if not NextWord(IEC_FF, next, s) then Exit;
Val(s, FResPrm, c);
if c > 0 then Exit;
Result := true;
end;
function TSPT961AnswerParser.ParseHeader(posDLE, posFF: int): bool;
begin
Result := false;
// проверим звголовок
if (posFF - posDLE < 6)
or (buf[posDLE + 1] <> IEC_SOH)
or (buf[posDLE + 4] <> IEC_DLE)
or (buf[posDLE + 5] <> IEC_ISI)
or (buf[posDLE + 7] <> IEC_DLE)
or (buf[posDLE + 8] <> IEC_STX) then Exit;
case buf[posDLE + 6] of
$03: FResType := logicaAnswerValue;
//$14: FResType := logicaAnswerIndexValue;
$16: FResType := logicaAnswerTimeArray;
else Exit;
end;
if not ExtractChnAndParam(posDLE + 9) then Exit;
FResDevNumber := buf[posDLE + 3];
Result := true;
end;
function TSPT961AnswerParser.ParseValue(): bool;
var posDLE, posFF, pos: int;
s: string;
begin
Result := false;
posDLE := FindMarker(0, IEC_DLE);
posFF := FindMarker(posDLE, IEC_FF);
pos := posFF + 1;
if not NextWord(IEC_HT, pos, s) then Exit;
try
FValue := MyStrToFloat(s);
Result := FValue <> INCORRECT_VALUE;
except
end;
end;
function TSPT961AnswerParser.ParseTimeArrayDT(const s: string): TDateTime;
var dd, mm, yy, hh, nn: int;
begin
Result := 0;
if (Length(s) < 14)
or (s[3] <> '-') or (s[6] <> '-')
or (s[9] <> '/') or (s[12] <> ':') then Exit;
dd := StrToInt(s[1] + s[2]);
mm := StrToInt(s[4] + s[5]);
yy := StrToInt(s[7] + s[8]);
hh := StrToInt(s[10] + s[11]);
nn := StrToInt(s[13] + s[14]);
Result := EncodeDateTime(2000 + yy, mm, dd, hh, nn, 0, 0);
end;
function TSPT961AnswerParser.ParseTimeArrayString(const str: string): bool;
var n: int;
value: double;
dt: TDateTime;
v: TValueFromBaseItem;
begin
Result := false;
if str[1] <> AnsiChar(IEC_HT) then Exit;
n := 2;
while (n <= Length(str)) and (str[n] <> AnsiChar(IEC_HT)) do
inc(n);
if n > Length(str) then Exit;
try
value := MyStrToFloat(Copy(str, 2, n - 2));
inc(n); // пропустим единицы измерения
while (n <= Length(str)) and (str[n] <> AnsiChar(IEC_HT)) do
inc(n);
if n > Length(str) then Exit;
dt := ParseTimeArrayDT(Copy(str, n + 1, Length(str)));
if dt <= 0 then Exit;
v := FArchive.Add();
v.Val.Val := value;
v.Val.UTime := LocalToUTC(dt);
Result := value <> INCORRECT_VALUE;
except
end;
end;
function TSPT961AnswerParser.ParseTimeArray(): bool;
var posDLE, posFF, pos: int;
s: string;
begin
Result := false;
posDLE := FindMarker(0, IEC_DLE);
posFF := FindMarker(posDLE, IEC_FF);
// После канала надо пропустить две даты
pos := posFF + 1;
if not NextWord(IEC_FF, pos, s) then Exit;
if not NextWord(IEC_FF, pos, s) then Exit;
Result := true;
while NextWord(IEC_FF, pos, s) do
begin
Result := Result and ParseTimeArrayString(s);
if not Result then Exit;
end;
end;
function TSPT961AnswerParser.ParseBody(): bool;
begin
case FResType of
logicaAnswerValue: Result := ParseValue();
logicaAnswerTimeArray: Result := ParseTimeArray();
else Result := false;
end;
end;
function TSPT961AnswerParser.Parse(ABuf: ArrayOfByte; ALen: int): bool;
var posDLE, posFF: int;
begin
Result := false;
InitResult();
buf := ABuf;
Len := ALen;
if not LogicaSPT961_CheckCRC(buf, Len) then Exit;
posDLE := FindMarker(0, IEC_DLE);
if posDLE < 0 then Exit;
posFF := FindMarker(posDLE, IEC_FF);
if posFF < 0 then Exit;
if not ParseHeader(posDLE, posFF) then Exit;
Result := ParseBody();
end;
function TSPT961AnswerParser.CheckInitialRequest(ReqDetails: TRequestDetails; PrmExtData: string): bool;
var Chn, Prm: int;
begin
// тип
Result := ( (ResType = logicaAnswerValue) and (ReqDetails.rqtp = rqtSPT961) )
or ( (ResType = logicaAnswerTimeArray) and (ReqDetails.rqtp in [rqtSPT961_HOUR, rqtSPT961_DAY]) );
if not Result then Exit;
// номер прибора и канал
Result := TSPT961ReqCreator.ExtractFromExtData(PrmExtData, ReqDetails.rqtp, Chn, Prm);
if not Result then Exit;
Result := (FResChn = Chn) and (FResPrm = Prm) and (FResDevNumber = ReqDetails.DevNumber);
end;
constructor TSPT961AnswerParser.Create;
begin
FArchive := TValuesCollection.Create();
end;
destructor TSPT961AnswerParser.Destroy;
begin
FArchive.Free();
inherited;
end;
end.
|
UNIT myCrypto;
INTERFACE
TYPE T_ISAAC=object
private
randrsl: array[0..256] of dword;
randcnt: dword;
mm: array[0..256] of dword;
aa,bb,cc: dword;
PROCEDURE isaac;
PROCEDURE iRandInit;
FUNCTION iRandA: byte;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE setSeedByTime;
PROCEDURE setSeed(CONST seed:int64);
PROCEDURE setSeed(CONST seed:string);
PROCEDURE setSeed(CONST seed:array of byte);
FUNCTION iRandom : dword;
{ XOR encrypt on random stream. Output: ASCII string }
FUNCTION Vernam(CONST msg: string): string;
end;
T_sha256Hash=array[0..31] of byte;
{ T_sha256 }
T_sha256=object
private
VAR CurrentHash: array[0..7] of dword;
HashBuffer: array[0..63] of byte;
index: dword;
size: dword;
PROCEDURE compress;
public
CONSTRUCTOR create;
DESTRUCTOR destroy;
PROCEDURE fillBuffer(CONST data:array of byte; CONST dataLength:longint);
PROCEDURE fillBuffer(CONST data:string);
FUNCTION getHash:T_sha256Hash;
end;
FUNCTION sha256(CONST data:string):T_sha256Hash;
IMPLEMENTATION
PROCEDURE T_ISAAC.isaac;
VAR i,x,y: dword;
begin
{$Q-}{$R-}
cc := cc + 1; // cc just gets incremented once per 256 results
bb := bb + cc; // then combined with bb
for i := 0 to 255 do begin
x := mm[i];
case (i mod 4) of
0: aa := aa xor (aa shl 13);
1: aa := aa xor (aa shr 6 );
2: aa := aa xor (aa shl 2 );
3: aa := aa xor (aa shr 16);
end;
aa := mm[(i+128) mod 256] + aa;
y := mm[(x shr 2) mod 256] + aa + bb;
mm[i] := y;
bb := mm[(y shr 10) mod 256] + x;
randrsl[i]:= bb;
end;
randcnt:=0; // prepare to use the first set of results
{$Q+}{$R+}
end;
CONSTRUCTOR T_ISAAC.create;
begin
setSeedByTime;
end;
DESTRUCTOR T_ISAAC.destroy;
begin
end;
PROCEDURE T_ISAAC.setSeedByTime;
VAR i: dword;
begin
randomize;
for i:=0 to 255 do mm[i]:=0;
for i:=0 to 255 do randrsl[i]:=random(256);
iRandInit;
end;
PROCEDURE T_ISAAC.setSeed(CONST seed:int64);
VAR i:longint;
s:int64;
begin
for i:=0 to 255 do mm[i]:=0;
s:=seed;
for i:=0 to 255 do begin
randrsl[i]:=s and 255;
{$R-}{$Q-}
s:=((s*31) shr 1) xor s;
{$R+}{$Q+}
end;
iRandInit;
end;
PROCEDURE T_ISAAC.setSeed(CONST seed:string);
VAR i,m: longint;
begin
for i:= 0 to 255 do mm[i]:=0;
m := length(seed)-1;
for i:= 0 to 255 do begin
if i>m then randrsl[i]:=0
else randrsl[i]:=ord(seed[i+1]);
end;
iRandInit;
end;
PROCEDURE T_ISAAC.setSeed(CONST seed:array of byte);
VAR i: longint;
begin
for i:= 0 to 255 do mm[i]:=0;
for i:= 0 to 255 do begin
if i>=length(seed) then randrsl[i]:=0
else randrsl[i]:=seed[i];
end;
iRandInit;
end;
PROCEDURE T_ISAAC.iRandInit;
{$Q-}{$R-}
PROCEDURE mix(VAR a,b,c,d,e,f,g,h: dword);
begin
a := a xor b shl 11; d:=d+a; b:=b+c;
b := b xor c shr 2; e:=e+b; c:=c+d;
c := c xor d shl 8; f:=f+c; d:=d+e;
d := d xor e shr 16; g:=g+d; e:=e+f;
e := e xor f shl 10; h:=h+e; f:=f+g;
f := f xor g shr 4; a:=a+f; g:=g+h;
g := g xor h shl 8; b:=b+g; h:=h+a;
h := h xor a shr 9; c:=c+h; a:=a+b;
end;
VAR i,a,b,c,d,e,f,g,h: dword;
begin
aa:=0; bb:=0; cc:=0;
a:=$9e3779b9; // the golden ratio
b:=a; c:=a; d:=a; e:=a; f:=a; g:=a; h:=a;
for i := 0 to 3 do // scramble it
mix(a,b,c,d,e,f,g,h);
i:=0;
repeat // fill in mm[] with messy stuff
a+=randrsl[i ]; b+=randrsl[i+1]; c+=randrsl[i+2]; d+=randrsl[i+3];
e+=randrsl[i+4]; f+=randrsl[i+5]; g+=randrsl[i+6]; h+=randrsl[i+7];
mix(a,b,c,d,e,f,g,h);
mm[i ]:=a; mm[i+1]:=b; mm[i+2]:=c; mm[i+3]:=d;
mm[i+4]:=e; mm[i+5]:=f; mm[i+6]:=g; mm[i+7]:=h;
i+=8;
until i>255;
// do a second pass to make all of the seed affect all of mm
i:=0;
repeat
a+=mm[i ]; b+=mm[i+1]; c+=mm[i+2]; d+=mm[i+3];
e+=mm[i+4]; f+=mm[i+5]; g+=mm[i+6]; h+=mm[i+7];
mix(a,b,c,d,e,f,g,h);
mm[i ]:=a; mm[i+1]:=b; mm[i+2]:=c; mm[i+3]:=d;
mm[i+4]:=e; mm[i+5]:=f; mm[i+6]:=g; mm[i+7]:=h;
i+=8;
until i>255;
isaac(); // fill in the first set of results
randcnt:=0; // prepare to use the first set of results
{$Q+}{$R+}
end; {randinit}
{ Get a random 32-bit value 0..MAXINT }
FUNCTION T_ISAAC.iRandom : dword;
begin
iRandom := randrsl[randcnt];
inc(randcnt);
if (randcnt >255) then begin
isaac();
randcnt := 0;
end;
end; {iRandom}
{ Get a random character in printable ASCII range }
FUNCTION T_ISAAC.iRandA: byte;
begin
iRandA := iRandom mod 95 + 32;
end;
{ XOR encrypt on random stream. Output: ASCII string }
FUNCTION T_ISAAC.Vernam(CONST msg: string): string;
VAR i: dword;
begin
initialize(result);
setLength(result,length(msg));
for i:=1 to length(msg) do result[i]:=chr(iRandA xor ord(msg[i]));
end;
FUNCTION sha256(CONST data:string):T_sha256Hash;
VAR helper:T_sha256;
begin
helper.create;
helper.fillBuffer(data);
result:=helper.getHash;
exit;
end;
{ T_sha256 }
FUNCTION SwapDWord(CONST a: dword): dword;
begin
result:= ((a and $ff) shl 24) or ((a and $FF00) shl 8) or ((a and $FF0000) shr 8) or ((a and $FF000000) shr 24);
end;
PROCEDURE T_sha256.compress;
{$Q-}{$R-}
VAR
a, b, c, d, e, f, g, h, t1, t2: dword;
W: array[0..63] of dword;
i: longword;
begin
index:= 0;
initialize(w);
FillChar(W, sizeOf(W), 0);
a:= CurrentHash[0]; b:= CurrentHash[1]; c:= CurrentHash[2]; d:= CurrentHash[3];
e:= CurrentHash[4]; f:= CurrentHash[5]; g:= CurrentHash[6]; h:= CurrentHash[7];
move(HashBuffer,W,sizeOf(HashBuffer));
for i:= 0 to 15 do
W[i]:= SwapDWord(W[i]);
for i:= 16 to 63 do
W[i]:= (((W[i-2] shr 17) or (W[i-2] shl 15)) xor ((W[i-2] shr 19) or (W[i-2] shl 13)) xor
(W[i-2] shr 10)) + W[i-7] + (((W[i-15] shr 7) or (W[i-15] shl 25)) xor
((W[i-15] shr 18) or (W[i-15] shl 14)) xor (W[i-15] shr 3)) + W[i-16];
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $428a2f98 + W[0]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $71374491 + W[1]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $b5c0fbcf + W[2]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $e9b5dba5 + W[3]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $3956c25b + W[4]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $59f111f1 + W[5]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $923f82a4 + W[6]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $ab1c5ed5 + W[7]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $d807aa98 + W[8]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $12835b01 + W[9]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $243185be + W[10]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $550c7dc3 + W[11]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $72be5d74 + W[12]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $80deb1fe + W[13]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $9bdc06a7 + W[14]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $c19bf174 + W[15]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $e49b69c1 + W[16]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $efbe4786 + W[17]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $0fc19dc6 + W[18]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $240ca1cc + W[19]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $2de92c6f + W[20]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4a7484aa + W[21]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5cb0a9dc + W[22]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $76f988da + W[23]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $983e5152 + W[24]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $a831c66d + W[25]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $b00327c8 + W[26]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $bf597fc7 + W[27]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $c6e00bf3 + W[28]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $d5a79147 + W[29]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $06ca6351 + W[30]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $14292967 + W[31]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $27b70a85 + W[32]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $2e1b2138 + W[33]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $4d2c6dfc + W[34]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $53380d13 + W[35]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $650a7354 + W[36]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $766a0abb + W[37]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $81c2c92e + W[38]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $92722c85 + W[39]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $a2bfe8a1 + W[40]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $a81a664b + W[41]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $c24b8b70 + W[42]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $c76c51a3 + W[43]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $d192e819 + W[44]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $d6990624 + W[45]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $f40e3585 + W[46]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $106aa070 + W[47]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $19a4c116 + W[48]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $1e376c08 + W[49]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $2748774c + W[50]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $34b0bcb5 + W[51]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $391c0cb3 + W[52]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $4ed8aa4a + W[53]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $5b9cca4f + W[54]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $682e6ff3 + W[55]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
t1:= h + (((e shr 6) or (e shl 26)) xor ((e shr 11) or (e shl 21)) xor ((e shr 25) or (e shl 7))) + ((e and f) xor (not e and g)) + $748f82ee + W[56]; t2:= (((a shr 2) or (a shl 30)) xor ((a shr 13) or (a shl 19)) xor ((a shr 22) xor (a shl 10))) + ((a and b) xor (a and c) xor (b and c)); h:= t1 + t2; d:= d + t1;
t1:= g + (((d shr 6) or (d shl 26)) xor ((d shr 11) or (d shl 21)) xor ((d shr 25) or (d shl 7))) + ((d and e) xor (not d and f)) + $78a5636f + W[57]; t2:= (((h shr 2) or (h shl 30)) xor ((h shr 13) or (h shl 19)) xor ((h shr 22) xor (h shl 10))) + ((h and a) xor (h and b) xor (a and b)); g:= t1 + t2; c:= c + t1;
t1:= f + (((c shr 6) or (c shl 26)) xor ((c shr 11) or (c shl 21)) xor ((c shr 25) or (c shl 7))) + ((c and d) xor (not c and e)) + $84c87814 + W[58]; t2:= (((g shr 2) or (g shl 30)) xor ((g shr 13) or (g shl 19)) xor ((g shr 22) xor (g shl 10))) + ((g and h) xor (g and a) xor (h and a)); f:= t1 + t2; b:= b + t1;
t1:= e + (((b shr 6) or (b shl 26)) xor ((b shr 11) or (b shl 21)) xor ((b shr 25) or (b shl 7))) + ((b and c) xor (not b and d)) + $8cc70208 + W[59]; t2:= (((f shr 2) or (f shl 30)) xor ((f shr 13) or (f shl 19)) xor ((f shr 22) xor (f shl 10))) + ((f and g) xor (f and h) xor (g and h)); e:= t1 + t2; a:= a + t1;
t1:= d + (((a shr 6) or (a shl 26)) xor ((a shr 11) or (a shl 21)) xor ((a shr 25) or (a shl 7))) + ((a and b) xor (not a and c)) + $90befffa + W[60]; t2:= (((e shr 2) or (e shl 30)) xor ((e shr 13) or (e shl 19)) xor ((e shr 22) xor (e shl 10))) + ((e and f) xor (e and g) xor (f and g)); d:= t1 + t2; h:= h + t1;
t1:= c + (((h shr 6) or (h shl 26)) xor ((h shr 11) or (h shl 21)) xor ((h shr 25) or (h shl 7))) + ((h and a) xor (not h and b)) + $a4506ceb + W[61]; t2:= (((d shr 2) or (d shl 30)) xor ((d shr 13) or (d shl 19)) xor ((d shr 22) xor (d shl 10))) + ((d and e) xor (d and f) xor (e and f)); c:= t1 + t2; g:= g + t1;
t1:= b + (((g shr 6) or (g shl 26)) xor ((g shr 11) or (g shl 21)) xor ((g shr 25) or (g shl 7))) + ((g and h) xor (not g and a)) + $bef9a3f7 + W[62]; t2:= (((c shr 2) or (c shl 30)) xor ((c shr 13) or (c shl 19)) xor ((c shr 22) xor (c shl 10))) + ((c and d) xor (c and e) xor (d and e)); b:= t1 + t2; f:= f + t1;
t1:= a + (((f shr 6) or (f shl 26)) xor ((f shr 11) or (f shl 21)) xor ((f shr 25) or (f shl 7))) + ((f and g) xor (not f and h)) + $c67178f2 + W[63]; t2:= (((b shr 2) or (b shl 30)) xor ((b shr 13) or (b shl 19)) xor ((b shr 22) xor (b shl 10))) + ((b and c) xor (b and d) xor (c and d)); a:= t1 + t2; e:= e + t1;
CurrentHash[0]:= CurrentHash[0] + a;
CurrentHash[1]:= CurrentHash[1] + b;
CurrentHash[2]:= CurrentHash[2] + c;
CurrentHash[3]:= CurrentHash[3] + d;
CurrentHash[4]:= CurrentHash[4] + e;
CurrentHash[5]:= CurrentHash[5] + f;
CurrentHash[6]:= CurrentHash[6] + g;
CurrentHash[7]:= CurrentHash[7] + h;
FillChar(W,sizeOf(W),0);
FillChar(HashBuffer,sizeOf(HashBuffer),0);
{$Q+}{$R+}
end;
CONSTRUCTOR T_sha256.create;
begin
size:=0;
initialize(HashBuffer);
FillChar(HashBuffer ,sizeOf(HashBuffer ),0);
FillChar(CurrentHash,sizeOf(CurrentHash),0);
CurrentHash[0]:= $6a09e667;
CurrentHash[1]:= $bb67ae85;
CurrentHash[2]:= $3c6ef372;
CurrentHash[3]:= $a54ff53a;
CurrentHash[4]:= $510e527f;
CurrentHash[5]:= $9b05688c;
CurrentHash[6]:= $1f83d9ab;
CurrentHash[7]:= $5be0cd19;
end;
DESTRUCTOR T_sha256.destroy;
begin
end;
PROCEDURE T_sha256.fillBuffer(CONST data:array of byte; CONST dataLength: longint);
VAR remainingData:longint;
i:longint=0;
begin
size+=dataLength;
remainingData:=dataLength;
while remainingData> 0 do begin
if (sizeOf(HashBuffer)-index)<= remainingData then begin
move(data[i],HashBuffer[index],sizeOf(HashBuffer)-index);
dec(remainingData,sizeOf(HashBuffer)-index);
inc(i ,sizeOf(HashBuffer)-index);
compress;
end else begin
move(data[i],HashBuffer[index],remainingData);
inc(index,remainingData);
remainingData:= 0;
end;
end;
end;
PROCEDURE T_sha256.fillBuffer(CONST data:string);
VAR remainingData:longint;
i:longint=1;
begin
size+=length(data);
remainingData:=length(data);
while remainingData> 0 do begin
if (sizeOf(HashBuffer)-index)<= remainingData then begin
move(data[i],HashBuffer[index],sizeOf(HashBuffer)-index);
dec(remainingData,sizeOf(HashBuffer)-index);
inc(i ,sizeOf(HashBuffer)-index);
compress;
end else begin
move(data[i],HashBuffer[index],remainingData);
inc(index,remainingData);
remainingData:= 0;
end;
end;
end;
FUNCTION T_sha256.getHash: T_sha256Hash;
VAR LenHi: longword;
LenLo: longword;
begin
{$Q-}{$R-}
LenHi:=size shr 29;
LenLo:=size*8;
HashBuffer[index]:= $80;
if index>= 56 then compress;
PDWord(@HashBuffer[56])^:= SwapDWord(LenHi);
PDWord(@HashBuffer[60])^:= SwapDWord(LenLo);
compress;
initialize(CurrentHash);
initialize(result);
CurrentHash[0]:= SwapDWord(CurrentHash[0]);
CurrentHash[1]:= SwapDWord(CurrentHash[1]);
CurrentHash[2]:= SwapDWord(CurrentHash[2]);
CurrentHash[3]:= SwapDWord(CurrentHash[3]);
CurrentHash[4]:= SwapDWord(CurrentHash[4]);
CurrentHash[5]:= SwapDWord(CurrentHash[5]);
CurrentHash[6]:= SwapDWord(CurrentHash[6]);
CurrentHash[7]:= SwapDWord(CurrentHash[7]);
move(CurrentHash,result,sizeOf(CurrentHash));
{$Q+}{$R+}
end;
end.
|
unit DialogPrint;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AncestorDialogScale, StdCtrls, Mask, Buttons,
ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus,
dxSkinsCore, dxSkinsDefaultPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, cxCurrencyEdit, dsdDB, Vcl.ActnList, dsdAction, cxPropertiesStore,
dsdAddOn, cxButtons;
type
TDialogPrintForm = class(TAncestorDialogScaleForm)
PrintPanel: TPanel;
PrintCountEdit: TcxCurrencyEdit;
PrintCountLabel: TLabel;
PrintIsValuePanel: TPanel;
cbPrintMovement: TCheckBox;
cbPrintAccount: TCheckBox;
cbPrintTransport: TCheckBox;
cbPrintQuality: TCheckBox;
cbPrintPack: TCheckBox;
cbPrintSpec: TCheckBox;
cbPrintTax: TCheckBox;
cbPrintPreview: TCheckBox;
cbPrintPackGross: TCheckBox;
cbPrintDiffOrder: TCheckBox;
procedure cbPrintTransportClick(Sender: TObject);
procedure cbPrintQualityClick(Sender: TObject);
procedure cbPrintTaxClick(Sender: TObject);
procedure cbPrintAccountClick(Sender: TObject);
procedure cbPrintPackClick(Sender: TObject);
procedure cbPrintSpecClick(Sender: TObject);
private
function Checked: boolean; override;//Проверка корректного ввода в Edit
public
function Execute(MovementDescId:Integer;CountMovement:Integer; isMovement, isAccount, isTransport, isQuality, isPack, isPackGross, isSpec, isTax : Boolean): Boolean; virtual;
end;
var
DialogPrintForm: TDialogPrintForm;
implementation
{$R *.dfm}
uses UtilScale;
{------------------------------------------------------------------------------}
function TDialogPrintForm.Execute(MovementDescId:Integer;CountMovement:Integer; isMovement, isAccount, isTransport, isQuality, isPack, isPackGross, isSpec, isTax : Boolean): Boolean; //Проверка корректного ввода в Edit
begin
// для ScaleCeh только одна печать
if (SettingMain.isCeh = TRUE)or((MovementDescId<>zc_Movement_Sale)and(MovementDescId<>zc_Movement_SendOnPrice))
then cbPrintMovement.Checked:= TRUE
else cbPrintMovement.Checked:= isMovement;
//
cbPrintPackGross.Checked:= FALSE;
cbPrintDiffOrder.Checked:= FALSE;//(MovementDescId=zc_Movement_Sale)or(MovementDescId=zc_Movement_SendOnPrice);
//
cbPrintAccount.Enabled:=(SettingMain.isCeh = FALSE);//or(MovementDescId=zc_Movement_Sale)or(MovementDescId<>zc_Movement_SendOnPrice);
cbPrintTransport.Enabled:=cbPrintAccount.Enabled;
cbPrintQuality.Enabled:=cbPrintAccount.Enabled;
cbPrintPack.Enabled:=cbPrintAccount.Enabled;
cbPrintSpec.Enabled:=cbPrintAccount.Enabled;
cbPrintTax.Enabled:=cbPrintAccount.Enabled;
cbPrintDiffOrder.Enabled:=cbPrintAccount.Enabled;
//
cbPrintAccount.Checked:=(isAccount) and (cbPrintAccount.Enabled);
cbPrintTransport.Checked:=(isTransport) and (cbPrintTransport.Enabled);
cbPrintQuality.Checked:=(isQuality) and (cbPrintQuality.Enabled);
cbPrintPack.Checked:=(isPack) and (cbPrintPack.Enabled);
cbPrintSpec.Checked:=(isSpec) and (cbPrintSpec.Enabled);
cbPrintTax.Checked:=(isTax) and (cbPrintTax.Enabled);
//
cbPrintPreview.Checked:=GetArrayList_Value_byName(Default_Array,'isPrintPreview') = AnsiUpperCase('TRUE');
if SettingMain.isCeh = FALSE
then PrintCountEdit.Text:=IntToStr(CountMovement)
else PrintCountEdit.Text:=GetArrayList_Value_byName(Default_Array,'PrintCount');
//
ActiveControl:=PrintCountEdit;
//
Result:=(ShowModal=mrOk);
end;
{------------------------------------------------------------------------------}
function TDialogPrintForm.Checked: boolean; //Проверка корректного ввода в Edit
begin
try Result:=(StrToInt(PrintCountEdit.Text)>0) and (StrToInt(PrintCountEdit.Text)<11);
except Result:=false;
end;
//
if not Result then ShowMessage('Ошибка.Значение <Кол-во копий> не попадает в диапазон от <1> до <10>.')
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintTransportClick(Sender: TObject);
begin
if cbPrintTransport.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)
and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice)
then cbPrintTransport.Checked:=false;
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintQualityClick(Sender: TObject);
begin
if cbPrintQuality.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)
and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice)
and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Loss)
then cbPrintQuality.Checked:=false;
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintTaxClick(Sender: TObject);
begin
if cbPrintTax.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)
or (GetArrayList_Value_byName(Default_Array,'isTax') <> AnsiUpperCase('TRUE'))
then cbPrintTax.Checked:=false;
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintAccountClick(Sender: TObject);
begin
if cbPrintAccount.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)
then cbPrintAccount.Checked:=false;
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintPackClick(Sender: TObject);
begin
if cbPrintPack.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice)
then cbPrintPack.Checked:=false;
end;
{------------------------------------------------------------------------------}
procedure TDialogPrintForm.cbPrintSpecClick(Sender: TObject);
begin
if cbPrintSpec.Checked
then
if (ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_Sale)and(ParamsMovement.ParamByName('MovementDescId').AsInteger<>zc_Movement_SendOnPrice)
then cbPrintSpec.Checked:=false;
end;
{------------------------------------------------------------------------------}
end.
|
unit ALimpaBancoDados;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls,
PainelGradiente, StdCtrls, Buttons, DB, DBClient, Tabela, CBancoDados, FMTBcd, SqlExpr,
ComCtrls;
type
TFLimpaBancoDados = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BLimpar: TBitBtn;
BFechar: TBitBtn;
CLog: TCheckBox;
CMovEstoqueProdutos: TCheckBox;
CLogReceber: TCheckBox;
CRetornoItem: TCheckBox;
Label1: TLabel;
EPeriodo: TComboBoxColor;
Aux: TSQL;
CTarefaEmarketing: TCheckBox;
Paginas: TPageControl;
PanelColor3: TPanelColor;
PGEral: TTabSheet;
PLog: TTabSheet;
ELog: TMemoColor;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BLimparClick(Sender: TObject);
procedure BFecharClick(Sender: TObject);
private
{ Private declarations }
VprTotalRegistroApagados : Integer;
function RDataLimpeza : TDateTime;
procedure AtualizaLog(VpaTexto : String);
procedure LimpaLog;
procedure LimpaLogReceber;
procedure limpamovestoqueprodutos;
procedure LimpaRetornoItem;
procedure LimpaTarefaEmarketing;
public
{ Public declarations }
end;
var
FLimpaBancoDados: TFLimpaBancoDados;
implementation
uses APrincipal, FunData, funSQL, constmsg;
{$R *.DFM}
{ **************************************************************************** }
procedure TFLimpaBancoDados.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
end;
{******************************************************************************}
procedure TFLimpaBancoDados.LimpaLog;
Var
VpfQtdRegistros : Integer;
begin
AtualizaLog('Verificando a quantidade de registros da tabela LOG');
AdicionaSQLAbreTabela(Aux,'Select COUNT(*) QTD FROM LOG '+
' Where DAT_LOG <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela LOG');
ExecutaComandoSql(Aux,'Delete from LOG '+
' Where DAT_LOG <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela LOG');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
end;
{******************************************************************************}
procedure TFLimpaBancoDados.LimpaLogReceber;
Var
VpfQtdRegistros : Integer;
begin
AtualizaLog('Verificando a quantidade de registros da tabela LOGCONTASARECEBER');
AdicionaSQLAbreTabela(Aux,'Select COUNT(*) QTD FROM LOGCONTASARECEBER '+
' Where DATLOG <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela LOGCONTASARECEBER');
ExecutaComandoSql(Aux,'Delete from LOGCONTASARECEBER '+
' Where DATLOG <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela LOGCONTASARECEBER');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
end;
{******************************************************************************}
procedure TFLimpaBancoDados.limpamovestoqueprodutos;
Var
VpfQtdRegistros : Integer;
begin
AtualizaLog('Verificando a quantidade de registros da tabela MOVESTOQUEPRODUTOS');
AdicionaSQLAbreTabela(Aux,'Select COUNT(*) QTD FROM MOVESTOQUEPRODUTOS '+
' Where D_DAT_MOV <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela MOVESTOQUEPRODUTOS');
ExecutaComandoSql(Aux,'Delete from MOVESTOQUEPRODUTOS '+
' Where D_DAT_MOV <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela MOVESTOQUEPRODUTOS');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
end;
{******************************************************************************}
procedure TFLimpaBancoDados.LimpaRetornoItem;
Var
VpfQtdRegistros : Integer;
begin
AtualizaLog('Verificando a quantidade de registros da tabela RETORNOITEM');
AdicionaSQLAbreTabela(Aux,'Select COUNT(*) QTD FROM RETORNOITEM '+
' Where DATOCORRENCIA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela RETORNOITEM');
ExecutaComandoSql(Aux,'Delete from RETORNOITEM '+
' Where DATOCORRENCIA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza));
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela RETORNOITEM');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
end;
{******************************************************************************}
procedure TFLimpaBancoDados.LimpaTarefaEmarketing;
Var
VpfQtdRegistros : Integer;
begin
AtualizaLog('Verificando a quantidade de registros da tabela TAREFAEMARKETINGITEM');
AdicionaSQLAbreTabela(Aux,'SELECT COUNT(*) QTD FROM TAREFAEMARKETINGITEM ITE '+
' WHERE SEQTAREFA IN ( SELECT SEQTAREFA FROM TAREFAEMARKETING TAR '+
' WHERE DATTAREFA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza)+')');
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela TAREFAEMARKETINGITEM');
ExecutaComandoSql(Aux,'DELETE FROM TAREFAEMARKETINGITEM ITE '+
' WHERE SEQTAREFA IN ( SELECT SEQTAREFA FROM TAREFAEMARKETING TAR '+
' WHERE DATTAREFA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza)+')');
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela TAREFAEMARKETINGITEM');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
AtualizaLog('Verificando a quantidade de registros da tabela TAREFAEMARKETINGPROSPECTITEM');
AdicionaSQLAbreTabela(Aux,'SELECT COUNT(*) QTD FROM TAREFAEMARKETINGPROSPECTITEM ITE '+
' WHERE SEQTAREFA IN ( SELECT SEQTAREFA FROM TAREFAEMARKETINGPROSPECT TAR '+
' WHERE DATTAREFA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza)+')');
VpfQtdRegistros := Aux.FieldByName('QTD').AsInteger;
AtualizaLog('Apagando registros tabela TAREFAEMARKETINGPROSPECTITEM');
ExecutaComandoSql(Aux,'DELETE FROM TAREFAEMARKETINGPROSPECTITEM ITE '+
' WHERE SEQTAREFA IN ( SELECT SEQTAREFA FROM TAREFAEMARKETINGPROSPECT TAR '+
' WHERE DATTAREFA <= ' +SQLTextoDataAAAAMMMDD(RDataLimpeza)+')');
AtualizaLog(IntToStr(VpfQtdRegistros)+' registros apagandos da tabela TAREFAEMARKETINGPROSPECTITEM');
VprTotalRegistroApagados := VprTotalRegistroApagados +VpfQtdRegistros;
AtualizaLog('Total de registros apagados '+IntToStr(VprTotalRegistroApagados));
end;
{******************************************************************************}
function TFLimpaBancoDados.RDataLimpeza: TDateTime;
begin
case EPeriodo.ItemIndex of
0 : Result := DecMes(PrimeiroDiaMes(date),3);
1 : Result := DecMes(PrimeiroDiaMes(date),6);
2 : Result := DecMes(PrimeiroDiaMes(date),12);
end;
end;
{ *************************************************************************** }
procedure TFLimpaBancoDados.AtualizaLog(VpaTexto: String);
begin
ELog.Lines.Add(VpaTexto);
ELog.Refresh;
end;
{******************************************************************************}
procedure TFLimpaBancoDados.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFLimpaBancoDados.BLimparClick(Sender: TObject);
begin
VprTotalRegistroApagados := 0;
ELog.Clear;
Paginas.ActivePage := PLog;
if CLog.Checked then
LimpaLog;
if CLogReceber.Checked then
LimpaLogReceber;
if CMovEstoqueProdutos.Checked then
limpamovestoqueprodutos;
if CRetornoItem.Checked then
LimpaRetornoItem;
if CTarefaEmarketing.Checked then
LimpaTarefaEmarketing;
aviso('Banco de dados limpo com sucesso.');
end;
procedure TFLimpaBancoDados.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFLimpaBancoDados]);
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
//
//主要实现:
//-----------------------------------------------------------------------------}
unit untEasyClasshrEmployee;
interface
uses
Classes, DB, DBClient, Variants;
type
TEasyhrEmployee = class
private
{ Private declarations }
FEmployeeGUID: string;
FEmployeeCName: string;
FEmployeeEName: string;
FSexGUID: string;
FBirthday: TDateTime;
FStature: Double;
FBroodGUID: string;
FNationGUID: string;
FNativePlaceGUID: string;
FIdentityCard: string;
FStudyExperienceGUID: string;
FSpeciality: string;
FMarryGUID: string;
FPolityStatusGUID: string;
FGraduateInstitute: string;
// FPhoto: EasyNULLType;
FPersonContactTel: string;
FFamilyContactTel: string;
FOtherContact: string;
FEmail: string;
FResidence: string;
FInServiceGUID: string;
FPositionGUID: string;
FOthersPositionGUID: string;
FResidenceTypeGUID: string;
FInsureNo: string;
FPayMentNo: string;
FCompanyGUID: string;
FDepartmentGUID: string;
FInCompanyDate: TDateTime;
FTryoutDate: TDateTime;
FFormalDate: TDateTime;
FEmpContractNo: string;
FEndDate: TDateTime;
FEmployeeTypeGUID: string;
FCallTitleGUID: string;
FCallTitleDate: TDateTime;
FForeignLangaugeLevelGUID: string;
FComputerTechnolicGUID: string;
FFamilyAddress: string;
FRemark: string;
FIsEnable: Boolean;
FOrderNo: Integer;
FRightNum: Integer;
FBarCode: string;
FICCardID: string;
FInputDate: TDateTime;
FUserGUID: string;
public
{ Public declarations }
property EmployeeGUID: string read FEmployeeGUID write FEmployeeGUID;
property EmployeeCName: string read FEmployeeCName write FEmployeeCName;
property EmployeeEName: string read FEmployeeEName write FEmployeeEName;
property SexGUID: string read FSexGUID write FSexGUID;
property Birthday: TDateTime read FBirthday write FBirthday;
property Stature: Double read FStature write FStature;
property BroodGUID: string read FBroodGUID write FBroodGUID;
property NationGUID: string read FNationGUID write FNationGUID;
property NativePlaceGUID: string read FNativePlaceGUID write FNativePlaceGUID;
property IdentityCard: string read FIdentityCard write FIdentityCard;
property StudyExperienceGUID: string read FStudyExperienceGUID write FStudyExperienceGUID;
property Speciality: string read FSpeciality write FSpeciality;
property MarryGUID: string read FMarryGUID write FMarryGUID;
property PolityStatusGUID: string read FPolityStatusGUID write FPolityStatusGUID;
property GraduateInstitute: string read FGraduateInstitute write FGraduateInstitute;
// property Photo: EasyNULLType read FPhoto write FPhoto;
property PersonContactTel: string read FPersonContactTel write FPersonContactTel;
property FamilyContactTel: string read FFamilyContactTel write FFamilyContactTel;
property OtherContact: string read FOtherContact write FOtherContact;
property Email: string read FEmail write FEmail;
property Residence: string read FResidence write FResidence;
property InServiceGUID: string read FInServiceGUID write FInServiceGUID;
property PositionGUID: string read FPositionGUID write FPositionGUID;
property OthersPositionGUID: string read FOthersPositionGUID write FOthersPositionGUID;
property ResidenceTypeGUID: string read FResidenceTypeGUID write FResidenceTypeGUID;
property InsureNo: string read FInsureNo write FInsureNo;
property PayMentNo: string read FPayMentNo write FPayMentNo;
property CompanyGUID: string read FCompanyGUID write FCompanyGUID;
property DepartmentGUID: string read FDepartmentGUID write FDepartmentGUID;
property InCompanyDate: TDateTime read FInCompanyDate write FInCompanyDate;
property TryoutDate: TDateTime read FTryoutDate write FTryoutDate;
property FormalDate: TDateTime read FFormalDate write FFormalDate;
property EmpContractNo: string read FEmpContractNo write FEmpContractNo;
property EndDate: TDateTime read FEndDate write FEndDate;
property EmployeeTypeGUID: string read FEmployeeTypeGUID write FEmployeeTypeGUID;
property CallTitleGUID: string read FCallTitleGUID write FCallTitleGUID;
property CallTitleDate: TDateTime read FCallTitleDate write FCallTitleDate;
property ForeignLangaugeLevelGUID: string read FForeignLangaugeLevelGUID write FForeignLangaugeLevelGUID;
property ComputerTechnolicGUID: string read FComputerTechnolicGUID write FComputerTechnolicGUID;
property FamilyAddress: string read FFamilyAddress write FFamilyAddress;
property Remark: string read FRemark write FRemark;
property IsEnable: Boolean read FIsEnable write FIsEnable;
property OrderNo: Integer read FOrderNo write FOrderNo;
property RightNum: Integer read FRightNum write FRightNum;
property BarCode: string read FBarCode write FBarCode;
property ICCardID: string read FICCardID write FICCardID;
property InputDate: TDateTime read FInputDate write FInputDate;
property UserGUID: string read FUserGUID write FUserGUID;
class procedure GeneratehrEmployee(var Data: OleVariant; AResult: TList);
class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
class procedure InitSinglehrEmployee(AClientDataSet: TClientDataSet; var AObj: TEasyhrEmployee);
end;
implementation
{TEasyhrEmployee}
class procedure TEasyhrEmployee.GeneratehrEmployee(var Data: OleVariant; AResult: TList);
var
I: Integer;
AEasyhrEmployee: TEasyhrEmployee;
AClientDataSet: TClientDataSet;
begin
//创建数据源,并获取数据
AClientDataSet := TClientDataSet.Create(nil);
AClientDataSet.Data := Data;
AClientDataSet.First;
try
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
//此句为实例化指定的对象
AEasyhrEmployee := TEasyhrEmployee.Create;
with AEasyhrEmployee do
begin
//1 EmployeeGUID
EmployeeGUID := AClientDataSet.FieldByName('EmployeeGUID').AsString;
//2 EmployeeCName
EmployeeCName := AClientDataSet.FieldByName('EmployeeCName').AsString;
//3 EmployeeEName
EmployeeEName := AClientDataSet.FieldByName('EmployeeEName').AsString;
//4 SexGUID
SexGUID := AClientDataSet.FieldByName('SexGUID').AsString;
//5 Birthday
Birthday := AClientDataSet.FieldByName('Birthday').AsDateTime;
//6 Stature
Stature := AClientDataSet.FieldByName('Stature').AsFloat;
//7 BroodGUID
BroodGUID := AClientDataSet.FieldByName('BroodGUID').AsString;
//8 NationGUID
NationGUID := AClientDataSet.FieldByName('NationGUID').AsString;
//9 NativePlaceGUID
NativePlaceGUID := AClientDataSet.FieldByName('NativePlaceGUID').AsString;
//10 IdentityCard
IdentityCard := AClientDataSet.FieldByName('IdentityCard').AsString;
//11 StudyExperienceGUID
StudyExperienceGUID := AClientDataSet.FieldByName('StudyExperienceGUID').AsString;
//12 Speciality
Speciality := AClientDataSet.FieldByName('Speciality').AsString;
//13 MarryGUID
MarryGUID := AClientDataSet.FieldByName('MarryGUID').AsString;
//14 PolityStatusGUID
PolityStatusGUID := AClientDataSet.FieldByName('PolityStatusGUID').AsString;
//15 GraduateInstitute
GraduateInstitute := AClientDataSet.FieldByName('GraduateInstitute').AsString;
//16 Photo
// Photo := AClientDataSet.FieldByName('Photo').AsEasyNullType;
//17 PersonContactTel
PersonContactTel := AClientDataSet.FieldByName('PersonContactTel').AsString;
//18 FamilyContactTel
FamilyContactTel := AClientDataSet.FieldByName('FamilyContactTel').AsString;
//19 OtherContact
OtherContact := AClientDataSet.FieldByName('OtherContact').AsString;
//20 Email
Email := AClientDataSet.FieldByName('Email').AsString;
//21 Residence
Residence := AClientDataSet.FieldByName('Residence').AsString;
//22 InServiceGUID
InServiceGUID := AClientDataSet.FieldByName('InServiceGUID').AsString;
//23 PositionGUID
PositionGUID := AClientDataSet.FieldByName('PositionGUID').AsString;
//24 OthersPositionGUID
OthersPositionGUID := AClientDataSet.FieldByName('OthersPositionGUID').AsString;
//25 ResidenceTypeGUID
ResidenceTypeGUID := AClientDataSet.FieldByName('ResidenceTypeGUID').AsString;
//26 InsureNo
InsureNo := AClientDataSet.FieldByName('InsureNo').AsString;
//27 PayMentNo
PayMentNo := AClientDataSet.FieldByName('PayMentNo').AsString;
//28 CompanyGUID
CompanyGUID := AClientDataSet.FieldByName('CompanyGUID').AsString;
//29 DepartmentGUID
DepartmentGUID := AClientDataSet.FieldByName('DepartmentGUID').AsString;
//30 InCompanyDate
InCompanyDate := AClientDataSet.FieldByName('InCompanyDate').AsDateTime;
//31 TryoutDate
TryoutDate := AClientDataSet.FieldByName('TryoutDate').AsDateTime;
//32 FormalDate
FormalDate := AClientDataSet.FieldByName('FormalDate').AsDateTime;
//33 EmpContractNo
EmpContractNo := AClientDataSet.FieldByName('EmpContractNo').AsString;
//34 EndDate
EndDate := AClientDataSet.FieldByName('EndDate').AsDateTime;
//35 EmployeeTypeGUID
EmployeeTypeGUID := AClientDataSet.FieldByName('EmployeeTypeGUID').AsString;
//36 CallTitleGUID
CallTitleGUID := AClientDataSet.FieldByName('CallTitleGUID').AsString;
//37 CallTitleDate
CallTitleDate := AClientDataSet.FieldByName('CallTitleDate').AsDateTime;
//38 ForeignLangaugeLevelGUID
ForeignLangaugeLevelGUID := AClientDataSet.FieldByName('ForeignLangaugeLevelGUID').AsString;
//39 ComputerTechnolicGUID
ComputerTechnolicGUID := AClientDataSet.FieldByName('ComputerTechnolicGUID').AsString;
//40 FamilyAddress
FamilyAddress := AClientDataSet.FieldByName('FamilyAddress').AsString;
//41 Remark
Remark := AClientDataSet.FieldByName('Remark').AsString;
//42 IsEnable
IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean;
//43 OrderNo
OrderNo := AClientDataSet.FieldByName('OrderNo').AsInteger;
//44 RightNum
RightNum := AClientDataSet.FieldByName('RightNum').AsInteger;
//45 BarCode
BarCode := AClientDataSet.FieldByName('BarCode').AsString;
//46 ICCardID
ICCardID := AClientDataSet.FieldByName('ICCardID').AsString;
//47 InputDate
InputDate := AClientDataSet.FieldByName('InputDate').AsDateTime;
//48 UserGUID
UserGUID := AClientDataSet.FieldByName('UserGUID').AsString;
end;
//在此添加将对象存放到指定容器的代码
AResult.Add(AEasyhrEmployee);
//如果要关联树也在此添加相应代码
AClientDataSet.Next;
end;
finally
AClientDataSet.Free;
end;
end;
class procedure TEasyhrEmployee.AppendClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
begin
with ACds do
begin
Append;
//1 EmployeeGUID
FieldByName('EmployeeGUID').AsString := AObj.EmployeeGUID;
//2 EmployeeCName
FieldByName('EmployeeCName').AsString := AObj.EmployeeCName;
//3 EmployeeEName
FieldByName('EmployeeEName').AsString := AObj.EmployeeEName;
//4 SexGUID
FieldByName('SexGUID').AsString := AObj.SexGUID;
//5 Birthday
FieldByName('Birthday').AsDateTime := AObj.Birthday;
//6 Stature
FieldByName('Stature').AsFloat := AObj.Stature;
//7 BroodGUID
FieldByName('BroodGUID').AsString := AObj.BroodGUID;
//8 NationGUID
FieldByName('NationGUID').AsString := AObj.NationGUID;
//9 NativePlaceGUID
FieldByName('NativePlaceGUID').AsString := AObj.NativePlaceGUID;
//10 IdentityCard
FieldByName('IdentityCard').AsString := AObj.IdentityCard;
//11 StudyExperienceGUID
FieldByName('StudyExperienceGUID').AsString := AObj.StudyExperienceGUID;
//12 Speciality
FieldByName('Speciality').AsString := AObj.Speciality;
//13 MarryGUID
FieldByName('MarryGUID').AsString := AObj.MarryGUID;
//14 PolityStatusGUID
FieldByName('PolityStatusGUID').AsString := AObj.PolityStatusGUID;
//15 GraduateInstitute
FieldByName('GraduateInstitute').AsString := AObj.GraduateInstitute;
//16 Photo
// FieldByName('Photo').AsEasyNullType := AObj.Photo;
//17 PersonContactTel
FieldByName('PersonContactTel').AsString := AObj.PersonContactTel;
//18 FamilyContactTel
FieldByName('FamilyContactTel').AsString := AObj.FamilyContactTel;
//19 OtherContact
FieldByName('OtherContact').AsString := AObj.OtherContact;
//20 Email
FieldByName('Email').AsString := AObj.Email;
//21 Residence
FieldByName('Residence').AsString := AObj.Residence;
//22 InServiceGUID
FieldByName('InServiceGUID').AsString := AObj.InServiceGUID;
//23 PositionGUID
FieldByName('PositionGUID').AsString := AObj.PositionGUID;
//24 OthersPositionGUID
FieldByName('OthersPositionGUID').AsString := AObj.OthersPositionGUID;
//25 ResidenceTypeGUID
FieldByName('ResidenceTypeGUID').AsString := AObj.ResidenceTypeGUID;
//26 InsureNo
FieldByName('InsureNo').AsString := AObj.InsureNo;
//27 PayMentNo
FieldByName('PayMentNo').AsString := AObj.PayMentNo;
//28 CompanyGUID
FieldByName('CompanyGUID').AsString := AObj.CompanyGUID;
//29 DepartmentGUID
FieldByName('DepartmentGUID').AsString := AObj.DepartmentGUID;
//30 InCompanyDate
FieldByName('InCompanyDate').AsDateTime := AObj.InCompanyDate;
//31 TryoutDate
FieldByName('TryoutDate').AsDateTime := AObj.TryoutDate;
//32 FormalDate
FieldByName('FormalDate').AsDateTime := AObj.FormalDate;
//33 EmpContractNo
FieldByName('EmpContractNo').AsString := AObj.EmpContractNo;
//34 EndDate
FieldByName('EndDate').AsDateTime := AObj.EndDate;
//35 EmployeeTypeGUID
FieldByName('EmployeeTypeGUID').AsString := AObj.EmployeeTypeGUID;
//36 CallTitleGUID
FieldByName('CallTitleGUID').AsString := AObj.CallTitleGUID;
//37 CallTitleDate
FieldByName('CallTitleDate').AsDateTime := AObj.CallTitleDate;
//38 ForeignLangaugeLevelGUID
FieldByName('ForeignLangaugeLevelGUID').AsString := AObj.ForeignLangaugeLevelGUID;
//39 ComputerTechnolicGUID
FieldByName('ComputerTechnolicGUID').AsString := AObj.ComputerTechnolicGUID;
//40 FamilyAddress
FieldByName('FamilyAddress').AsString := AObj.FamilyAddress;
//41 Remark
FieldByName('Remark').AsString := AObj.Remark;
//42 IsEnable
FieldByName('IsEnable').AsBoolean := AObj.IsEnable;
//43 OrderNo
FieldByName('OrderNo').AsInteger := AObj.OrderNo;
//44 RightNum
FieldByName('RightNum').AsInteger := AObj.RightNum;
//45 BarCode
FieldByName('BarCode').AsString := AObj.BarCode;
//46 ICCardID
FieldByName('ICCardID').AsString := AObj.ICCardID;
//47 InputDate
FieldByName('InputDate').AsDateTime := AObj.InputDate;
//48 UserGUID
FieldByName('UserGUID').AsString := AObj.UserGUID;
post;
end;
AObjList.Add(AObj);
end;
class procedure TEasyhrEmployee.EditClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
begin
if ACds.Locate('EmployeeGUID', VarArrayOf([AObj.EmployeeGUID]), [loCaseInsensitive]) then
begin
with ACds do
begin
Edit;
//1 EmployeeGUID
FieldByName('EmployeeGUID').AsString := AObj.EmployeeGUID;
//2 EmployeeCName
FieldByName('EmployeeCName').AsString := AObj.EmployeeCName;
//3 EmployeeEName
FieldByName('EmployeeEName').AsString := AObj.EmployeeEName;
//4 SexGUID
FieldByName('SexGUID').AsString := AObj.SexGUID;
//5 Birthday
FieldByName('Birthday').AsDateTime := AObj.Birthday;
//6 Stature
FieldByName('Stature').AsFloat := AObj.Stature;
//7 BroodGUID
FieldByName('BroodGUID').AsString := AObj.BroodGUID;
//8 NationGUID
FieldByName('NationGUID').AsString := AObj.NationGUID;
//9 NativePlaceGUID
FieldByName('NativePlaceGUID').AsString := AObj.NativePlaceGUID;
//10 IdentityCard
FieldByName('IdentityCard').AsString := AObj.IdentityCard;
//11 StudyExperienceGUID
FieldByName('StudyExperienceGUID').AsString := AObj.StudyExperienceGUID;
//12 Speciality
FieldByName('Speciality').AsString := AObj.Speciality;
//13 MarryGUID
FieldByName('MarryGUID').AsString := AObj.MarryGUID;
//14 PolityStatusGUID
FieldByName('PolityStatusGUID').AsString := AObj.PolityStatusGUID;
//15 GraduateInstitute
FieldByName('GraduateInstitute').AsString := AObj.GraduateInstitute;
//16 Photo
// FieldByName('Photo').AsEasyNullType := AObj.Photo;
//17 PersonContactTel
FieldByName('PersonContactTel').AsString := AObj.PersonContactTel;
//18 FamilyContactTel
FieldByName('FamilyContactTel').AsString := AObj.FamilyContactTel;
//19 OtherContact
FieldByName('OtherContact').AsString := AObj.OtherContact;
//20 Email
FieldByName('Email').AsString := AObj.Email;
//21 Residence
FieldByName('Residence').AsString := AObj.Residence;
//22 InServiceGUID
FieldByName('InServiceGUID').AsString := AObj.InServiceGUID;
//23 PositionGUID
FieldByName('PositionGUID').AsString := AObj.PositionGUID;
//24 OthersPositionGUID
FieldByName('OthersPositionGUID').AsString := AObj.OthersPositionGUID;
//25 ResidenceTypeGUID
FieldByName('ResidenceTypeGUID').AsString := AObj.ResidenceTypeGUID;
//26 InsureNo
FieldByName('InsureNo').AsString := AObj.InsureNo;
//27 PayMentNo
FieldByName('PayMentNo').AsString := AObj.PayMentNo;
//28 CompanyGUID
FieldByName('CompanyGUID').AsString := AObj.CompanyGUID;
//29 DepartmentGUID
FieldByName('DepartmentGUID').AsString := AObj.DepartmentGUID;
//30 InCompanyDate
FieldByName('InCompanyDate').AsDateTime := AObj.InCompanyDate;
//31 TryoutDate
FieldByName('TryoutDate').AsDateTime := AObj.TryoutDate;
//32 FormalDate
FieldByName('FormalDate').AsDateTime := AObj.FormalDate;
//33 EmpContractNo
FieldByName('EmpContractNo').AsString := AObj.EmpContractNo;
//34 EndDate
FieldByName('EndDate').AsDateTime := AObj.EndDate;
//35 EmployeeTypeGUID
FieldByName('EmployeeTypeGUID').AsString := AObj.EmployeeTypeGUID;
//36 CallTitleGUID
FieldByName('CallTitleGUID').AsString := AObj.CallTitleGUID;
//37 CallTitleDate
FieldByName('CallTitleDate').AsDateTime := AObj.CallTitleDate;
//38 ForeignLangaugeLevelGUID
FieldByName('ForeignLangaugeLevelGUID').AsString := AObj.ForeignLangaugeLevelGUID;
//39 ComputerTechnolicGUID
FieldByName('ComputerTechnolicGUID').AsString := AObj.ComputerTechnolicGUID;
//40 FamilyAddress
FieldByName('FamilyAddress').AsString := AObj.FamilyAddress;
//41 Remark
FieldByName('Remark').AsString := AObj.Remark;
//42 IsEnable
FieldByName('IsEnable').AsBoolean := AObj.IsEnable;
//43 OrderNo
FieldByName('OrderNo').AsInteger := AObj.OrderNo;
//44 RightNum
FieldByName('RightNum').AsInteger := AObj.RightNum;
//45 BarCode
FieldByName('BarCode').AsString := AObj.BarCode;
//46 ICCardID
FieldByName('ICCardID').AsString := AObj.ICCardID;
//47 InputDate
FieldByName('InputDate').AsDateTime := AObj.InputDate;
//48 UserGUID
FieldByName('UserGUID').AsString := AObj.UserGUID;
post;
end;
end;
end;
class procedure TEasyhrEmployee.DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasyhrEmployee; var AObjList: TList);
var
I,
DelIndex: Integer;
begin
DelIndex := -1;
if ACds.Locate('EmployeeGUID', VarArrayOf([AObj.EmployeeGUID]), [loCaseInsensitive]) then
ACds.Delete;
for I := 0 to AObjList.Count - 1 do
begin
if TEasyhrEmployee(AObjList[I]).EmployeeGUID = TEasyhrEmployee(AObj).EmployeeGUID then
begin
DelIndex := I;
Break;
end;
end;
if DelIndex <> -1 then
begin
TEasyhrEmployee(AObjList[DelIndex]).Free;
AObjList.Delete(DelIndex);
end;
end;
class procedure TEasyhrEmployee.InitSinglehrEmployee(
AClientDataSet: TClientDataSet; var AObj: TEasyhrEmployee);
begin
with AObj do
begin
//1 EmployeeGUID
EmployeeGUID := AClientDataSet.FieldByName('EmployeeGUID').AsString;
//2 EmployeeCName
EmployeeCName := AClientDataSet.FieldByName('EmployeeCName').AsString;
//3 EmployeeEName
EmployeeEName := AClientDataSet.FieldByName('EmployeeEName').AsString;
//4 SexGUID
SexGUID := AClientDataSet.FieldByName('SexGUID').AsString;
//5 Birthday
Birthday := AClientDataSet.FieldByName('Birthday').AsDateTime;
//6 Stature
Stature := AClientDataSet.FieldByName('Stature').AsFloat;
//7 BroodGUID
BroodGUID := AClientDataSet.FieldByName('BroodGUID').AsString;
//8 NationGUID
NationGUID := AClientDataSet.FieldByName('NationGUID').AsString;
//9 NativePlaceGUID
NativePlaceGUID := AClientDataSet.FieldByName('NativePlaceGUID').AsString;
//10 IdentityCard
IdentityCard := AClientDataSet.FieldByName('IdentityCard').AsString;
//11 StudyExperienceGUID
StudyExperienceGUID := AClientDataSet.FieldByName('StudyExperienceGUID').AsString;
//12 Speciality
Speciality := AClientDataSet.FieldByName('Speciality').AsString;
//13 MarryGUID
MarryGUID := AClientDataSet.FieldByName('MarryGUID').AsString;
//14 PolityStatusGUID
PolityStatusGUID := AClientDataSet.FieldByName('PolityStatusGUID').AsString;
//15 GraduateInstitute
GraduateInstitute := AClientDataSet.FieldByName('GraduateInstitute').AsString;
//16 Photo
// Photo := AClientDataSet.FieldByName('Photo').AsEasyNullType;
//17 PersonContactTel
PersonContactTel := AClientDataSet.FieldByName('PersonContactTel').AsString;
//18 FamilyContactTel
FamilyContactTel := AClientDataSet.FieldByName('FamilyContactTel').AsString;
//19 OtherContact
OtherContact := AClientDataSet.FieldByName('OtherContact').AsString;
//20 Email
Email := AClientDataSet.FieldByName('Email').AsString;
//21 Residence
Residence := AClientDataSet.FieldByName('Residence').AsString;
//22 InServiceGUID
InServiceGUID := AClientDataSet.FieldByName('InServiceGUID').AsString;
//23 PositionGUID
PositionGUID := AClientDataSet.FieldByName('PositionGUID').AsString;
//24 OthersPositionGUID
OthersPositionGUID := AClientDataSet.FieldByName('OthersPositionGUID').AsString;
//25 ResidenceTypeGUID
ResidenceTypeGUID := AClientDataSet.FieldByName('ResidenceTypeGUID').AsString;
//26 InsureNo
InsureNo := AClientDataSet.FieldByName('InsureNo').AsString;
//27 PayMentNo
PayMentNo := AClientDataSet.FieldByName('PayMentNo').AsString;
//28 CompanyGUID
CompanyGUID := AClientDataSet.FieldByName('CompanyGUID').AsString;
//29 DepartmentGUID
DepartmentGUID := AClientDataSet.FieldByName('DepartmentGUID').AsString;
//30 InCompanyDate
InCompanyDate := AClientDataSet.FieldByName('InCompanyDate').AsDateTime;
//31 TryoutDate
TryoutDate := AClientDataSet.FieldByName('TryoutDate').AsDateTime;
//32 FormalDate
FormalDate := AClientDataSet.FieldByName('FormalDate').AsDateTime;
//33 EmpContractNo
EmpContractNo := AClientDataSet.FieldByName('EmpContractNo').AsString;
//34 EndDate
EndDate := AClientDataSet.FieldByName('EndDate').AsDateTime;
//35 EmployeeTypeGUID
EmployeeTypeGUID := AClientDataSet.FieldByName('EmployeeTypeGUID').AsString;
//36 CallTitleGUID
CallTitleGUID := AClientDataSet.FieldByName('CallTitleGUID').AsString;
//37 CallTitleDate
CallTitleDate := AClientDataSet.FieldByName('CallTitleDate').AsDateTime;
//38 ForeignLangaugeLevelGUID
ForeignLangaugeLevelGUID := AClientDataSet.FieldByName('ForeignLangaugeLevelGUID').AsString;
//39 ComputerTechnolicGUID
ComputerTechnolicGUID := AClientDataSet.FieldByName('ComputerTechnolicGUID').AsString;
//40 FamilyAddress
FamilyAddress := AClientDataSet.FieldByName('FamilyAddress').AsString;
//41 Remark
Remark := AClientDataSet.FieldByName('Remark').AsString;
//42 IsEnable
IsEnable := AClientDataSet.FieldByName('IsEnable').AsBoolean;
//43 OrderNo
OrderNo := AClientDataSet.FieldByName('OrderNo').AsInteger;
//44 RightNum
RightNum := AClientDataSet.FieldByName('RightNum').AsInteger;
//45 BarCode
BarCode := AClientDataSet.FieldByName('BarCode').AsString;
//46 ICCardID
ICCardID := AClientDataSet.FieldByName('ICCardID').AsString;
//47 InputDate
InputDate := AClientDataSet.FieldByName('InputDate').AsDateTime;
//48 UserGUID
UserGUID := AClientDataSet.FieldByName('UserGUID').AsString;
end;
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Медиа-сервер }
{ }
{ <Область> 16:Медиа-контроль }
{ }
{ <Задача> Медиа-источник, предоставляющий чтение данных из источника, }
{ поддерживающего протокол RTSP }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 14.01.2011 }
{ }
{ <Примечание> Нет примечаний. }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaServer.Stream.Source.RTSP;
interface
uses Windows, SysUtils, Classes, MediaStream.DataSource.RTSP, MediaServer.Stream.Source;
type
//Класс, выполняющий непосредственно получение данных (видеопотока) из камеры
TMediaServerSourceRTSP = class (TMediaServerSourceBasedOnMediaStream)
private
FURL: string;
FOverTCP: boolean;
public
constructor Create(const aURL: string;
aOverTCP: boolean;
aTransmitAudio: boolean; //Записывать ли аудио
aDataReceiveTimeout: integer //таймаут получения данных от канала
); overload;
destructor Destroy; override;
function Name: string; override;
function DeviceType: string; override;
function ConnectionString: string; override;
end;
implementation
{ TMediaServerSourceRTSP }
function TMediaServerSourceRTSP.ConnectionString: string;
begin
result:=FURL;
if FOverTCP then
result:=result+' (RTP over TCP)';
end;
constructor TMediaServerSourceRTSP.Create(const aURL: string; aOverTCP: boolean;
aTransmitAudio: boolean; //Записывать ли аудио
aDataReceiveTimeout: integer //таймаут получения данных от канала
);
var
aParams: TMediaStreamDataSourceConnectParams_RTSP;
begin
aParams:=TMediaStreamDataSourceConnectParams_RTSP.Create(aURL,aOverTCP,true,aTransmitAudio);
inherited Create(aParams, TMediaStreamDataSource_RTSP, aTransmitAudio, aDataReceiveTimeout);
FURL:=aURL;
FOverTCP:=aOverTCP;
end;
destructor TMediaServerSourceRTSP.Destroy;
begin
inherited;
end;
function TMediaServerSourceRTSP.DeviceType: string;
begin
result:='RTSP';
end;
function TMediaServerSourceRTSP.Name: string;
begin
Result := FURL;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC tracer }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Stan.Tracer;
interface
uses
System.SysUtils, System.Classes,
FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Stan.Intf;
type
TFDTracer = class;
{ --------------------------------------------------------------------------- }
{ TFDTracer }
{ --------------------------------------------------------------------------- }
TFDTracer = class(TFDThread)
private
FTraceFileName: String;
FTraceFileHandler: TFDTextFile;
FTraceFileAppend: Boolean;
FCounter: Int64;
FTraceFileColumns: TFDTraceFileColumns;
FTraceFileEncoding: TFDEncoding;
procedure CheckInactive;
procedure SetTraceFileName(const AValue: String);
procedure SetTraceFileAppend(AValue: Boolean);
procedure OpenTraceFiles;
procedure CloseTraceFiles;
procedure SetTraceFileEncoding(const Value: TFDEncoding);
protected
class function GetStartMsgClass: TFDThreadMsgClass; override;
class function GetStopMsgClass: TFDThreadMsgClass; override;
class function GetTerminateMsgClass: TFDThreadMsgClass; override;
function DoAllowTerminate: Boolean; override;
procedure DoActiveChanged; override;
procedure DoIdle; override;
public
constructor Create;
procedure TraceMsg(const AObjClassName, AObjName, AMsg: String);
property TraceFileName: String read FTraceFileName write SetTraceFileName;
property TraceFileAppend: Boolean read FTraceFileAppend write SetTraceFileAppend;
property TraceFileColumns: TFDTraceFileColumns read FTraceFileColumns write FTraceFileColumns;
property TraceFileEncoding: TFDEncoding read FTraceFileEncoding write SetTraceFileEncoding;
end;
var
FADShowTraces: Boolean = True;
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SyncObjs, System.Diagnostics,
FireDAC.Stan.Consts, FireDAC.Stan.ResStrs;
var
GTracesLock: TCriticalSection;
GTraces: TFDStringList = nil;
type
TFDTracerMsgBase = class;
TFDTracerStartMsg = class;
TFDTracerStopMsg = class;
TFDTracerTerminateMsg = class;
TFDTracerOutputMsg = class;
{ --------------------------------------------------------------------------- }
{ TFDTracerMsgBase }
{ --------------------------------------------------------------------------- }
TFDTracerMsgBase = class(TFDThreadMsgBase)
private
FCounter: Int64;
FTime: TDateTime;
FThreadID: TThreadID;
public
constructor Create; override;
function Perform(AThread: TFDThread): Boolean; override;
function AsString(AItems: TFDTraceFileColumns): String; virtual;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerStartMsg }
{ --------------------------------------------------------------------------- }
TFDTracerStartMsg = class(TFDTracerMsgBase)
public
constructor Create; override;
function Perform(AThread: TFDThread): Boolean; override;
function AsString(AItems: TFDTraceFileColumns): String; override;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerStopMsg }
{ --------------------------------------------------------------------------- }
TFDTracerStopMsg = class(TFDTracerMsgBase)
public
function Perform(AThread: TFDThread): Boolean; override;
function AsString(AItems: TFDTraceFileColumns): String; override;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerTerminateMsg }
{ --------------------------------------------------------------------------- }
TFDTracerTerminateMsg = class(TFDTracerMsgBase)
public
function Perform(AThread: TFDThread): Boolean; override;
function AsString(AItems: TFDTraceFileColumns): String; override;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerOutputMsg }
{ --------------------------------------------------------------------------- }
TFDTracerOutputMsg = class(TFDTracerMsgBase)
private
FObjClassName: String;
FObjID: String;
FMsgText: String;
public
constructor Create(const AObjectClassName, AObjID, AMsgText: String); overload;
function AsString(AItems: TFDTraceFileColumns): String; override;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerMsgBase }
{ --------------------------------------------------------------------------- }
constructor TFDTracerMsgBase.Create;
begin
inherited Create;
FCounter := TStopwatch.GetTimeStamp();
FTime := Time();
FThreadID := TThread.CurrentThread.ThreadID;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerMsgBase.AsString(AItems: TFDTraceFileColumns): String;
var
s: String;
begin
if tiRefNo in AItems then
Result := Format('%8d ', [FCounter])
else
Result := '';
if tiTime in AItems then begin
DateTimeToString(s, 'hh:nn:ss.zzz ', FTime);
Result := Result + s;
end;
if tiThreadID in AItems then
Result := Result + Format('%8d ', [FThreadID]);
end;
{ --------------------------------------------------------------------------- }
function TFDTracerMsgBase.Perform(AThread: TFDThread): Boolean;
var
oTracer: TFDTracer;
begin
oTracer := AThread as TFDTracer;
Inc(FCounter);
Self.FCounter := FCounter;
if oTracer.FTraceFileHandler <> nil then
oTracer.FTraceFileHandler.WriteLine(AsString(oTracer.FTraceFileColumns));
Result := True;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerStartMsg }
{ --------------------------------------------------------------------------- }
constructor TFDTracerStartMsg.Create;
begin
inherited Create;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerStartMsg.Perform(AThread: TFDThread): Boolean;
var
oMsg: TFDThreadStartMsg;
begin
(AThread as TFDTracer).OpenTraceFiles;
inherited Perform(AThread);
oMsg := TFDThreadStartMsg.Create;
try
Result := oMsg.Perform(AThread);
finally
FDFree(oMsg);
end;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerStartMsg.AsString(AItems: TFDTraceFileColumns): String;
begin
Result := inherited AsString(AItems) + '-=#!!! FireDAC Tracer started !!!#=-';
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerStopMsg }
{ --------------------------------------------------------------------------- }
function TFDTracerStopMsg.Perform(AThread: TFDThread): Boolean;
var
oMsg: TFDThreadStopMsg;
begin
inherited Perform(AThread);
(AThread as TFDTracer).CloseTraceFiles;
oMsg := TFDThreadStopMsg.Create;
try
Result := oMsg.Perform(AThread);
finally
FDFree(oMsg);
end;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerStopMsg.AsString(AItems: TFDTraceFileColumns): String;
begin
Result := inherited AsString(AItems) + '-=#!!! FireDAC Tracer stopped !!!#=-';
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerTerminateMsg }
{ --------------------------------------------------------------------------- }
function TFDTracerTerminateMsg.Perform(AThread: TFDThread): Boolean;
var
oMsg: TFDThreadTerminateMsg;
begin
inherited Perform(AThread);
oMsg := TFDThreadTerminateMsg.Create;
try
Result := oMsg.Perform(AThread);
finally
FDFree(oMsg);
end;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerTerminateMsg.AsString(AItems: TFDTraceFileColumns): String;
begin
Result := inherited AsString(AItems) + '-=#!!! FireDAC Tracer terminated !!!#=-';
end;
{ --------------------------------------------------------------------------- }
{ TFDTracerOutputMsg }
{ --------------------------------------------------------------------------- }
constructor TFDTracerOutputMsg.Create(const AObjectClassName, AObjID, AMsgText: String);
begin
inherited Create;
FObjClassName := AObjectClassName;
FObjID := AObjID;
FMsgText := AMsgText;
end;
{ --------------------------------------------------------------------------- }
function TFDTracerOutputMsg.AsString(AItems: TFDTraceFileColumns): String;
begin
Result := inherited AsString(AItems);
if tiClassName in AItems then
Result := Result + FDPadR(FObjClassName, 32) + ' ';
if tiObjID in AItems then
Result := Result + FDPadR(FObjID, 20) + ' ';
if tiMsgText in AItems then
Result := Result + FMsgText;
end;
{ --------------------------------------------------------------------------- }
{ TFDTracer }
{ --------------------------------------------------------------------------- }
constructor TFDTracer.Create;
begin
inherited Create;
FreeOnTerminate := False;
FTraceFileAppend := C_FD_MonitorAppend;
FTraceFileColumns := C_FD_MonitorColumns;
end;
{ --------------------------------------------------------------------------- }
class function TFDTracer.GetStartMsgClass: TFDThreadMsgClass;
begin
Result := TFDTracerStartMsg;
end;
{ --------------------------------------------------------------------------- }
class function TFDTracer.GetStopMsgClass: TFDThreadMsgClass;
begin
Result := TFDTracerStopMsg;
end;
{ --------------------------------------------------------------------------- }
class function TFDTracer.GetTerminateMsgClass: TFDThreadMsgClass;
begin
Result := TFDTracerTerminateMsg;
end;
{ --------------------------------------------------------------------------- }
function TFDTracer.DoAllowTerminate: Boolean;
begin
if Messages = nil then
Result := True
else begin
Result := Messages.LockList.Count = 0;
Messages.UnlockList;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.DoActiveChanged;
begin
if not Active then
while not DoAllowTerminate do
Sleep(1);
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.DoIdle;
begin
if (FTraceFileHandler <> nil) and (FTraceFileHandler.Stream <> nil) and
(FTraceFileHandler.Stream is TBufferedFileStream) then
TBufferedFileStream(FTraceFileHandler.Stream).FlushBuffer;
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.CheckInactive;
begin
if Active then
raise EFDException.Create(sMb_TracerPropertyChangeOnlyActiveFalse);
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.SetTraceFileName(const AValue: String);
begin
CheckInactive;
FTraceFileName := FDExpandStr(AValue);
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.SetTraceFileAppend(AValue: Boolean);
begin
CheckInactive;
FTraceFileAppend := AValue;
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.SetTraceFileEncoding(const Value: TFDEncoding);
begin
CheckInactive;
FTraceFileEncoding := Value;
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.OpenTraceFiles;
begin
FCounter := 0;
if FTraceFileHandler <> nil then
raise EFDException.Create(sMb_TracerTraceFileHasToBeClosed);
if FTraceFileName = '' then
raise EFDException.Create(sMb_TracerTraceFileNameNotAssigned);
FTraceFileHandler := TFDTextFile.Create(FTraceFileName,
False, FTraceFileAppend, FTraceFileEncoding, elWindows);
FTraceFileHandler.WriteLine('--- new start of FireDAC Trace ---');
if GTraces <> nil then begin
GTracesLock.Enter;
try
if GTraces.IndexOf(FTraceFileName) = -1 then
GTraces.Add(FTraceFileName);
finally
GTracesLock.Leave;
end;
end;
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.CloseTraceFiles;
begin
if FTraceFileHandler = nil then
raise EFDException.Create(sMb_TracerTraceFileHasToBeOpen);
FDFreeAndNil(FTraceFileHandler);
end;
{ --------------------------------------------------------------------------- }
procedure TFDTracer.TraceMsg(const AObjClassName, AObjName, AMsg: String);
begin
if (Self <> nil) and Active then
EnqueueMsg(TFDTracerOutputMsg.Create(AObjClassName, AObjName, AMsg));
end;
{ --------------------------------------------------------------------------- }
procedure ShowTraces;
var
sMsg: String;
begin
sMsg := C_FD_Product + ' produced following application trace files:' +
C_FD_EOL + GTraces.Text;
{$IFDEF MSWINDOWS}
sMsg := sMsg + C_FD_EOL + 'Press OK to close application.';
{$ENDIF}
FDSystemMessage(C_FD_Product + ' MonitorBy=FlatFile', sMsg, False);
end;
{ --------------------------------------------------------------------------- }
initialization
GTracesLock := TCriticalSection.Create;
GTraces := TFDStringList.Create;
finalization
GTracesLock.Enter;
try
if FADShowTraces and (GTraces.Count > 0) and not FDIsDesignTime then
ShowTraces;
FDFreeAndNil(GTraces);
finally
GTracesLock.Leave;
FDFreeAndNil(GTracesLock);
end;
end.
|
unit IdIRC;
{
TIRCClient component for Borland Delphi 5.0 or above
by Steve 'Sly' Williams (stevewilliams@kromestudios.com)
ported to Indy by Daaron Dwyer (ddwyer@ncic.com)
File: IRCClient.pas
Version: 1.06
Objects: TIRCClient, TUser, TUsers, TChannel, TChannels, TIdIRCReplies
Requires: Indy9
Provides a simple, high-level interface to the IRC network. Set the
properties and write event handlers for the events you wish to respond to.
Any events that do not have a specific event handler will continue normal
processing (ie. reply to a request, ignore a message, etc).
I have tried to keep the TIRCClient object as independent as possible from
the user interface implementation. This is so the user interface is not
constrained by any inherent limitations placed upon it by the implementation
of the TIRCClient object itself, thus leaving the user interface to be as
standard or as non-standard as the designer wishes.
This is a non-visual component, and should be placed either on the main form
or in a data module, where all units can easily access the component.
The command numerics and server operation are based on RFC1459, the original
specification for IRC. Any change from the specification is due to the
differences that have been noted from practical experience. There may be
some IRC networks that operate differently and therefore do not operate with
this TIRCClient object in the correct manner. If you do have any information
that would make the TIRCClient object more compatible with current or planned
IRC networks, then e-mail me so that I may add these features to the next
release.
History:
1.00 Initial release
1.01 1/03/1999
- Changed SocketDataAvailable to handle lines ending with either CRLF
(within spec) or a single LF (breaks spec). It seems a few servers
break the rules. Also added check for a non-zero Error parameter.
1.02 5/04/1999
- Added SocksServer and SocksPort properties as requested by Joe
(cybawiz@softhome.net).
1.03 13/05/1999
- Moved the creation of the TWSocket to the overridden Loaded
procedure to get rid of the annoying "A device attached to the
system is not functioning" error when recompiling the package.
1.04 28/11/1999
- If Suppress in the OnRaw event was set to True, the User object
would not have been released.
- Uncommented the OnJoin and OnPart events. Not sure why I had them
commented out.
1.05 02/12/1999
- Fixed the Replies property and made it published. The TIdIRCReplies
object had to descend from TPersistent, not TObject. Oops.
- Fixed the Client property of TUser, TUsers, TChannel and TChannels.
Made a forward declaration of TIRCClient and used that as the type.
1.06 25/05/2000
- Fixed TUsers.Destroy and TChannels.Destroy. The list items were not
being deleted after the objects were freed. Silly error on my part.
1.061 27/07/2001 - Daaron Dwyer (ddwyer@ncic.com)
- Modified component to use Indy TCPClient control rather than ICS
1.062 10/11/2001 - J. Peter Mugaas
- added ACmd Integer parameter to TIdIRCOnSystem as suggested by Andrew P.Rybin
- added Channel to OnNames event as suggested by Sven Orro
TUser object
-------------------------------------
Properties:
Nick The user's nickname.
Address The full address of the user.
Count Count of the number of objects referencing this
user. This user is removed when the reference
count drops to zero.
Data A reference to an object defined by the client.
Usually references the message window for this user.
Methods:
Say Send a message to this user.
TUsers object
-------------------------------------
Properties:
none
Methods:
Add Increments the reference count for this user. If the
user does not exist, then a new user is created with
a reference count of one. Returns the TUser object
for the user.
Remove Decrement the reference count for this user. The
user is only deleted if the reference count becomes
zero.
Address Return the address of a specified nick.
Find Returns the index of the user if the nick is found.
Get Returns the user object if the nick is found.
Nick Change the nick of an existing user.
TChannel object
-------------------------------------
Properties:
Name Channel name.
Topic Current topic of the channel (if set).
Mode Set of channel modes.
Limit Set if a limit is set to the number of users in a
channel.
Key Set if a password key is set for the channel.
ModeChange True if mode changes are being compiled.
Data A reference to an object defined by the client.
Usually references the message window for this
channel.
Methods:
Say Send a message to the channel.
Part Part the channel.
Kick Kick a nick from the channel.
Topic Set the channel topic.
BeginMode Compile but do not send mode changes until the
EndMode method is called.
EndMode Compile all mode changes since BeginMode and send to
the server.
Op Give a user channel operator status.
Deop Remove channel operator status from a user.
Voice Give a voice to a user in a moderated channel.
Devoice Remove the voice from a user in a moderated channel.
Ban Ban a user from the channel.
Unban Remove a ban from the channel.
TopicChanged Call to change the topic without sending a topic
command (ie. when another user changes the topic).
ModeChanged Call to change the channel mode without sending a
mode command (ie. when another user changes the
mode).
LimitChanged Call to change the channel limit without sending a
mode command (ie. when another user changes the
limit).
KeyChanged Call to change the channel key without sending a
mode command (ie. when another user changes the
key).
AddUser Add a user to the channel.
RemoveUser Remove a user from the channel.
TChannels object
-------------------------------------
Properties:
none
Methods:
Add Add a new channel to the list.
Remove Remove a channel from the list.
Find Find a channel name, if it exists.
Get Returns the channel object for the name given.
TIRCClient component
-------------------------------------
Design-time properties:
Nick The primary nick to be used. Defaults to 'Nick'.
AltNick Another nick to use if the primary nick is already
in use. Defaults to 'OtherNick'.
UserName Your username (for the system you are using).
RealName The information you want displayed in your whois
response.
Server Address of the IRC server to connect to.
Port Server port number to connect to. Defaults to
'6667'.
Password Password to connect (if required).
UserMode Set of user modes. Defaults to an empty set.
umInvisible, umOperator, umServerNotices, umWallops.
SocksServer Address of the SOCKS server to connect through.
SocksPort Port number of the SOCKS server to connect through.
Run-time properties:
Connected Returns True if currently connected to the IRC
network.
Away Set to True if you are marked as away.
Notify List of nicknames/addresses to be notified of when
they join/leave IRC.
State The current connection state.
Channels The list of channel objects.
Replies
Finger Standard CTCP reply for FINGER requests.
Version Standard CTCP reply for VERSION requests.
UserInfo Standard CTCP reply for USERINFO requests.
ClientInfo Standard CTCP reply for CLIENTINFO requests.
Events:
OnConnect Connected to the IRC network.
OnDisconnect Disconnected from the IRC network.
OnChannelMessage Received a channel message.
OnChannelNotice Received a channel notice.
OnChannelAction Received a channel action.
OnPrivateMessage Received a private message.
OnPrivateNotice Received a private notice.
OnPrivateAction Received a private action.
OnJoin A user joined a channel.
OnJoined You joined a channel.
OnPart A user parted a channel.
OnParted You parted a channel.
OnKick A user kicked another user from a channel.
OnKicked You were kicked from a channel by a user.
OnNickChange A user changed their nick.
OnNickChanged Your nick was changed.
OnTopic The topic of the channel was changed.
OnQuit A user quit IRC.
OnNames Received a list of names of people in a channel.
OnInvite A user has invited you to a channel.
OnInviting You invited a user to a channel.
OnPingPong Received a server ping (PONG response sent
automatically).
OnError Error message from server.
OnAway Received an away message for a user.
OnNowAway You are marked as being away.
OnUnAway You are no longer marked as being away.
OnWallops Received a wallops message.
OnSystem Any response from the server not handled by a
specific event handler.
OnRaw Every command from the IRC server goes through this
handler first. Normal processing can be suppressed
by setting the Suppress parameter to True.
OnOp A user was oped in a channel.
OnDeop A user was deoped in a channel.
OnBan A user was banned in a channel.
OnUnban A user was unbanned in a channel.
OnVoice A user was given a voice in a channel.
OnDevoice A user's voice was taken away in a channel.
OnChannelMode The channel mode was changed.
OnChannelModeChanged Called after the channel mode change has been parsed
and the mode was changed.
OnUserMode Your user mode was changed.
OnUserModeChanged Called after the user mode change has been parsed
and the mode was changed.
OnKill A user was killed.
OnUnknownCommand An unknown command was received from the server.
OnStateChange Called when the current state of the IRC connection
changes.
OnSend Called for every command sent to the IRC server.
Useful for displaying in a raw output window.
OnReceive Called for every command is received from the IRC
server. Useful for displaying in a raw output
window.
OnNicksInUse Called during the registration process when both Nick
and AltNick are in use.
OnSocketError An error occurred in the TCP/IP socket.
OnNoTopic There is no topic for this channel.
OnChannelMode The channel mode is now set.
OnLinks Results from a /LINK command
OnList Results from a /LIST command
The following CTCP query event handlers can suppress the standard response by
setting the Suppress parameter to True.
OnCTCPQuery A user sent you a CTCP query.
OnCTCPReply Received a reply from a CTCP query.
Events to be added later:
OnOped You were oped in a channel.
OnDeoped You were deoped in a channel.
OnBanned You were banned in a channel.
OnUnbanned You were unbanned in a channel.
OnVoiced You were given a voice in a channel.
OnDevoiced Your voice was taken away in a channel.
OnKilled You were killed.
OnNotify A person on your notify list has joined IRC.
OnDenotify A person on your notify list has left IRC.
OnLag Update on the current lag time.
DCC events to be added later
OnChat Someone wants to initiate a DCC chat.
OnChatClosed The DCC chat was closed.
OnFileReceive Someone wants to send you a file.
OnFileReceived The file was received successfully.
OnFileSend A file is offered to someone.
OnFileSent The file was sent successfully.
OnFileError There was an error during file transfer.
OnDCC General DCC event handler.
*TEMPDCC EVENTS UNTIL ABOVE ARE DONE*:
OnDCCChat Someone wants to DCC Chat
OnDCCSend Someone wants to Send you a File Via DCC
OnDCCResume Someone is requesting a DCC File RESUME
OnDCCAccept Someone has ACCEPTED your DCC File RESUME request
Set the Accept parameter to True to accept the DCC. Set the Resume
parameter to True to resume a DCC file transfer. Set the Filename parameter
to the full path and name of the place to store the received file.
Methods:
Connect Connect to the IRC network.
Disconnect Force a disconnect from the IRC network.
Raw Send the command directly to the IRC server.
Say Send a message to a user/channel.
Notice Send a notice to a user/channel.
Join Join channel/s with given key/s.
Part Part channel/s with an optional reason (if supported
by the IRC server).
Kick Kick a person from a channel.
Quit Quit the IRC network.
CTCP Send a CTCP command to a user/channel.
CTCPReply Send a reply to a CTCP command.
IsChannel Returns True if the name is a channel name.
IsOp Returns True if the user has operator status.
IsVoice Returns True if the user has a voice.
MatchHostmask Returns True if the address matches the hostmask.
GetTopic Get the topic for the specified channel.
SetTopic Set the topic for the specifiec channel.
Methods to be added later:
Ban Ban hostmask/s from a channel.
Unban Unban hostmask/s from a channel.
Op Op nick/s in a channel.
Deop Deop nick/s in a channel.
Voice Give a voice to nick/s.
Devoice Take voice from nick/s.
Invite Invite someone to a channel.
DCCChat Initiate a DCC chat.
DCCSend Initiate a DCC send of a file.
}
interface
uses
Classes, IdAssignedNumbers, IdBaseComponent, IdComponent, IdTCPConnection,
IdException, IdTCPClient, IdThread, IdStack, IdGlobal;
const
{ Numerics as defined in RFC1459. }
RPL_TRACELINK = 200 ; { Link <version & debug level> <destination> <next server> }
RPL_TRACECONNECTING = 201 ; { Try. <class> <server> }
RPL_TRACEHANDSHAKE = 202 ; { H.S. <class> <server> }
RPL_TRACEUNKNOWN = 203 ; { ???? <class> [<client IP address in dot form>] }
RPL_TRACEOPERATOR = 204 ; { Oper <class> <nick> }
RPL_TRACEUSER = 205 ; { User <class> <nick> }
RPL_TRACESERVER = 206 ; { Serv <class> <int>S <int>C <server> <nick!user|*!*>@<host|server> }
RPL_TRACENEWTYPE = 208 ; { <newtype> 0 <client name> }
RPL_STATSLINKINFO = 211 ; { <linkname> <sendq> <sent messages> <sent bytes> <received messages> <received bytes> <time open> }
RPL_STATSCOMMANDS = 212 ; { <command> <count> }
RPL_STATSCLINE = 213 ; { C <host> * <name> <port> <class> }
RPL_STATSNLINE = 214 ; { N <host> * <name> <port> <class> }
RPL_STATSILINE = 215 ; { I <host> * <host> <port> <class> }
RPL_STATSKLINE = 216 ; { K <host> * <username> <port> <class> }
RPL_STATSYLINE = 218 ; { Y <class> <ping frequency> <connect frequency> <max sendq> }
RPL_ENDOFSTATS = 219 ; { <stats letter> :End of /STATS report }
RPL_UMODEIS = 221 ; { <user mode string> }
RPL_STATSLLINE = 241 ; { L <hostmask> * <servername> <maxdepth> }
RPL_STATSUPTIME = 242 ; { :Server Up %d days %d:%02d:%02d }
RPL_STATSOLINE = 243 ; { O <hostmask> * <name> }
RPL_STATSHLINE = 244 ; { H <hostmask> * <servername> }
RPL_LUSERCLIENT = 251 ; { :There are <integer> users and <integer> invisible on <integer> servers }
RPL_LUSEROP = 252 ; { <integer> :operator(s) online }
RPL_LUSERUNKNOWN = 253 ; { <integer> :unknown connection(s) }
RPL_LUSERCHANNELS = 254 ; { <integer> :channels formed }
RPL_LUSERME = 255 ; { :I have <integer> clients and <integer> servers }
RPL_ADMINME = 256 ; { <server> :Administrative info }
RPL_ADMINLOC1 = 257 ; { :<admin info> }
RPL_ADMINLOC2 = 258 ; { :<admin info> }
RPL_ADMINEMAIL = 259 ; { :<admin info> }
RPL_TRACELOG = 261 ; { File <logfile> <debug level> }
RPL_NONE = 300 ; { Dummy reply number. Not used. }
RPL_AWAY = 301 ; { <nick> :<away message> }
RPL_USERHOST = 302 ; { :[<reply><space><reply>] }
RPL_ISON = 303 ; { :[<nick> <space><nick>] }
RPL_UNAWAY = 305 ; { :You are no longer marked as being away }
RPL_NOWAWAY = 306 ; { :You have been marked as being away }
RPL_WHOISUSER = 311 ; { <nick> <user> <host> * :<real name> }
RPL_WHOISSERVER = 312 ; { <nick> <server> :<server info> }
RPL_WHOISOPERATOR = 313 ; { <nick> :is an IRC operator }
RPL_WHOWASUSER = 314 ; { <nick> <user> <host> * :<real name> }
RPL_ENDOFWHO = 315 ; { <name> :End of /WHO list }
RPL_WHOISIDLE = 317 ; { <nick> <integer> :seconds idle }
RPL_ENDOFWHOIS = 318 ; { <nick> :End of /WHOIS list }
RPL_WHOISCHANNELS = 319 ; { <nick> :[@|+]<channel><space> }
RPL_LISTSTART = 321 ; { Channel :Users Name }
RPL_LIST = 322 ; { <channel> <# visible> :<topic> }
RPL_LISTEND = 323 ; { :End of /LIST }
RPL_CHANNELMODEIS = 324 ; { <channel> <mode> <mode params> }
RPL_NOTOPIC = 331 ; { <channel> :No topic is set }
RPL_TOPIC = 332 ; { <channel> :<topic> }
RPL_INVITING = 341 ; { <channel> <nick> }
RPL_SUMMONING = 342 ; { <user> :Summoning user to IRC }
RPL_VERSION = 351 ; { <version>.<debuglevel> <server> :<comments> }
RPL_WHOREPLY = 352 ; { <channel> <user> <host> <server> <nick> <H|G>[*][@|+] :<hopcount> <real name> }
RPL_NAMREPLY = 353 ; { <channel> :[[@|+]<nick> [[@|+]<nick> [...]]] }
RPL_LINKS = 364 ; { <mask> <server> :<hopcount> <server info> }
RPL_ENDOFLINKS = 365 ; { <mask> :End of /LINKS list }
RPL_ENDOFNAMES = 366 ; { <channel> :End of /NAMES list }
RPL_BANLIST = 367 ; { <channel> <banid> }
RPL_ENDOFBANLIST = 368 ; { <channel> :End of channel ban list }
RPL_ENDOFWHOWAS = 369 ; { <nick> :End of WHOWAS }
RPL_INFO = 371 ; { :<string> }
RPL_MOTD = 372 ; { :- <text> }
RPL_ENDOFINFO = 374 ; { :End of /INFO list }
RPL_MOTDSTART = 375 ; { ":- <server> Message of the day -," }
RPL_ENDOFMOTD = 376 ; { :End of /MOTD command }
RPL_YOUREOPER = 381 ; { :You are now an IRC operator }
RPL_REHASHING = 382 ; { <config file> :Rehashing }
RPL_TIME = 391 ; { }
RPL_USERSSTART = 392 ; { :UserID Terminal Host }
RPL_USERS = 393 ; { :%-8s %-9s %-8s }
RPL_ENDOFUSERS = 394 ; { :End of users }
RPL_NOUSERS = 395 ; { :Nobody logged in }
ERR_NOSUCHNICK = 401 ; { <nickname> :No such nick/channel }
ERR_NOSUCHSERVER = 402 ; { <server name> :No such server }
ERR_NOSUCHCHANNEL = 403 ; { <channel name> :No such channel }
ERR_CANNOTSENDTOCHAN = 404 ; { <channel name> :Cannot send to channel }
ERR_TOOMANYCHANNELS = 405 ; { <channel name> :You have joined too many channels }
ERR_WASNOSUCHNICK = 406 ; { <nickname> :There was no such nickname }
ERR_TOOMANYTARGETS = 407 ; { <target> :Duplicate recipients. No message delivered }
ERR_NOORIGIN = 409 ; { :No origin specified }
ERR_NORECIPIENT = 411 ; { :No recipient given (<command>) }
ERR_NOTEXTTOSEND = 412 ; { :No text to send }
ERR_NOTOPLEVEL = 413 ; { <mask> :No toplevel domain specified }
ERR_WILDTOPLEVEL = 414 ; { <mask> :Wildcard in toplevel domain }
ERR_UNKNOWNCOMMAND = 421 ; { <command> :Unknown command }
ERR_NOMOTD = 422 ; { :MOTD File is missing }
ERR_NOADMININFO = 423 ; { <server> :No administrative info available }
ERR_FILEERROR = 424 ; { :File error doing <file op> on <file> }
ERR_NONICKNAMEGIVEN = 431 ; { :No nickname given }
ERR_ERRONEUSNICKNAME = 432 ; { <nick> :Erroneus nickname }
ERR_NICKNAMEINUSE = 433 ; { <nick> :Nickname is already in use }
ERR_NICKCOLLISION = 436 ; { <nick> :Nickname collision KILL }
ERR_USERNOTINCHANNEL = 441 ; { <nick> <channel> :They aren't on that channel } {Do not Localize}
ERR_NOTONCHANNEL = 442 ; { <channel> :You're not on that channel } {Do not Localize}
ERR_USERONCHANNEL = 443 ; { <user> <channel> :is already on channel }
ERR_NOLOGIN = 444 ; { <user> :User not logged in }
ERR_SUMMONDISABLED = 445 ; { :SUMMON has been disabled }
ERR_USERSDISABLED = 446 ; { :USERS has been disabled }
ERR_NOTREGISTERED = 451 ; { :You have not registered }
ERR_NEEDMOREPARAMS = 461 ; { <command> :Not enough parameters }
ERR_ALREADYREGISTRED = 462 ; { :You may not reregister }
ERR_NOPERMFORHOST = 463 ; { :Your host isn't among the privileged } {Do not Localize}
ERR_PASSWDMISMATCH = 464 ; { :Password incorrect }
ERR_YOUREBANNEDCREEP = 465 ; { :You are banned from this server }
ERR_KEYSET = 467 ; { <channel> :Channel key already set }
ERR_CHANNELISFULL = 471 ; { <channel> :Cannot join channel (+l) }
ERR_UNKNOWNMODE = 472 ; { <char> :is unknown mode char to me }
ERR_INVITEONLYCHAN = 473 ; { <channel> :Cannot join channel (+i) }
ERR_BANNEDFROMCHAN = 474 ; { <channel> :Cannot join channel (+b) }
ERR_BADCHANNELKEY = 475 ; { <channel> :Cannot join channel (+k) }
ERR_NOPRIVILEGES = 481 ; { :Permission Denied- You're not an IRC operator } {Do not Localize}
ERR_CHANOPRIVSNEEDED = 482 ; { <channel> :You're not channel operator } {Do not Localize}
ERR_CANTKILLSERVER = 483 ; { :You cant kill a server! }
ERR_NOOPERHOST = 491 ; { :No O-lines for your host }
ERR_UMODEUNKNOWNFLAG = 501 ; { :Unknown MODE flag }
ERR_USERSDONTMATCH = 502 ; { :Cant change mode for other users }
type
{ TIdIRCUser }
TIdIRC = class;
//TODO: This needs to be a TCollecitonItem
TIdIRCUser = class(TCollectionItem)
protected
FClient: TIdIRC;
FNick: String;
FAddress: String;
FData: TObject;
FReason: String;
public
Count: Integer;
constructor Create(AClient: TIdIRC; ANick, AAddress: String); reintroduce;
destructor Destroy; override;
procedure Say(AMsg: String);
property Nick: String read FNick write FNick;
property Address: String read FAddress write FAddress;
property Data: TObject read FData write FData;
property Reason: String read FReason write FReason;
end;
{ TIdIRCUsers }
TIdIRCSortCompareUsers = procedure (Sender :TObject;
AItem1, AItem2 : TIdIRCUser; var AResult : Integer);
//TODO: This needs to be a TCollection
TIdIRCUsers = class(TCollection)
protected
FClient: TIdIRC;
FOnSortCompareUsers : TIdIRCSortCompareUsers;
procedure SetItem ( Index: Integer; const Value: TIdIRCUser );
function GetItem(Index: Integer): TIdIRCUser;
public
constructor Create(AClient: TIdIRC);
destructor Destroy; override;
function Add(ANick, AAddress: String): TIdIRCUser;
procedure Remove(AUser: TIdIRCUser);
function Address(ANick: String): String;
function Find(ANick: String; var AIndex: Integer): Boolean;
function Get(ANick: String): TIdIRCUser;
procedure Nick(AFromNick, AToNick: String);
procedure Sort;
property Items[Index: Integer] : TIdIRCUser read GetItem write SetItem;
property OnSortCompareUsers : TIdIRCSortCompareUsers
read FOnSortCompareUsers write FOnSortCompareUsers;
end;
{ TChannel }
TIdIRCChangeType = (ctNone, ctAdd, ctSubtract);
TIdIRCChannelMode = (cmPrivate, cmSecret, cmInviteOnly, cmOpsSetTopic,
cmNoExternalMessages, cmModerated, cmUserLimit, cmKey);
TIdIRCChannelModes = Set of TIdIRCChannelMode;
TIdIRCCloseType = (ctReset, ctPart, ctKick);
TIdIRCChannelUpdateType = (cuMode, cuTopic, cuUser, cuNames, cuNick, cuJoin,
cuPart, cuKick, cuQuit);
TIdIRCOnChannelUpdate = procedure (Sender: TObject; AUpdateType:
TIdIRCChannelUpdateType; AUser: TIdIRCUser; AInfo: Integer) of object;
//TODO: This needs to be a TCollectionItem
TIdIRCChannel = class(TCollectionItem)
protected
FClient: TIdIRC;
FName: String;
FTopic: String;
FMode: TIdIRCChannelModes;
FLimit: Integer;
FKey: String;
FNames: TStringList;
FBans: TStringList;
FActive: Boolean;
FData: TObject;
FModeChange: Boolean;
ModeOptions: String;
ModeParams: String;
ChangeType: TIdIRCChangeType;
FCloseType: TIdIRCCloseType;
FOnChannelUpdate: TIdIRCOnChannelUpdate;
procedure SetTopic(AValue: String);
procedure SetMode(AValue: TIdIRCChannelModes);
procedure SetLimit(AValue: Integer);
procedure SetKey(AValue: String);
function GetModeString: String;
public
constructor Create(AClient: TIdIRC; AName: String); reintroduce;
destructor Destroy; override;
procedure Say(AMsg: String);
procedure Part(AReason: String);
procedure Kick(ANick, AReason: String);
procedure BeginMode;
procedure EndMode;
procedure Op(ANick: String);
procedure Deop(ANick: String);
procedure Voice(ANick: String);
procedure Devoice(ANick: String);
procedure Ban(AHostmask: String);
procedure Unban(AHostmask: String);
procedure TopicChanged(ATopic: String);
procedure ModeChanged(AMode: TIdIRCChannelModes);
procedure LimitChanged(ALimit: Integer);
procedure KeyChanged(AKey: String);
function AddUser(ANick, AAddress: String): TIdIRCUser;
procedure RemoveUser(AUser: TIdIRCUser);
function HasUser(ANick: String): Boolean;
function Find(ANick: String; var AIndex: Integer): Boolean;
procedure GotOp(AUser: TIdIRCUser);
procedure GotDeop(AUser: TIdIRCUser);
procedure GotVoice(AUser: TIdIRCUser);
procedure GotDevoice(AUser: TIdIRCUser);
procedure ChangedNick(AUser: TIdIRCUser; ANewNick: String);
procedure Joined(AUser: TIdIRCUser);
procedure Parted(AUser: TIdIRCUser);
procedure Kicked(AUser: TIdIRCUser);
procedure Quit(AUser: TIdIRCUser);
property Name: String read FName;
property Topic: String read FTopic write SetTopic;
property Mode: TIdIRCChannelModes read FMode write SetMode;
property Limit: Integer read FLimit write SetLimit;
property Key: String read FKey write SetKey;
property ModeChange: Boolean read FModeChange;
property ModeString: String read GetModeString;
property Names: TStringList read FNames;
property Bans: TStringList read FBans;
property Active: Boolean read FActive write FActive;
property CloseType: TIdIRCCloseType read FCloseType write FCloseType;
property Data: TObject read FData write FData;
property OnChannelUpdate: TIdIRCOnChannelUpdate read FOnChannelUpdate write FOnChannelUpdate;
end;
{ TIdIRCChannels }
TIdIRCSortCompareChanels = procedure (Sender :TObject; AItem1, AItem2 : TIdIRCChannel; var AResult : Integer);
//TODO: This needs to be a TCollection
TIdIRCChannels = class(TCollection)
protected
FClient: TIdIRC;
FOnSortCompareChanels : TIdIRCSortCompareChanels;
function GetItem(Index:Integer): TIdIRCChannel;
procedure SetItem ( Index: Integer; const Value: TIdIRCChannel );
public
constructor Create(AClient: TIdIRC); reintroduce;
destructor Destroy; override;
function Add(AName: String): TIdIRCChannel;
procedure Remove(AName: String);
function Find(AName: String; var AIndex: Integer): Boolean;
function Get(AName: String): TIdIRCChannel;
procedure ChangedNick(AUser: TIdIRCUser; ANewNick: String);
procedure Quit(AUser: TIdIRCUser);
public
procedure Sort; virtual;
property Items[Index: Integer] : TIdIRCChannel read GetItem write SetItem;
end;
{ TIdIRCReplies }
TIdIRCReplies = class(TPersistent)
protected
FFinger: String;
FVersion: String;
FUserInfo: String;
FClientInfo: String;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property Finger: String read FFinger write FFinger;
property Version: String read FVersion write FVersion;
property UserInfo: String read FUserInfo write FUserInfo;
property ClientInfo: String read FClientInfo write FClientInfo;
end;
{ TIdIRCReadThread }
TIdIRCReadThread = class(TIdThread)
protected
FClient: TIdIRC;
FRecvData: string;
procedure Run; override;
public
constructor Create(AClient: TIdIRC); reintroduce;
end;
{ TIdIRC }
TIdIRCUserMode = (umInvisible, umOperator, umServerNotices, umWallops);
TIdIRCUserModes = Set of TIdIRCUserMode;
TIdIRCState = (csDisconnect, csDisconnected, csConnecting, csLoggingOn, csConnected);
TIdIRCUpdateType = (utTopic, utMode, utNicks);
TIdIRCOnMessage = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel; Content: String) of object;
TIdIRCOnJoin = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel) of object;
TIdIRCOnJoined = procedure (Sender: TObject; AChannel: TIdIRCChannel) of object;
TIdIRCOnPart = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel) of object;
TIdIRCOnParted = procedure (Sender: TObject; AChannel: TIdIRCChannel) of object;
TIdIRCOnKick = procedure (Sender: TObject; AUser, AVictim: TIdIRCUser; AChannel: TIdIRCChannel) of object;
TIdIRCOnKicked = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel) of object;
TIdIRCOnNickChange = procedure (Sender: TObject; AUser: TIdIRCUser; ANewNick: String) of object;
TIdIRCOnTopic = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel; const AChanName, ATopic : String) of object;
TIdIRCOnQuit = procedure (Sender: TObject; AUser: TIdIRCUser) of object;
TIdIRCOnNames = procedure (Sender: TObject; AUsers : TIdIRCUsers; AChannel: TIdIRCChannel) of object;
TIdIRCOnInvite = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: String) of object;
TIdIRCOnError = procedure (Sender: TObject; AUser: TIdIRCUser; ANumeric, AError: String) of object;
TIdIRCOnAway = procedure (Sender: TObject; AUser: TIdIRCUser) of object;
TIdIRCOnWallops = procedure (Sender: TObject; AUser: TIdIRCUser; AContent: String) of object;
TIdIRCOnSystem = procedure (Sender: TObject; AUser: TIdIRCUser; ACmdCode: Integer; ACommand, AContent: String) of object;
TIdIRCOnRaw = procedure (Sender: TObject; AUser: TIdIRCUser; ACommand, AContent: String;
var Suppress: Boolean) of object;
TIdIRCOnOp = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel; ATarget: TIdIRCUser) of object;
TIdIRCOnBan = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel; AHostmask: String) of object;
TIdIRCOnChannelMode = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel; AChanName: String; AModes: String) of object;
TIdIRCOnChannelModeChanged = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel) of object;
TIdIRCOnUserMode = procedure (Sender: TObject; AModes: String) of object;
TIdIRCOnInviting = procedure (Sender: TObject; ANick, AChannel: String) of object;
TIdIRCOnKill = procedure (Sender: TObject; User: TIdIRCUser; AVictim, AReason: String) of object;
TIdIRCOnUnknownCommand = procedure (Sender: TObject; AUser: TIdIRCUser; ACommand, AContent: String) of object;
TIdIRCOnCTCPQuery = procedure (Sender: TObject; User: TIdIRCUser; AChannel: TIdIRCChannel;
Command, Args: String; var ASuppress: Boolean) of object;
TIdIRCOnCTCPReply = procedure (Sender: TObject; AUser: TIdIRCUser; AChannel: TIdIRCChannel;
Command, Args: String) of object;
TIdIRCOnSend = procedure (Sender: TObject; ACommand: String) of object;
TIdIRCOnNicksInUse = procedure (Sender: TObject; var ANick: String) of object;
TIdIRCOnSocketError = procedure (Sender: TObject; ASocket, AMsg: String) of object;
TIdIRCOnNoTopic = procedure (Sender: TObject; AChannel: TIdIRCChannel; AContent: String) of object;
TIdIRCOnAwayChange = procedure (Sender: TObject; AContent: String) of object;
TIdIRCOnNickChanged = procedure (Sender: TObject; AOldNick: String) of object;
TIdIRCOnDCCChat = procedure(Sender: TObject; ANick, AIp, APort: String) of object;
TIdIRCOnDCCSend = procedure(Sender: TObject; ANick, AIp, APort, AFileName, AFileSize: String) of object;
TIdIRCOnDCCResume = procedure(Sender: TObject; ANick, APort, AFileName, APosition: String) of object;
TIdIRCOnDCCAccept = procedure(Sender: TObject; ANick, APort, AFileName, APosition: String) of object;
TIdIRCOnLinks = procedure(Sender: TObject; AMask, AServer, AHopCount, AServerInfo: String) of object;
TIdIRCOnList = procedure(Sender: TObject; AChans: TStringList; APosition: Integer; ALast: Boolean) of object;
// TIdIRCOnChannelMode = procedure (Sender: TObject; Nick, Address, Channel: String) of object;
TIdIRC = class(TIdTCPClient)
protected
{ Property fields }
FNick: String;
FAltNick: String;
FUsername: String;
FRealName: String;
FServer: String;
//FPort: Integer;
FPassword: String;
FUserMode: TIdIRCUserModes;
FAway: Boolean;
FNotify: TStringList;
FReplies: TIdIRCReplies;
FState: TIdIRCState;
FCurrentNick: String;
FData: TObject;
{ Event handlers }
FOnMessage: TIdIRCOnMessage;
FOnNotice: TIdIRCOnMessage;
FOnAction: TIdIRCOnMessage;
FOnConnect: TNotifyEvent;
FOnDisconnect: TNotifyEvent;
FOnJoin: TIdIRCOnJoin;
FOnJoined: TIdIRCOnJoined;
FOnPart: TIdIRCOnPart;
FOnParted: TIdIRCOnParted;
FOnKick: TIdIRCOnKick;
FOnKicked: TIdIRCOnKicked;
FOnNickChange: TIdIRCOnNickChange;
FOnNickChanged: TIdIRCOnNickChanged;
FOnTopic: TIdIRCOnTopic;
FOnQuit: TIdIRCOnQuit;
FOnNames: TIdIRCOnNames;
FOnInvite: TIdIRCOnInvite;
FOnPingPong: TNotifyEvent;
FOnError: TIdIRCOnError;
FOnAway: TIdIRCOnAway;
FOnNowAway: TIdIRCOnAwayChange;
FOnUnAway: TIdIRCOnAwayChange;
FOnWallops: TIdIRCOnWallops;
FOnSystem: TIdIRCOnSystem;
FOnRaw: TIdIRCOnRaw;
FOnOp: TIdIRCOnOp;
FOnDeop: TIdIRCOnOp;
FOnBan: TIdIRCOnBan;
FOnUnban: TIdIRCOnBan;
FOnVoice: TIdIRCOnOp;
FOnDevoice: TIdIRCOnOp;
FOnChannelMode: TIdIRCOnChannelMode;
FOnChannelModeChanged: TIdIRCOnChannelModeChanged;
FOnUserMode: TIdIRCOnUserMode;
FOnUserModeChanged: TNotifyEvent;
FOnInviting: TIdIRCOnInviting;
FOnKill: TIdIRCOnKill;
FOnUnknownCommand: TIdIRCOnUnknownCommand;
FOnCTCPQuery: TIdIRCOnCTCPQuery;
FOnCTCPReply: TIdIRCOnCTCPReply;
FOnStateChange: TNotifyEvent;
FOnSend: TIdIRCOnSend;
FOnReceive: TIdIRCOnSend;
FOnNicksInUse: TIdIRCOnNicksInUse;
FOnSocketError: TIdIRCOnSocketError;
FOnNoTopic: TIdIRCOnNoTopic;
FOnDCCChat: TIdIRCOnDCCChat;
FOnDCCSend: TIdIRCOnDCCSend;
FOnDCCResume: TIdIRCOnDCCResume;
FOnDCCAccept: TIdIRCOnDCCAccept;
FOnLinks: TIdIRCOnLinks;
FOnList: TIdIRCOnList;
// FOnChannelMode: TIdIRCOnChannelMode;
FOnChannelUpdate: TIdIRCOnChannelUpdate;
{ Other fields }
FList: TStringList;
FListLast: Integer;
Token: TStringList;
FullCommand: String;
SenderNick: String;
SenderAddress: String;
Command: String;
Content: String;
FChannels: TIdIRCChannels;
FUsers: TIdIRCUsers;
FUser: TIdIRCUser;
FIRCThread: TIdIRCReadThread;
{ Socket }
FBuffer: String;
{ Socket event handlers }
procedure SocketDataAvailable;
//procedure SocketSessionClosed(Sender: TObject);
//procedure SocketSessionConnected(Sender: TObject);
{ Property methods }
procedure SetNick(AValue: String);
function GetNick: String;
procedure SetAltNick(AValue: String);
procedure SeTIdIRCUsername(AValue: String);
procedure SetRealName(AValue: String);
procedure SetPassword(AValue: String);
procedure SeTIdIRCUserMode(AValue: TIdIRCUserModes);
procedure SeTIdIRCReplies(AValue: TIdIRCReplies);
//procedure SetServer(Value: String);
//procedure SetPort(Value: Integer);
//function GetConnected: Boolean;
//function GetLocalHost: String;
//function GetLocalIPAddr: String;
//procedure SetSocksServer(Value: String);
//procedure SetSocksPort(Value: String);
{ Other methods }
procedure SeTIdIRCState(AState: TIdIRCState);
procedure TokenizeCommand;
function MatchCommand: Integer;
procedure ParseCommand;
function MatchDCC(ADCC: String): Integer;
function MatchCTCP(ACTCP: String): Integer;
procedure ParseDCC(ADCC: String);
procedure ParseCTCPQuery;
procedure ParseCTCPReply;
function ParseChannelModeChange(AChannelToken: Integer): Boolean;
function ParseUserModeChange: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure Connect(const ATimeout: Integer = IdTimeoutDefault); override;
procedure Disconnect(AForce: Boolean); reintroduce; overload;
function IsChannel(AChannel: String): Boolean;
function IsOp(ANick: String): Boolean;
function IsVoice(ANick: String): Boolean;
function MatchHostmask(AAddress, AHostmask: PChar): Boolean;
procedure Raw(ALine: String);
procedure Say(ATarget, AMsg: String);
procedure Notice(ATarget, AMsg: String);
procedure Action(ATarget, AMsg: String);
procedure CTCPQuery(ATarget, ACommand, AParameters: String);
procedure CTCPReply(ATarget, ACTCP, AReply: String);
procedure Join(AChannels : String; const AKeys: String =''); {Do not Localize}
procedure Part(AChannels : String; const AReason: String = ''); {Do not Localize}
procedure Kick(AChannel, ANick, AReason: String);
procedure Quit(AReason: String);
procedure Mode(AChannel, AModes : String; const AParams: String = ''); {Do not Localize}
procedure GetTopic(AChannel: String);
procedure SetTopic(AChannel, ATopic: String);
procedure SetAwayMessage(AMsg: String);
procedure ClearAwayMessage;
function GetModeString: String;
{ Public properties }
//property Connected: Boolean read GetConnected;
property Away: Boolean read FAway;
property Notify: TStringList read FNotify write FNotify;
property State: TIdIRCState read FState;
property Channels: TIdIRCChannels read FChannels;
property Users: TIdIRCUsers read FUsers;
property IRCThread: TIdIRCReadThread read FIRCThread;
//property LocalHost: String read GetLocalHost;
//property LocalIPAddr: String read GetLocalIPAddr;
//property Data: TObject read FData write FData;
published
{ Published properties }
property Nick: String read GetNick write SetNick;
property AltNick: String read FAltNick write SetAltNick;
property Username: String read FUsername write SeTIdIRCUsername;
property RealName: String read FRealName write SetRealName;
//property Server: String read FServer write SetServer;
//property Port: Integer read FPort write SetPort;
property Port default IdPORT_IRC;
property Password: String read FPassword write SetPassword;
property Replies: TIdIRCReplies read FReplies write SeTIdIRCReplies;
property UserMode: TIdIRCUserModes read FUserMode write SeTIdIRCUserMode;
//property SocksServer: String read FSocksServer write SetSocksServer;
//property SocksPort: String read FSocksPort write SetSocksPort;
{ Published events }
property OnMessage: TIdIRCOnMessage read FOnMessage write FOnMessage;
property OnNotice: TIdIRCOnMessage read FOnNotice write FOnNotice;
property OnAction: TIdIRCOnMessage read FOnAction write FOnAction;
property OnConnect: TNotifyEvent read FOnConnect write FOnConnect;
property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect;
property OnJoin: TIdIRCOnJoin read FOnJoin write FOnJoin;
property OnJoined: TIdIRCOnJoined read FOnJoined write FOnJoined;
property OnPart: TIdIRCOnPart read FOnPart write FOnPart;
property OnParted: TIdIRCOnParted read FOnParted write FOnParted;
property OnKick: TIdIRCOnKick read FOnKick write FOnKick;
property OnKicked: TIdIRCOnKicked read FOnKicked write FOnKicked;
property OnNickChange: TIdIRCOnNickChange read FOnNickChange write FOnNickChange;
property OnNickChanged: TIdIRCOnNickChanged read FOnNickChanged write FOnNickChanged;
property OnTopic: TIdIRCOnTopic read FOnTopic write FOnTopic;
property OnQuit: TIdIRCOnQuit read FOnQuit write FOnQuit;
property OnNames: TIdIRCOnNames read FOnNames write FOnNames;
property OnInvite: TIdIRCOnInvite read FOnInvite write FOnInvite;
property OnPingPong: TNotifyEvent read FOnPingPong write FOnPingPong;
property OnError: TIdIRCOnError read FOnError write FOnError;
property OnAway: TIdIRCOnAway read FOnAway write FOnAway;
property OnNowAway: TIdIRCOnAwayChange read FOnNowAway write FOnNowAway;
property OnUnAway: TIdIRCOnAwayChange read FOnUnAway write FOnUnAway;
property OnWallops: TIdIRCOnWallops read FOnWallops write FOnWallops;
property OnSystem: TIdIRCOnSystem read FOnSystem write FOnSystem;
property OnRaw: TIdIRCOnRaw read FOnRaw write FOnRaw;
property OnOp: TIdIRCOnOp read FOnOp write FOnOp;
property OnDeop: TIdIRCOnOp read FOnDeop write FOnDeop;
property OnBan: TIdIRCOnBan read FOnBan write FOnBan;
property OnUnban: TIdIRCOnBan read FOnUnban write FOnUnban;
property OnVoice: TIdIRCOnOp read FOnVoice write FOnVoice;
property OnDevoice: TIdIRCOnOp read FOnDevoice write FOnDevoice;
property OnChannelMode: TIdIRCOnChannelMode read FOnChannelMode write FOnChannelMode;
property OnChannelModeChanged: TIdIRCOnChannelModeChanged read FOnChannelModeChanged write FOnChannelModeChanged;
property OnUserMode: TIdIRCOnUserMode read FOnUserMode write FOnUserMode;
property OnUserModeChanged: TNotifyEvent read FOnUserModeChanged write FOnUserModeChanged;
property OnInviting: TIdIRCOnInviting read FOnInviting write FOnInviting;
property OnKill: TIdIRCOnKill read FOnKill write FOnKill;
property OnUnknownCommand: TIdIRCOnUnknownCommand read FOnUnknownCommand write FOnUnknownCommand;
property OnCTCPQuery: TIdIRCOnCTCPQuery read FOnCTCPQuery write FOnCTCPQuery;
property OnCTCPReply: TIdIRCOnCTCPReply read FOnCTCPReply write FOnCTCPReply;
property OnStateChange: TNotifyEvent read FOnStateChange write FOnStateChange;
property OnSend: TIdIRCOnSend read FOnSend write FOnSend;
property OnReceive: TIdIRCOnSend read FOnReceive write FOnReceive;
property OnNicksInUse: TIdIRCOnNicksInUse read FOnNicksInUse write FOnNicksInUse;
property OnSocketError: TIdIRCOnSocketError read FOnSocketError write FOnSocketError;
property OnNoTopic: TIdIRCOnNoTopic read FOnNoTopic write FOnNoTopic;
property OnDCCChat: TIdIRCOnDCCChat read FOnDCCChat write FOnDCCChat;
property OnDCCSend: TIdIRCOnDCCSend read FOnDCCSend write FOnDCCSend;
property OnDCCResume: TIdIRCOnDCCResume read FOnDCCResume write FOnDCCResume;
property OnDCCAccept: TIdIRCOnDCCAccept read FOnDCCAccept write FOnDCCAccept;
property OnLinks: TIdIRCOnLinks read FOnLinks write FOnLinks;
property OnList: TIdIRCOnList read FOnList write FOnList;
// property OnChannelMode: TIdIRCOnChannelMode read FOnChannelMode write FOnChannelMode;
property OnChannelUpdate: TIdIRCOnChannelUpdate read FOnChannelUpdate write FOnChannelUpdate;
End;//TIdIRC
const
{ RFC1459 specifies 15 as the maximum token count in any one line. }
{ I changed this to 30, becuase 15 causes problems on servers that don't stick to RFC - MRE - 4/16/02}
IdIrcMinTokenCount: Byte = 30;
implementation
uses
IdResourceStrings,
SysUtils;
const
{ Responses from the server that do not appear as a numeric. }
Commands: Array [0..12] of String = ('PRIVMSG', 'NOTICE', 'JOIN', 'PART', 'KICK', 'MODE', {Do not Localize}
'NICK', 'QUIT', 'INVITE', 'KILL', 'PING', 'WALLOPS', 'TOPIC'); {Do not Localize}
{ Standard CTCP queries and replies. }
CTCPs: Array [0..9] of String = ('ACTION', 'SOUND', 'PING', 'FINGER', 'USERINFO', 'VERSION', {Do not Localize}
'CLIENTINFO', 'TIME', 'ERROR', 'DCC'); {Do not Localize}
{ Standard DCC queries and replies. }
DCCs: Array [0..3] of String = ('SEND', 'CHAT', 'RESUME', 'ACCEPT');
{ The characters for the channel modes. In the same order as TIdIRCChannelModes. }
ChannelModeChars: array [0..7] of Char = ('p', 's', 'i', 't', 'n', 'm', 'l', 'k'); {Do not Localize}
{ The characters for the user modes. In the same order as TIdIRCUserModes. }
UserModeChars: array [0..3] of Char = ('i', 'o', 's', 'w'); {Do not Localize}
{ Default CTCP Version and ClientInfo replies (just a bit of advertising if
the client coder forgets to specify any other values). }
IRCChannelPrefixes = ['&','#','+','!']; {do not translate} {Do not Localize}
{ Register the component TIdIRC in Delphi. }
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRCUser }
{ //////////////////////////////////////////////////////////////////////////// }
{ Create a new user in our list. }
constructor TIdIRCUser.Create(AClient: TIdIRC; ANick, AAddress: String);
begin
inherited Create( AClient.Users );
FClient := AClient;
FNick := ANick;
FAddress := AAddress;
FData := nil;
FReason := ''; {Do not Localize}
Count := 1;
end;
{ Delete the user from our list. }
destructor TIdIRCUser.Destroy;
begin
inherited Destroy;
end;
{ Send a private message to the user. }
procedure TIdIRCUser.Say(AMsg: String);
begin
FClient.Say(FNick, AMsg);
end;
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRCUsers }
{ //////////////////////////////////////////////////////////////////////////// }
{ Create the list of users. }
constructor TIdIRCUsers.Create(AClient: TIdIRC);
begin
inherited Create (TIdIRCUser);
FClient := AClient;
end;
{ Delete the list of users. }
destructor TIdIRCUsers.Destroy;
begin
inherited Destroy;
end;
procedure TIdIRCUsers.SetItem ( Index: Integer; const Value: TIdIRCUser );
begin
inherited SetItem (Index, Value);
end;
{inherited GetItem for our items property}
function TIdIRCUsers.GetItem(Index: Integer): TIdIRCUser;
begin
Result := TIdIRCUser( inherited GetItem(Index));
end;
{ Increments the reference count for the user. If the user does not exist,
then a new user is created with a reference count of one. If the user
already exists, the address is updated. Returns the user object. }
function TIdIRCUsers.Add(ANick, AAddress: String): TIdIRCUser;
var
Index: Integer;
begin
if Find(ANick, Index) then
{ The user already exists, so increment the reference count. }
begin
Result := Items[Index];
if (AAddress <> '') and (Result.Address <> AAddress) then {Do not Localize}
begin
Result.Address := AAddress;
end;
Inc(Result.Count);
end
else
{ Create a new user with a reference count of one. }
begin
Result := TIdIRCUser.Create(FClient, ANick, AAddress);
end;
end;
{ Decrement the reference count for this user. If the reference count becomes
zero, then delete the user object and remove the nick from the list (if the
nick in the list refers to the same user object). }
procedure TIdIRCUsers.Remove(AUser: TIdIRCUser);
var
Index: Integer;
begin
Dec(AUser.Count);
if AUser.Count = 0 then
begin
if Find(AUser.Nick, Index) and ((Items[Index] as TIdIRCUser) = AUser) then
begin
Items[Index].Free;
end;
end;
end;
{ Returns the address for the specified nick, if available. }
function TIdIRCUsers.Address(ANick: String): String;
var
Index: Integer;
begin
Result := ''; {Do not Localize}
if Find(ANick, Index) then
begin
Result := Items[Index].Address;
end;
end;
{ Searches for the given nick. Returns True and the index number of the nick
if found. }
function TIdIRCUsers.Find(ANick: String; var AIndex: Integer): Boolean;
begin
{ Need a case-insensitive search. So it has to be done manually, I guess. }
Result := False;
AIndex := 0;
while AIndex < Count do
begin
Result := AnsiCompareText(ANick, Items[AIndex].FNick) = 0;
if Result then
begin
Exit;
end;
Inc(AIndex);
end;
{ Search failed, so Index is set to -1. }
AIndex := -1;
end;
{ Returns the user object for the given nick. If the nick is not found, then
it returns nil. }
function TIdIRCUsers.Get(ANick: String): TIdIRCUser;
var
Index: Integer;
begin
Result := nil;
if Find(ANick, Index) then
begin
Result := Items[Index];
end;
end;
{sort user list}
procedure TIdIRCUsers.Sort;
{I found this procedure at:
http://groups.google.com/groups?q=Sort+TCollection&start=30&hl=en&safe=off&rnum=35&selm=904181166%40f761.n5030.z2.FidoNet.ftn
and it seems to look good.}
function DoCompare(AItem1, AItem2 : TIdIRCUser) : Integer;
begin
if Assigned(FOnSortCompareUsers) then
begin
FOnSortCompareUsers(Self,AItem1, AItem2, Result);
end
else
begin
Result := 0;
end;
end;
procedure SwapItems(i, j : Integer);
var
T : TIdIRCUser;
begin
T := Items[i];
Items[i] := Items[j];
Items[j] := T;
end;
procedure SortItems(iStart, iEnd : Integer);
var
i, j : Integer;
Med : TIdIRCUser;
begin
while iStart < iEnd do
begin
i := iStart;
j := iEnd;
if iStart = iEnd-1 then
begin
if DoCompare(Items[iStart], Items[iEnd]) > 0 then
begin
SwapItems(iStart, iEnd);
end;
Break;
end;
Med := Items[(i + j) div 2];
repeat
while DoCompare(Items[i], Med) < 0 do
begin
Inc(i);
end;
while DoCompare(Items[j], Med) > 0 do
begin
Dec(j);
end;
if i <= j then
begin
SwapItems(i, j);
Inc(i);
Dec(j);
end;
until i > j;
if j-iStart > iEnd-i then
begin
SortItems(i, iEnd);
iEnd := j;
end
else
begin
SortItems(iStart, j);
iStart := i;
end;
end;
end;
begin
if Count > 0 then
begin
SortItems(0, Count - 1);
end;
end;
{ Changes the user's nick. } {Do not Localize}
procedure TIdIRCUsers.Nick(AFromNick, AToNick: String);
var
Index: Integer;
User: TIdIRCUser;
begin
if Find(AFromNick, Index) then
begin
User := Items[Index];
User.Nick := AToNick;
{I'm leaving this all commented because I'm not sure if it is needed or not due
to some comments made by the author}
{ items[Index].Free;
if Find(AToNick, Index) then
{ The ToNick already exists (probably from the previous user having quit
IRC and a query window is still open), so replace the existing user
object with the new user object.}
{ FNickList.Objects[Index] := User
else
{ Add the user to the list with the new nick. }
{ begin
Index := FNickList.Add(AToNick);
FNickList.Objects[Index] := User;
end; }
end;
end;
{ Purge the users list. }
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRCChannel }
{ //////////////////////////////////////////////////////////////////////////// }
{ Create a new channel in the channel list. }
constructor TIdIRCChannel.Create(AClient: TIdIRC; AName: String);
begin
inherited Create(AClient.FChannels);
FClient := AClient;
FName := AName;
FTopic := ''; {Do not Localize}
FMode := [];
FLimit := 0;
FKey := ''; {Do not Localize}
FNames := TStringList.Create;
FBans := TStringList.Create;
FModeChange := False;
FActive := False;
FCloseType := ctReset;
FData := nil;
{ Attach the event handler for channel updates. }
FOnChannelUpdate := FClient.OnChannelUpdate;
end;
{ Delete a channel from the channel list. }
destructor TIdIRCChannel.Destroy;
begin
FNames.Free;
FBans.Free;
inherited Destroy;
end;
{ Set the topic of the channel. }
procedure TIdIRCChannel.SetTopic(AValue: String);
begin
FClient.SetTopic(FName, AValue);
end;
{ Compile a mode command to change the mode of the channel. }
procedure TIdIRCChannel.SetMode(AValue: TIdIRCChannelModes);
var
Element: TIdIRCChannelMode;
Difference: TIdIRCChannelModes;
TempOptions: String;
begin
TempOptions := ''; {Do not Localize}
{ If no difference in modes, then exit. }
if FMode = AValue then
begin
Exit;
end;
{ Calculate which modes have been removed. }
Difference := FMode - AValue;
if Difference <> [] then
begin
if ChangeType <> ctSubtract then
begin
TempOptions := TempOptions + '-'; {Do not Localize}
ChangeType := ctSubtract;
end;
for Element := cmPrivate to cmKey do
begin
if Element in Difference then
begin
TempOptions := TempOptions + ChannelModeChars[Ord(Element)];
end;
end;
end;
{ Calculate which modes have been added. }
Difference := AValue - FMode;
if Difference <> [] then
begin
if ChangeType <> ctAdd then
begin
TempOptions := TempOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Will not add Limit or Key modes. These must be added with the Limit and
Key properties. }
for Element := cmPrivate to cmKey do
begin
if (Element <> cmUserLimit) and (Element <> cmKey) then
begin
if Element in Difference then
begin
TempOptions := TempOptions + ChannelModeChars[Ord(Element)];
end;
end;
end;
end;
{ If compiling mode changes. }
if FModeChange then
begin
{ Add the mode change. }
ModeOptions := ModeOptions + TempOptions;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, TempOptions, ''); {Do not Localize}
end;
end;
procedure TIdIRCChannel.SetLimit(AValue: Integer);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctAdd then
begin
ModeOptions := ModeOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'l'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + Format('%s', [FLimit]); {Do not Localize}
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '+l', Format('%s', [FLimit])); {Do not Localize}
end;
end;
procedure TIdIRCChannel.SetKey(AValue: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctAdd then
begin
ModeOptions := ModeOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'k'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + FKey;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '+k', FKey); {Do not Localize}
end;
end;
{ Send a message to the channel. }
procedure TIdIRCChannel.Say(AMsg: String);
begin
FClient.Say(FName, AMsg);
end;
{ Part the channel. }
procedure TIdIRCChannel.Part(AReason: String);
begin
FClient.Part(FName, AReason);
end;
{ Kick a person from the channel. }
procedure TIdIRCChannel.Kick(ANick, AReason: String);
begin
FClient.Kick(FName, ANick, AReason);
end;
{ Begin compiling all subsequent mode changes into one mode command. }
procedure TIdIRCChannel.BeginMode;
begin
ModeOptions := ''; {Do not Localize}
ModeParams := ''; {Do not Localize}
ChangeType := ctNone;
FModeChange := True;
end;
{ Send all compiled mode changes as one mode command. }
procedure TIdIRCChannel.EndMode;
begin
{ If no mode changes have been compiled, then do not send the command. }
if ModeOptions <> '' then {Do not Localize}
begin
FClient.Mode(FName, ModeOptions, ModeParams);
end;
FModeChange := False;
end;
{ Give a user channel operator status. }
procedure TIdIRCChannel.Op(ANick: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctAdd then
begin
ModeOptions := ModeOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'o'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + ANick;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '+o', ANick); {Do not Localize}
end;
end;
{ Remove channel operator status from a user. }
procedure TIdIRCChannel.Deop(ANick: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctSubtract then
begin
ModeOptions := ModeOptions + '-'; {Do not Localize}
ChangeType := ctSubtract;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'o'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + ANick;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '-o', ANick); {Do not Localize}
end;
end;
{ Give a user a voice in a moderated channel. }
procedure TIdIRCChannel.Voice(ANick: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctAdd then
begin
ModeOptions := ModeOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'v'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + ANick;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '+v', ANick); {Do not Localize}
end;
end;
{ Remove the voice from a user in a moderated channel. }
procedure TIdIRCChannel.Devoice(ANick: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctSubtract then
begin
ModeOptions := ModeOptions + '-'; {Do not Localize}
ChangeType := ctSubtract;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'v'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + ANick;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '-v', ANick); {Do not Localize}
end;
end;
{ Ban a user from the channel. }
procedure TIdIRCChannel.Ban(AHostmask: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctAdd then
begin
ModeOptions := ModeOptions + '+'; {Do not Localize}
ChangeType := ctAdd;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'b'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + AHostmask;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '+b', AHostmask); {Do not Localize}
end;
end;
{ Remove the ban from the channel. }
procedure TIdIRCChannel.Unban(AHostmask: String);
begin
{ If compiling mode changes. }
if FModeChange then
begin
{ If the change type needs to be modified. }
if ChangeType <> ctSubtract then
begin
ModeOptions := ModeOptions + '-'; {Do not Localize}
ChangeType := ctSubtract;
end;
{ Add the mode change. }
ModeOptions := ModeOptions + 'b'; {Do not Localize}
{ If there are already some parameters, then add a space separator. }
if ModeParams <> '' then {Do not Localize}
begin
ModeParams := ModeParams + ' '; {Do not Localize}
end;
{ Add the parameter. }
ModeParams := ModeParams + AHostmask;
end
{ Send the mode change immediately. }
else
begin
FClient.Mode(FName, '-b', AHostmask); {Do not Localize}
end;
end;
{ Call to change the topic without sending a topic command. }
procedure TIdIRCChannel.TopicChanged(ATopic: String);
begin
if FTopic <> ATopic then
begin
FTopic := ATopic;
end;
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuTopic, nil, 0);
end;
end;
{ Call to change the channel mode without sending a mode command. }
procedure TIdIRCChannel.ModeChanged(AMode: TIdIRCChannelModes);
begin
if FMode <> AMode then
begin
FMode := AMode;
end;
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuMode, nil, 0);
end;
end;
{ Call to change the channel limit without sending a mode command. }
procedure TIdIRCChannel.LimitChanged(ALimit: Integer);
begin
if FLimit <> ALimit then
begin
FLimit := ALimit;
end;
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuMode, nil, 0);
end;
end;
{ Call to change the channel key without sending a mode command. }
procedure TIdIRCChannel.KeyChanged(AKey: String);
begin
if FKey <> AKey then
begin
FKey := AKey;
end;
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuMode, nil, 0);
end;
end;
{ Return a string representation of the channel mode. }
function TIdIRCChannel.GetModeString: String;
var
Element: TIdIRCChannelMode;
begin
{ Only bother if there are actually modes to show. }
if FMode <> [] then
begin
Result := '+'; {Do not Localize}
{ Add all mode characters. }
for Element := cmPrivate to cmKey do
begin
if Element in FMode then
begin
Result := Result + ChannelModeChars[Ord(Element)];
end;
end;
{ Add limit if present. }
if cmUserLimit in FMode then
begin
Result := Format('%s %d', [Result, FLimit]); {Do not Localize}
end;
{ Add key if present. }
if cmKey in FMode then
begin
Result := Format('%s %s', [Result, FKey]); {Do not Localize}
end
end
else
begin
Result := ''; {Do not Localize}
end;
end;
{ Add a new user to the channel. }
function TIdIRCChannel.AddUser(ANick, AAddress: String): TIdIRCUser;
var
IsOp, HasVoice: Boolean;
Attributes, Index: Integer;
begin
{ Op and Voice status are declared by @ and + symbols. If a person has voice
only, then the + is placed before the nick. If the person has ops, then the
@ symbol is placed before the nick. If the person has ops and voice (rather
pointless, but can happen) then the @ goes in front and the + goes at the
end. }
IsOp := (Length(ANick)>0) and (ANick[1] = '@'); {Do not Localize}
Attributes := 0;
if IsOp then
begin
Attributes := Attributes + 1;
ANick := Copy(ANick, 2, Length(ANick) - 1);
HasVoice := (Length(ANick)>0) and (ANick[Length(ANick)] = '+'); {Do not Localize}
if HasVoice then
begin
Attributes := Attributes + 2;
ANick := Copy(ANick, 1, Length(ANick) - 1);
end;
end
else
begin
HasVoice := (Length(ANick)>0) and (ANick[1] = '+'); {Do not Localize}
if HasVoice then
begin
Attributes := Attributes + 2;
ANick := Copy(ANick, 2, Length(ANick) - 1);
end;
end;
Result := nil;
{ If the nick already exists, don't add. } {Do not Localize}
if not Find(ANick, Index) then
begin
{ Add this user to the list. }
Result := FClient.Users.Add(ANick, AAddress);
FNames.AddObject(ANick, Pointer(Attributes));
end;
end;
{ Remove a user from the channel. }
procedure TIdIRCChannel.RemoveUser(AUser: TIdIRCUser);
var
Index: Integer;
begin
if Find(AUser.Nick, Index) then
begin
FNames.Delete(Index);
{ Release the user object. }
FClient.Users.Remove(AUser);
end;
end;
{ Returns True if the user is in the channel. }
function TIdIRCChannel.HasUser(ANick: String): Boolean;
var
Index: Integer;
begin
Result := Find(ANick, Index);
end;
{ Search for a nick in the channel. }
function TIdIRCChannel.Find(ANick: String; var AIndex: Integer): Boolean;
begin
{ Need a case-insensitive search. So it has to be done manually, I guess. }
Result := False;
AIndex := 0;
while AIndex < FNames.Count do
begin
Result := AnsiCompareText(ANick, FNames[AIndex]) = 0;
if Result then
begin
Exit;
end;
Inc(AIndex);
end;
{ Search failed, so Index is set to -1. }
AIndex := -1;
end;
{ User got op status. }
procedure TIdIRCChannel.GotOp(AUser: TIdIRCUser);
var
Index, Attr: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Add the op flag. }
Attr := Integer(FNames.Objects[Index]) or 1;
FNames.Objects[Index] := Pointer(Attr);
{ Tell the world we changed this user's status. } {Do not Localize}
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuUser, AUser, Attr);
end;
end;
end;
{ User lost op status. }
procedure TIdIRCChannel.GotDeop(AUser: TIdIRCUser);
var
Index, Attr: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check Aif the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Remove the op flag. }
Attr := Integer(FNames.Objects[Index]) and (not 1);
FNames.Objects[Index] := Pointer(Attr);
{ Tell the world we changed this user's status. } {Do not Localize}
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuUser, AUser, Attr);
end;
end;
end;
{ User got voice status. }
procedure TIdIRCChannel.GotVoice(AUser: TIdIRCUser);
var
Index, Attr: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Add the voice flag. }
Attr := Integer(FNames.Objects[Index]) or 2;
FNames.Objects[Index] := Pointer(Attr);
{ Tell the world we changed this user's status. } {Do not Localize}
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuUser, AUser, Attr);
end;
end;
end;
{ User lost voice status. }
procedure TIdIRCChannel.GotDevoice(AUser: TIdIRCUser);
var
Index, Attr: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Remove the voice flag. }
Attr := Integer(FNames.Objects[Index]) and (not 2);
FNames.Objects[Index] := Pointer(Attr);
{ Tell the world we changed this user's status. } {Do not Localize}
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuUser, AUser, Attr);
end;
end;
end;
{ User changed nick. }
procedure TIdIRCChannel.ChangedNick(AUser: TIdIRCUser; ANewNick: String);
var
Index: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
FNames[Index] := ANewNick;
{ Tell the world this user changed nick. }
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuNick, AUser, Index);
end;
end;
end;
{ User joined. }
procedure TIdIRCChannel.Joined(AUser: TIdIRCUser);
var
Index: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
Exit;
end;
{ Add to the names list. }
Index := FNames.AddObject(AUser.Nick, Pointer(0));
{ Tell the world this user joined. }
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuJoin, AUser, Index);
end;
end;
{ User parted. }
procedure TIdIRCChannel.Parted(AUser: TIdIRCUser);
var
Index: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Tell the world this user quit. }
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuPart, AUser, Index);
end;
{ Remove from the names list. }
FNames.Delete(Index);
end;
end;
{ User was kicked. }
procedure TIdIRCChannel.Kicked(AUser: TIdIRCUser);
var
Index: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Tell the world this user was kicked. }
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuKick, AUser, Index);
end;
{ Remove from the names list. }
FNames.Delete(Index);
end;
end;
{ User quit. }
procedure TIdIRCChannel.Quit(AUser: TIdIRCUser);
var
Index: Integer;
begin
{ No user object, so fail. }
if AUser = nil then
begin
Exit;
end;
{ Check if the user is in this channel. }
if Find(AUser.Nick, Index) then
begin
{ Tell the world this user quit. }
if Assigned(FOnChannelUpdate) then
begin
FOnChannelUpdate(Self, cuQuit, AUser, Index);
end;
{ Remove from the names list. }
FNames.Delete(Index);
end;
end;
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRCChannels }
{ //////////////////////////////////////////////////////////////////////////// }
{ Create the list of channels. }
constructor TIdIRCChannels.Create(AClient: TIdIRC);
begin
inherited Create(TIdIRCChannel);
FClient := AClient;
end;
{ Delete the list of channels. }
destructor TIdIRCChannels.Destroy;
begin
inherited Destroy;
end;
{ Add a new channel. If channel of this name exists, delete the previous
channel object and create a new object. Returns the channel object. }
function TIdIRCChannels.Add(AName: String): TIdIRCChannel;
var
Index: Integer;
begin
{ Object of this name already exists, so delete it. }
if Find(AName, Index) then
begin
Items[Index].Free;
end;
{ Create new channel object and add it. }
Result := TIdIRCChannel.Create(FClient, AName);
end;
{ Remove a channel. }
procedure TIdIRCChannels.Remove(AName: String);
var
Index: Integer;
begin
if Find(AName, Index) then
begin
Items[Index].Free;
end;
end;
{ Search for a specific channel name, and return the index if found. }
function TIdIRCChannels.Find(AName: String; var AIndex: Integer): Boolean;
begin
{ Need a case-insensitive search. So it has to be done manually, I guess. }
Result := False;
AIndex := 0;
while AIndex < Count do
begin
Result := AnsiCompareText(AName, Items[AIndex].Name) = 0;
if Result then
begin
Exit;
end;
Inc(AIndex);
end;
{ Search failed, so Index is set to -1. }
AIndex := -1;
end;
{ Return the channel object for the name given. If the channel name is not
found, then it returns nil. }
function TIdIRCChannels.Get(AName: String): TIdIRCChannel;
var
Index: Integer;
begin
Result := nil;
if Find(AName, Index) then
begin
Result := GetItem(Index);
end;
end;
{inherited SetItem for our items property}
procedure TIdIRCChannels.SetItem ( Index: Integer; const Value: TIdIRCChannel );
begin
inherited SetItem (Index, Value);
end;
{inherited GetItem for our items property}
function TIdIRCChannels.GetItem(Index: Integer): TIdIRCChannel;
begin
Result := TIdIRCChannel( inherited GetItem(Index));
end;
{ A user changed nick, so go through all channels and notify of the change. }
procedure TIdIRCChannels.ChangedNick(AUser: TIdIRCUser; ANewNick: String);
var
Index: Integer;
begin
for Index := 0 to Count - 1 do
begin
GetItem(Index).ChangedNick(AUser, ANewNick);
end;
end;
{ A user quit, so go through all channels and notify of the quit. }
procedure TIdIRCChannels.Quit(AUser: TIdIRCUser);
var
Index: Integer;
begin
for Index := 0 to Count - 1 do
begin
GetItem(Index).Quit(AUser);
end;
end;
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRCReplies }
{ //////////////////////////////////////////////////////////////////////////// }
constructor TIdIRCReplies.Create;
begin
inherited Create;
FFinger := ''; {Do not Localize}
FVersion := ''; {Do not Localize}
FUserInfo := ''; {Do not Localize}
FClientInfo := ''; {Do not Localize}
end;
procedure TIdIRCReplies.Assign(Source: TPersistent);
begin
if Source is TIdIRCReplies then
begin
FFinger := TIdIRCReplies(Source).Finger;
FVersion := TIdIRCReplies(Source).Version;
FUserInfo := TIdIRCReplies(Source).UserInfo;
FClientInfo := TIdIRCReplies(Source).ClientInfo;
end;
end;
{ //////////////////////////////////////////////////////////////////////////// }
{ TIdIRC }
{ //////////////////////////////////////////////////////////////////////////// }
constructor TIdIRC.Create(AOwner: TComponent);
var
Index: Integer;
begin
inherited Create(AOwner);
FList := TStringList.Create;
FNotify := TStringList.Create;
FReplies := TIdIRCReplies.Create;
with FReplies do
begin
Finger := ''; {Do not Localize}
Version := RSIRCClientVersion;
UserInfo := ''; {Do not Localize}
ClientInfo := Format(RSIRCClientInfo,[RSIRCClientVersion]);
end;
FNick := RSIRCNick; {Do not Localize}
FAltNick := RSIRCAltNick; {Do not Localize}
FUserName := RSIRCUserName; {Do not Localize}
FRealName := RSIRCRealName; {Do not Localize}
FServer := ''; {Do not Localize}
Port := IdPORT_IRC;
FUserMode := [];
FState := csDisconnected;
FCurrentNick := ''; {Do not Localize}
FData := nil;
{ The following objects only needed during run-time. }
if not (csDesigning in ComponentState) then
begin
Token := TStringList.Create;
FChannels := TIdIRCChannels.Create(Self);
FUsers := TIdIRCUsers.Create(Self);
{ Create a list of up to MinTokenCount tokens with a null string. }
for Index := 0 to IdIrcMinTokenCount - 1 do
begin
Token.Add(''); {Do not Localize}
end;
end;
end;
destructor TIdIRC.Destroy;
begin
{ Free all allocated objects. }
if not (csDesigning in ComponentState) then
begin
{ If still connected, the leave gracefully. }
if Connected then
begin
Disconnect(True);
end;
Token.Free;
FChannels.Free;
FUsers.Free;
end;
FList.Free;
FNotify.Free;
FReplies.Free;
inherited Destroy;
end;
procedure TIdIRC.Loaded;
begin
inherited Loaded;
end;
{ Data has arrived at the socket. }
procedure TIdIRC.SocketDataAvailable;
begin
{ Get all the data that we received and add it to the end of the current
buffer. }
if fState = csDisconnected then
begin
exit;
end;
FBuffer := IRCThread.FRecvData;
FullCommand := FBuffer;
if Length(FBuffer) > 0 then begin
{ Pass to the raw receive event handler. }
if Assigned(FOnReceive) then begin
FOnReceive(Self, FBuffer);
end;
{ Process the received command. }
ParseCommand;
end;
end;
{ Connect to the IRC server. }
procedure TIdIRC.Connect;
var LOurAddr : String;
LServerAddr : String;
begin
{ If already connected or in the process of connecting, the force a
disconnect. }
if Connected then
begin
Disconnect(TRUE);
end;
{ Clear the channel and user lists. }
FChannels.Clear;
FUsers.Clear;
{ Get a user object for ourselves. }
FUser := FUsers.Add(FNick, ''); {Do not Localize}
{ Set the current nick. }
FCurrentNick := FNick;
{ Set the current state. }
SeTIdIRCState(csConnecting);
{ Set the properties of the socket and start the connection process. }
inherited Connect;
SeTIdIRCState(csLoggingOn);
try
if Assigned(FOnConnect) then begin
OnConnect(SELF);
end;
if Connected then begin
FIRCThread := TIdIRCReadThread.Create(SELF);
end;
//we let the user override the IP address if they need to use the BoundIP
//property (that may be needed for some multihorned computers on more than
//one network.
if (Length(BoundIP)>0) then
begin
LOurAddr := BoundIP;
end
else
begin
LOurAddr := GStack.LocalAddress;
end;
//we want to let the user override the Server parameter with their own if they
//want. Otherwise, just use our local address.
if (Length(FServer)>0) then
begin
LServerAddr := FServer;
end
else
begin
LServerAddr := LOurAddr;
end;
{ If there is a password supplied, then send it first. }
if FPassword <> '' then {Do not Localize}
begin
Raw(Format('PASS %s', [FPassword])); {Do not Localize}
end;
{ Send the nick and user information. }
Raw(Format('NICK %s', [FNick])); {Do not Localize}
Raw(Format('USER %s %s %s :%s', [FUsername, LOurAddr, LServerAddr, FRealName])); {Do not Localize}
// SeTIdIRCState(csConnected);
except
on E: EIdSocketError do
raise EComponentError.Create(RSIRCCanNotConnect);
end;
end;
{ Force a disconnect from the IRC server. }
procedure TIdIRC.Disconnect(AForce: Boolean);
begin
{ Close the connection. }
if (FState <> csConnected) and (AForce<>TRUE) then
begin
exit;
end;
{ Release our user object. }
FUsers.Remove(FUser);
SeTIdIRCState(csDisconnect);
if Assigned(FOnDisconnect) then
begin
FOnDisconnect(self);
end;
if Assigned(IRCThread) then begin
// TODO: FreeOnTerminate:=FALSE; .Terminate; FreeAndNIL()
IRCThread.Terminate;
end;
inherited Disconnect;
SeTIdIRCState(csDisconnected);
if Assigned(FOnDisconnected) then
begin
FOnDisconnected(Self);
end;
end;
{ Send a command to the server. }
procedure TIdIRC.Raw(ALine: String);
begin
{ Send the string directly to the server without processing. Line is
terminated by CR-LF pair. }
if Connected then
begin
WriteLn(Aline+#13#10);
if Assigned(FOnSend) then
begin
FOnSend(Self, ALine);
end;
end
else
begin
if Assigned(FOnError) then
begin
FOnError(Self, nil, '', RSIRCNotConnected); {Do not Localize}
end;
end;
end;
{ Send a message to the specified target (channel or user). }
procedure TIdIRC.Say(ATarget, AMsg: String);
begin
Raw(Format('PRIVMSG %s :%s', [ATarget, AMsg])); {Do not Localize}
end;
{ Send a notice to the specified target (channel or user). }
procedure TIdIRC.Notice(ATarget, AMsg: String);
begin
Raw(Format('NOTICE %s :%s', [ATarget, AMsg])); {Do not Localize}
end;
{ Send an action (just a wrapper for a CTCP query). }
procedure TIdIRC.Action(ATarget, AMsg: String);
begin
CTCPQuery(ATarget, 'ACTION', AMsg); {Do not Localize}
end;
{ Send a CTCP request to the specifed target (channel or user). }
procedure TIdIRC.CTCPQuery(ATarget, ACommand, AParameters: String);
begin
Say(ATarget, Format(#1'%s %s'#1, [Uppercase(ACommand), AParameters])); {Do not Localize}
end;
{ Send a CTCP reply to the specified target (primarily a user, but could be a
channel). }
procedure TIdIRC.CTCPReply(ATarget, ACTCP, AReply: String);
begin
Notice(ATarget, Format(#1'%s %s'#1, [ACTCP, AReply])); {Do not Localize}
end;
{ Join the channels, using the keys supplied. Channels and Keys are comma-
separated lists of channel names and keys for those channels that require
a key. }
procedure TIdIRC.Join(AChannels : String; const AKeys: String = ''); {Do not Localize}
begin
if Length(AKeys) <> 0 then
begin
Raw(Format('JOIN %s %s', [AChannels, AKeys])) {Do not Localize}
end
else
begin
Raw(Format('JOIN %s', [AChannels])); {Do not Localize}
end;
end;
{ Part the channels, using the given reason (if the server supports part
messages). Channels is a comma-separated list of channel names to part. }
procedure TIdIRC.Part(AChannels : String; const AReason: String = ''); {Do not Localize}
begin
if Length(AReason) <> 0 then
begin
Raw(Format('PART %s :%s', [AChannels, AReason])) {Do not Localize}
end
else
begin
Raw(Format('PART %s', [AChannels])); {Do not Localize}
end;
end;
{ Kick a person from a channel. }
procedure TIdIRC.Kick(AChannel, ANick, AReason: String);
begin
Raw(Format('KICK %s %s :%s', [AChannel, ANick, AReason])); {Do not Localize}
end;
{ Quit IRC. }
procedure TIdIRC.Quit(AReason: String);
begin
Raw(Format('QUIT :%s', [AReason])); {Do not Localize}
end;
{ Set the mode of a channel. }
procedure TIdIRC.Mode(AChannel, AModes : String; const AParams: String = ''); {Do not Localize}
begin
if AParams = '' then {Do not Localize}
begin
Raw(Format('MODE %s %s', [AChannel, AModes])) {Do not Localize}
end
else
begin
Raw(Format('MODE %s %s %s', [AChannel, AModes, AParams])); {Do not Localize}
end;
end;
{ Return True if connected, or in the process of connecting. }
{
function TIdIRC.GetConnected: Boolean;
begin
Result := FState <> csDisconnected;
end;
}
{ Send the TOPIC command to retrieve the current topic and nick of the person
who set the topic for the specified channel. }
procedure TIdIRC.GetTopic(AChannel: String);
begin
Raw(Format('TOPIC %s', [AChannel])); {Do not Localize}
end;
{ Set the topic of the specified channel to the string Topic. }
procedure TIdIRC.SetTopic(AChannel, ATopic: String);
begin
Raw(Format('TOPIC %s :%s', [AChannel, ATopic])); {Do not Localize}
end;
{ Set an away message. }
procedure TIdIRC.SetAwayMessage(AMsg: String);
begin
Raw(Format('AWAY %s', [AMsg])); {Do not Localize}
end;
{ Clear the away message. }
procedure TIdIRC.ClearAwayMessage;
begin
Raw('AWAY'); {Do not Localize}
end;
{ Return the Nick property. }
function TIdIRC.GetNick: String;
begin
if Connected then
begin
Result := FCurrentNick
end
else
begin
Result := FNick;
end;
end;
{ Return the local host name. }
{
function TIdIRC.GetLocalHost: String;
begin
Result := LocalHost;
end;
}
{ Return the local IP address. }
{
function TIdIRC.GetLocalIPAddr: String;
begin
Result := FSocket.BoundIP;
end;
}
{ Change the user's nick. } {Do not Localize}
procedure TIdIRC.SetNick(AValue: String);
begin
{ Only allow direct change if not connected... }
if not Connected then
begin
if FNick <> AValue then
begin
FNick := AValue;
end;
end
else
begin
{ else send a NICK command and only change the nick if the command is
successful }
Raw(Format('NICK %s', [AValue])); {Do not Localize}
end;
end;
{ Change the user's alternative nick. } {Do not Localize}
procedure TIdIRC.SetAltNick(AValue: String);
begin
if FAltNick <> AValue then
begin
FAltNick := AValue;
end;
end;
{ Change the user's username. } {Do not Localize}
procedure TIdIRC.SeTIdIRCUsername(AValue: String);
begin
if FUsername <> AValue then
begin
FUsername := AValue;
end;
end;
{ Change the user's real name. } {Do not Localize}
procedure TIdIRC.SetRealName(AValue: String);
begin
if FRealName <> AValue then
begin
FRealName := AValue;
end;
end;
{ Change the password for the server . }
procedure TIdIRC.SetPassword(AValue: String);
begin
if FPassword <> AValue then
begin
FPassword := AValue;
end;
end;
{ Change the user's mode. } {Do not Localize}
procedure TIdIRC.SeTIdIRCUserMode(AValue: TIdIRCUserModes);
begin
{ Only allow direct change if not connected... }
if not Connected then
begin
if FUserMode <> AValue then
begin
FUserMode := AValue;
end;
end
else
{ else send a mode change command and only change the user mode if the
command is successful }
begin
{ Only modify the values that have actually changed }
{ FIXME: Needs to be completed. }
end;
end;
{ Set the CTCP replies. }
procedure TIdIRC.SeTIdIRCReplies(AValue: TIdIRCReplies);
begin
{ Copy the given TIdIRCReplies object to the internal object. }
FReplies.Assign(AValue);
end;
{ Change the current state. }
procedure TIdIRC.SeTIdIRCState(AState: TIdIRCState);
begin
if AState <> FState then
begin
FState := AState;
if Assigned(FOnStateChange) then
begin
FOnStateChange(Self);
end;
end;
end;
{ Split into SenderNick, SenderAddress, Command, Content and separate Tokens. }
procedure TIdIRC.TokenizeCommand;
var
Index: Integer;
Count: Integer;
begin
{ Set the values to null strings. }
SenderNick := ''; {Do not Localize}
SenderAddress := ''; {Do not Localize}
Command := ''; {Do not Localize}
Content := ''; {Do not Localize}
{ Extract the sender of the message first if it is present. }
if (Length(FullCommand)>0) and (FullCommand[1] = ':') then {Do not Localize}
begin
Index := Pos(' ', FullCommand); {Do not Localize}
SenderAddress := Copy(FullCommand, 2, Index - 2);
FullCommand := Copy(FullCommand, Index + 1, 512);
{ Copy the full address to the first token. }
Token[0] := SenderAddress;
{ See if the address contains a nick as well. }
Index := Pos('!', SenderAddress); {Do not Localize}
if Index > 0 then
begin
{ Extract the nick from the address. }
SenderNick := Copy(SenderAddress, 1, Index - 1);
SenderAddress := Copy(SenderAddress, Index + 1, 512);
end;
end
else
begin
{ Make the first token a null string. }
Token[0] := ''; {Do not Localize}
end;
{ Extract the command. }
Index := Pos(' ', FullCommand); {Do not Localize}
Command := Copy(FullCommand, 1, Index - 1);
FullCommand := Copy(FullCommand, Index + 1, 512);
{ Copy the Command to the second token. }
Token[1] := Command;
{ Extract the rest of the arguments into Content and Token. }
Content := FullCommand;
Count := 2;
while Length(FullCommand) > 0 do
begin
{ If the argument is prefixed by a semi-colon, then the rest of the line is
treated as one argument. }
if (Length(FullCommand)>0) and (FullCommand[1] = ':') then {Do not Localize}
begin
Token[Count] := Copy(FullCommand, 2, Length(FullCommand) - 1);
FullCommand := ''; {Do not Localize}
end
else
begin
Index := Pos(' ', FullCommand); {Do not Localize}
if Index > 0 then
begin
{ Copy the argument and remove it from the string. }
Token[Count] := Copy(FullCommand, 1, Index - 1);
{ Remove that token and process the remaining string. }
FullCommand := Copy(FullCommand, Index + 1, 512);
end
else
begin
{ Must be the last argument, so copy the entire remaining string. }
Token[Count] := Copy(FullCommand, 1, 512);
FullCommand := ''; {Do not Localize}
end;
end;
Inc(Count);
end;
{ Fill any empty tokens with a null string. }
for Index := Count to IdIrcMinTokenCount - 1 do
begin
Token[Index] := ''; {Do not Localize}
end;
end;
{ Attempt to match the given command with one of a list of commands. If a
match is found, then the index of that command is returned, else the return
value is -1. }
function TIdIRC.MatchCommand: Integer;
var
Index: Integer;
begin
Index := 0;
Result := -1;
while (Result < 0) and (Index <= High(Commands)) do
begin
if Command = Commands[Index] then
begin
Result := Index;
end;
Inc(Index);
end;
end;
{ Parse the string and call any appropriate event handlers. }
procedure TIdIRC.ParseCommand;
var
CommandNumber: Integer;
Suppress: Boolean;
Index: Integer;
Channel: TIdIRCChannel;
User, Target: TIdIRCUser;
lcTemp : String;
begin
{ Break up the command into its tokens. }
TokenizeCommand;
{ Get a reference to a user object for the sender. }
User := FUsers.Add(SenderNick, SenderAddress);
{ If an OnRaw event handler is assigned, then call it. }
if Assigned(FOnRaw) then
begin
Suppress := False;
FOnRaw(Self, User, Command, Content, Suppress);
{ If the user set Suppress to True, then stop processing for this string. }
if Suppress then
begin
{ Fixed 28/11/99. If Suppress was set to True, the User object would not
have been released. }
FUsers.Remove(User);
Exit;
end;
end;
{ Try to match a numeric command. If not a valid numeric command, then
returns -1. }
CommandNumber := StrToIntDef(Command, -1);
if CommandNumber > -1 then
begin
case CommandNumber of
1, { 001 }
2, { 002 }
3, { 003 }
4: { 004 }
begin
{ Apparently these are the first messages sent back from
the server, so set the Server to the address of the
sender of these messages. This is the actual address
of the server we are on. }
FServer := SenderAddress;
{ Set state to connected. May need this elsewhere too. }
SeTIdIRCState(csConnected);
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WELCOME', Content); {Do not Localize}
end;
end;
6, {NOT NAMED IN RFC2812 - /MAP LINE}
7: {NOT NAMED IN RFC2812 - END of /MAP}
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'MAP', Format('%s', [Token[3]]));
end;
RPL_TRACELINK, { 200 }
RPL_TRACECONNECTING, { 201 }
RPL_TRACEHANDSHAKE, { 202 }
RPL_TRACEUNKNOWN, { 203 }
RPL_TRACEOPERATOR, { 204 }
RPL_TRACEUSER, { 205 }
RPL_TRACESERVER, { 206 }
RPL_TRACENEWTYPE: { 208 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'TRACE', Content); {Do not Localize}
end;
RPL_STATSLINKINFO, { 211 }
RPL_STATSCOMMANDS, { 212 }
RPL_STATSCLINE, { 213 }
RPL_STATSNLINE, { 214 }
RPL_STATSILINE, { 215 }
RPL_STATSKLINE, { 216 }
RPL_STATSYLINE: { 218 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'STATS', Content); {Do not Localize}
end;
RPL_ENDOFSTATS: { 219 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'STATS', Format('%s %s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_UMODEIS: { 221 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'UMODE', Format('%s %s', [Token[2], Token[3]])); {Do not Localize}
end;
RPL_STATSLLINE, { 241 }
RPL_STATSUPTIME, { 242 }
RPL_STATSOLINE, { 243 }
RPL_STATSHLINE: { 244 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'STATS', Content); {Do not Localize}
end;
250, {NOT NAMED IN RFC2812 - Highest Connection Count}
RPL_LUSERCLIENT, { 251 }
RPL_LUSEROP, { 252 }
RPL_LUSERUNKNOWN, { 253 }
RPL_LUSERCHANNELS, { 254 }
RPL_LUSERME: { 255 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'LUSER', Format('%s %s',[Token[3], Token[4]])); {Do not Localize}
end;
RPL_ADMINME, { 256 }
RPL_ADMINLOC1, { 257 }
RPL_ADMINLOC2, { 258 }
RPL_ADMINEMAIL: { 259 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'ADMIN', Content); {Do not Localize}
end;
RPL_TRACELOG: { 261 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'TRACE', Content); {Do not Localize}
end;
265, {NOT NAMED IN RFC2812 - Current Local Users}
266: {NOT NAMED IN RFC2812 - Current Global Users}
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'LUSER', Token[3]); {Do not Localize}
end;
RPL_AWAY: { 301 }
begin
{ Store the away reason in the user object. }
User.Reason := Token[4];
if Assigned(FOnAway) then
begin
FOnAway(Self, User);
end;
end;
RPL_USERHOST: { 302 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'USERHOST', Token[3]);
end;
RPL_ISON: { 303 }
{ Check to see if this is a response to a notify request. }
{ FIXME: Needs to be implemented. }
{ Not a notify request response, so just output as received. }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'ISON', Token[2]); {Do not Localize}
end;
RPL_UNAWAY: { 305 }
begin
FAway := False;
if Assigned(FOnUnAway) then
begin
FOnUnAway(Self, Token[3]);
end;
end;
RPL_NOWAWAY: { 306 }
begin
FAway := True;
if Assigned(FOnNowAway) then
begin
FOnNowAway(Self, Token[3]);
end;
end;
307: { :server 307 yournick whoisnick :is a registered and identified nick }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s %s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_WHOISUSER: { 311 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s is %s@%s %s %s', [Token[3], Token[4], Token[5], Token[6], Token[7]])); {Do not Localize}
end;
RPL_WHOISSERVER: { 312 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s is using %s %s', [Token[3], Token[4], Token[5]])); {Do not Localize}
end;
RPL_WHOISOPERATOR: { 313 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s %s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_WHOWASUSER: { 314 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOWAS', Format('%s was %s@%s %s %s', [Token[3], Token[4], Token[5], Token[6], Token[7]])); {Do not Localize}
end;
RPL_ENDOFWHO: { 315 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHO', Format('%s :%s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_WHOISIDLE: { 317 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s has been idle %s seconds, signed on at %s', [Token[3], Token[4], Token[5]])); {Do not Localize}
end;
RPL_ENDOFWHOIS: { 318 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s :%s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_WHOISCHANNELS: { 319 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Format('%s is on %s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_LISTSTART: { 321 }
begin
if Assigned(FOnList) then
begin
FList.Clear;
FListLast:= 0;
FOnList(Self, FList, 0, False);
end;
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'LIST', 'Start of LIST'); {Do not Localize}
end;
end;
RPL_LIST: { 322 }
if Assigned(FOnList) then
begin
FList.Add(Format('%s %s %s', [Token[3], Token[4], Token[5]]));
if (FList.Count - FListLast = 40) then //SOMEONE MAY WANT TO SET THIS NUMBER!
begin
FOnList(Self, FList, FListLast, False);
FListLast:= FList.Count - 1;
end;
end;
RPL_LISTEND: { 323 }
begin
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'LIST', Token[3]); {Do not Localize}
end;
if Assigned(FOnList) then
begin
FOnList(Self, FList, FListLast, True);
FList.Clear;
FListLast:= 0;
end;
end;
RPL_CHANNELMODEIS: { 324 }
{ :sender 324 nick channel +mode [param[ param]] }
begin
{ Can safely call this function, because there should be
no +/-b, +/-o or +/-v modes (therefore the events
OnBan, OnUnban, OnOp, OnDeop, OnVoice and OnDevoice
will not get called). }
lcTemp:= Token[4];
for Index:= 5 to Token.Count - 1 do
begin
if Token[Index] <> '' then
begin
lcTemp:= lcTemp + ' ' + Token[Index];
end;
end;
if Assigned(FOnChannelMode) then
begin
FOnChannelMode(Self, nil, FChannels.Get(Token[3]), Token[3], lcTemp);
end;
ParseChannelModeChange(3);
{ FOnChannelMode(Sender, SenderNick, SenderAddress,
Channel) }
// if Assigned(FOnChannelMode) then
// FOnChannelMode(Self, SenderNick, SenderAddress, Token[3]);
end;
329: { 329 }
{ :sender 329 nick channel time }
begin
if Assigned(FOnSystem) then
FOnSystem(Self, User, CommandNumber, Command, Content);
end;
RPL_NOTOPIC: { 331 }
begin
{ Set topic in channel object. }
Channel := FChannels.Get(Token[3]);
if Channel <> nil then
begin
Channel.TopicChanged(''); {Do not Localize}
{ FOnNoTopic(Sender, Channel) }
if Assigned(FOnNoTopic) then
FOnNoTopic(Self, Channel, Token[4]);
end;
end;
RPL_TOPIC: { 332 }
begin
{ Set topic in channel object. }
Channel := FChannels.Get(Token[3]);
if Channel <> nil then
begin
Channel.TopicChanged(Token[4]);
{ FOnTopic(Sender, User, Channel) }
end;
if Assigned(FOnTopic) then
begin
FOnTopic(Self, User, Channel, Token[3],Token[4]);
end;
end;
RPL_INVITING: { 341 }
if Assigned(FOnInviting) then
begin
FOnInviting(Self, Token[3], Token[4]);
end;
RPL_SUMMONING: { 342 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'SUMMON', Format('%s has been summoned', [Token[2]])); {Do not Localize}
end;
RPL_VERSION: { 351 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'VERSION', Format('%s %s %s', [Token[3], Token[4], Token[5]])); {Do not Localize}
end;
RPL_WHOREPLY: { 352 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHO', Token[2]); {Do not Localize}
end;
RPL_NAMREPLY: { 353 }
{ :sender 353 nick = channel :[name[ name...]] }
begin
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'NAMES', Format('%s :%s', [Token[4], Token[5]])); {Do not Localize}
end;
{ Scan through names and add to channel. }
Channel := FChannels.Get(Token[4]);
if Channel <> nil then
begin
while Length(Token[5]) > 0 do
begin
Index := Pos(' ', Token[5]); {Do not Localize}
if Index > 0 then
begin
Channel.AddUser(Copy(Token[5], 1, Index - 1), ''); {Do not Localize}
Token[5] := Copy(Token[5], Index + 1, 512);
end
else
begin
Channel.AddUser(Token[5], ''); {Do not Localize}
Token[5] := ''; {Do not Localize}
end;
end;
{ Inform of a change in the channel info. }
if Assigned(Channel.OnChannelUpdate) then
Channel.OnChannelUpdate(Channel, cuNames, nil, 0);
end;
end;
RPL_LINKS: { 364 }
if Assigned(FOnLinks) then
begin
lcTemp:= Token[5];
FOnLinks(Self, Token[4], Token[3], COPY(lcTemp, 1, POS(' ', lcTemp) - 1), COPY(lcTemp, POS(' ', lcTemp) + 1, Length(lcTemp)));
end;
RPL_ENDOFLINKS: { 365 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'LINKS', Format('%s %s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_ENDOFNAMES: { 366 }
begin
Channel := FChannels.Get(Token[3]);
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'NAMES', Format('%s :%s', [Token[3], Token[4]])); {Do not Localize}
end;
if Assigned(FOnNames) then
begin
FOnNames(Self,fUsers,Channel);
end;
end;
RPL_BANLIST: { 367 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'BANS', Format('%s %s', [Token[2], Token[3]])); {Do not Localize}
end;
RPL_ENDOFBANLIST: { 368 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'BANS', Format('%s :%s', [Token[2], Token[3]])); {Do not Localize}
end;
RPL_ENDOFWHOWAS: { 369 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOWAS', Format('%s :%s', [Token[3], Token[4]])); {Do not Localize}
end;
RPL_INFO: { 371 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'INFO', Token[2]); {Do not Localize}
end;
RPL_MOTD: { 372 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'MOTD', Token[3]); {Do not Localize}
end;
RPL_ENDOFINFO: { 374 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'INFO', Token[2]); {Do not Localize}
end;
RPL_MOTDSTART: { 375 }
begin
{ Set state to connected. May need this elsewhere too. }
SeTIdIRCState(csConnected);
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'MOTD', Token[3]); {Do not Localize}
end;
end;
RPL_ENDOFMOTD: { 376 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'MOTD', Token[3]); {Do not Localize}
end;
RPL_YOUREOPER: { 381 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'OPER', Token[2]); {Do not Localize}
end;
RPL_REHASHING: { 382 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'REHASH', Format('%s :%s', [Token[2], Token[3]])); {Do not Localize}
end;
RPL_TIME: { 391 }
if Assigned(FOnSystem) then
begin
if UpperCase(Token[0]) = UpperCase(Token[3]) then
begin
FOnSystem(Self, User, CommandNumber,'TIME', Format('%s :%s', [Token[0], Token[4]]))
end
else
begin
FOnSystem(Self, User, CommandNumber,'TIME', Format('%s :%s', [Token[0], Token[3]]));
end;
end;
RPL_USERSSTART: { 392 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'USERS', Token[2]); {Do not Localize}
end;
RPL_USERS: { 393 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'USERS', Token[2]); {Do not Localize}
end;
RPL_ENDOFUSERS: { 394 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'USERS', Token[2]); {Do not Localize}
end;
RPL_NOUSERS: { 395 }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'USERS', Token[2]); {Do not Localize}
end;
{ All responses from 401 to 502 are errors. }
ERR_NOSUCHNICK.. { 401 }
ERR_USERSDONTMATCH: { 502 }
begin
{ Call the general error handler. }
if Assigned(FOnError) then
begin
FOnError(Self, User, Command, Content);
end;
{ ERR_NICKNAMEINUSE special case for registration
process. }
{ FIXME: Need to update own user object with chosen nick. }
if (CommandNumber >= ERR_NONICKNAMEGIVEN) and (CommandNumber <= ERR_NICKNAMEINUSE) and (FState = csLoggingOn) then
begin
{ Try the AltNick. }
if FCurrentNick = FNick then
begin
FCurrentNick:= FAltNick;
end
{ Tried the AltNick, so ask the user for another one. }
else
begin
if FCurrentNick = FAltNick then
begin
if Assigned(FOnNicksInUse) then
FOnNicksInUse(Self, FCurrentNick)
else
FCurrentNick := ''; {Do not Localize}
end;
end;
{ If there is another nick to try, send it. }
if FCurrentNick <> '' then {Do not Localize}
begin
SetNick(FCurrentNick);
end
else
begin
Disconnect(True);
end;
end;
end;
614: { :server 614 yournick :whoisnick (host.net) is using modes: +modes }
if Assigned(FOnSystem) then
begin
FOnSystem(Self, User, CommandNumber,'WHOIS', Token[3]); {Do not Localize}
end;
else
begin
if Assigned(FOnUnknownCommand) then
begin
FOnUnknownCommand(Self, User, Command, Content);
end;
end;
end;
end
else
begin
{ Try to match with a text command. }
CommandNumber := MatchCommand;
if CommandNumber > -1 then
begin
case CommandNumber of
0:
{ PRIVMSG nick/#channel :message }
{ Check for CTCP query. }
if (Token[3] <> '') AND (Token[3][1] = #1) then
begin
ParseCTCPQuery;
end
else
begin
if Assigned(FOnMessage) then
begin
FOnMessage(Self, User, FChannels.Get(Token[2]), Token[3]);
end;
end;
1:
{ NOTICE nick/#channel :message }
{ Check for CTCP reply. }
if (Token[3] <> '') and (Token[3][1] = #1) then
begin
ParseCTCPReply;
end
else
begin
if Assigned(FOnNotice) then
begin
FOnNotice(Self, User, FChannels.Get(Token[2]), Token[3]);
end;
end;
2:
{ JOIN #channel }
if SenderNick = FCurrentNick then
begin
{ Add the channel object to the channel list, and set it as
active. }
Channel := FChannels.Add(Token[2]);
Channel.Active := True;
{ Need to send a MODE query so we can get the channel mode. }
Mode(Token[2], '', ''); {Do not Localize}
if Assigned(FOnJoined) then
begin
FOnJoined(Self, Channel);
end;
end
else
begin
{ Add the new user to the channel object. }
Channel := FChannels.Get(Token[2]);
Channel.Joined(User);
if Assigned(FOnJoin) then
begin
FOnJoin(Self, User, Channel);
end;
end;
3:
{ PART #channel }
begin
{ Store the part reason in the user object. }
User.Reason := Token[3];
if SenderNick = FCurrentNick then
begin
{ Mark the channel object as inactive. }
Channel := FChannels.Get(Token[2]);
Channel.Active := False;
Channel.CloseType := ctPart;
if Assigned(FOnParted) then
begin
FOnParted(Self, Channel);
end;
FChannels.Remove(Token[2]);
end
else
begin
Channel := FChannels.Get(Token[2]);
Channel.Parted(User);
if Assigned(FOnPart) then
FOnPart(Self, User, Channel);
end;
end;
4:
{ KICK #channel target :reason }
begin
{ Store the kick reason in the user object. }
User.Reason := Token[4];
if Token[3] = FCurrentNick then
begin
{ Mark the channel object as inactive. }
Channel := FChannels.Get(Token[2]);
Channel.Active := False;
Channel.CloseType := ctKick;
if Assigned(FOnKicked) then
begin
FOnKicked(Self, User, Channel);
end;
FChannels.Remove(Token[2]);
end
else
begin
Channel := FChannels.Get(Token[2]);
Target := FUsers.Add(Token[3], ''); {Do not Localize}
{ Copy the kick reason to the target's user object. } {Do not Localize}
Target.Reason := User.Reason;
if Assigned(FOnKick) then
begin
FOnKick(Self, User, Target, Channel);
end;
Channel.Kicked(Target);
FUsers.Remove(Target);
end;
end;
5:
{ MODE nick/#channel +/-modes parameters... }
if IsChannel(Token[2]) then
{ Channel mode change }
begin
if FChannels.Find(Token[2], Index) then
begin
lcTemp:= Token[3];
for Index:= 4 to Token.Count - 1 do
begin
//TODO: This could be better as noted in BUg report 531202
//but it does work on a temporary basis. This is necessary as there
//is more than one entry for User Modes
if Token[Index] <> '' then
begin
lcTemp:= lcTemp + ' ' + Token[Index];
end;
end;
if Assigned(FOnChannelMode) then
begin
FOnChannelMode(Self, FUsers.Get(SenderNick), FChannels.Get(Token[2]), Token[2], lcTemp);
end;
ParseChannelModeChange(2);
// if ParseChannelModeChange(2) then
// if Assigned(FOnChannelModeChanged) then
// with FChannels.Get(Token[2]) do
// FOnChannelModeChanged(Self, SenderNick, SenderAddress, Token[2], Mode, Limit, Key);
end;
end
else
{ User mode change }
begin
if Token[2] = FCurrentNick then
begin
if Assigned(FOnUserMode) then
begin
FOnUserMode(Self, Token[3]);
end;
if ParseUserModeChange then
begin
if Assigned(FOnUserModeChanged) then
begin
FOnUserModeChanged(Self);
end;
end;
end;
end;
6:
{ NICK newnick }
begin
if (SenderNick = FCurrentNick) then
begin
lcTemp:= FCurrentNick;
FCurrentNick := Token[2];
if Assigned(FOnNickChanged) then
begin
FOnNickChanged(Self, lcTemp);
end;
end
else
begin
if Assigned(FOnNickChange) then
begin
FOnNickChange(Self, User, Token[2]);
end;
end;
{ Go through all channels and inform of the nick change. }
FChannels.ChangedNick(User, Token[2]);
{ Apply the new nick. }
User.Nick := Token[2];
end;
7:
{ QUIT :reason }
begin
{ Store the quit reason. }
User.Reason := Token[2];
if Assigned(FOnQuit) then
begin
FOnQuit(Self, User);
end;
{ Go through all channels and inform of the quit. }
FChannels.Quit(User);
end;
8:
{ INVITE nick :#channel }
if Assigned(FOnInvite) then
begin
FOnInvite(Self, User, Token[3]);
end;
9:
{ KILL nick :reason }
if Assigned(FOnKill) then
begin
FOnKill(Self, User, Token[2], Token[3]);
end;
10:
{ PING server }
begin
{ Send the PONG response }
Raw(Format('PONG :%s', [Token[2]])); {Do not Localize}
if Assigned(FOnPingPong) then
begin
FOnPingPong(Self);
end;
end;
11:
{ WALLOPS :message }
if Assigned(FOnWallops) then
begin
FOnWallops(Self, User, Token[2]);
end;
12:
{TOPIC}
begin
Channel := fChannels.Get(Token[2]);
if Channel <> nil then
begin
Channel.TopicChanged(Token[3]);
if Assigned(FOnTopic) then
begin
FOnTopic(Self, User, Channel, Channel.Name, Token[3]);
end;
end;
end;
end;
end
else
{ Unknown command from server }
begin
if Assigned(FOnUnknownCommand) then
begin
FOnUnknownCommand(Self, User, Command, Content);
end;
end;
end;
{ Release the sender user object. }
FUsers.Remove(User);
end;
{ Attempt to match the given DCC command with one of a list of DCC commands.
If a match is found, then the index of that command is returned, else the
return value is -1. }
function TIdIRC.MatchDCC(ADCC: String): Integer;
var
Index: Integer;
begin
Index := 0;
Result := -1;
while (Result < 0) and (Index <= High(DCCs)) do
begin
if ADCC = DCCs[Index] then
begin
Result := Index;
end;
Inc(Index);
end;
end;
{ Attempt to match the given CTCP command with one of a list of CTCP commands.
If a match is found, then the index of that command is returned, else the
return value is -1. }
function TIdIRC.MatchCTCP(ACTCP: String): Integer;
var
Index: Integer;
begin
Index := 0;
Result := -1;
while (Result < 0) and (Index <= High(CTCPs)) do
begin
if ACTCP = CTCPs[Index] then
begin
Result := Index;
end;
Inc(Index);
end;
end;
{ Parse a DCC query and call the appropriate event handlers. }
procedure TIdIRC.ParseDCC(ADCC: String);
var
DCCToken: TStringList;
begin
DCCToken:= TStringList.Create;
ADCC:= ADCC + ' ';
while POS(' ', ADCC) > 0 do
begin
DCCToken.Add(COPY(ADCC, 1, POS(' ', ADCC) -1));
DELETE(ADCC, 1, POS(' ', ADCC));
end;
case MatchDCC(DCCToken[0]) of
0:
{SEND}
begin
if Assigned(FOnDCCSend) then
begin
FOnDCCSend(Self, SenderNick, DCCToken[2], DCCToken[3], DCCToken[1], DCCToken[4]);
end;
end;
1:
{CHAT}
begin
if Assigned(FOnDCCChat) then
begin
FOnDCCChat(Self, SenderNick, DCCToken[2], DCCToken[3]);
end;
end;
2:
{RESUME}
begin
if Assigned(FOnDCCResume) then
begin
FOnDCCResume(Self, SenderNick, DCCToken[2], DCCToken[1], DCCToken[3]);
end;
end;
3:
{ACCEPT}
begin
if Assigned(FOnDCCAccept) then
begin
FOnDCCAccept(Self, SenderNick, DCCToken[2], DCCToken[1], DCCToken[3]);
end;
end;
end;
DCCToken.Free;
end;
{ Parse a CTCP query and call the appropriate event handlers. }
procedure TIdIRC.ParseCTCPQuery;
var
CTCP, Args: String;
Index, L: Integer;
User: TIdIRCUser;
Suppress: Boolean;
begin
L := Length(Token[3]);
Index := Pos(' ', Token[3]); {Do not Localize}
if Index > 0 then
begin
{ CTCP command plus parameters. }
CTCP := Copy(Token[3], 2, Index - 2);
Args := Copy(Token[3], Index + 1, L - Index - 1);
end
else
begin
{ No parameters. }
CTCP := Copy(Token[3], 2, L - 2);
Args := ''; {Do not Localize}
end;
Suppress := False;
User := FUsers.Add(SenderNick, SenderAddress);
case MatchCTCP(CTCP) of
-1:
{ Unknown CTCP query. }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
{ Suppressing an unknown CTCP query has no meaning, so ignore the
Suppress variable. }
end;
end;
0:
{ ACTION }
begin
if Assigned(FOnAction) then
FOnAction(Self, User, FChannels.Get(Token[2]), Args);
end;
1:
{ SOUND }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppressing an CTCP SOUND query has no meaning, so ignore the
Suppress variable. }
end;
2:
{ PING }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard PING response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Args);
end;
end;
3:
{ FINGER }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard FINGER response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Replies.Finger);
end;
end;
4:
{ USERINFO }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard USERINFO response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Replies.UserInfo);
end;
end;
5:
{ VERSION }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard VERSION response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Replies.Version);
end;
end;
6:
{ CLIENTINFO }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard CLIENTINFO response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Replies.ClientInfo);
end;
end;
7:
{ TIME }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
{ Suppress the standard TIME response if requested. }
if not Suppress then
begin
CTCPReply(SenderNick, CTCP, Format(RSIRCTimeIsNow, [DateTimeToStr(Now)])); {Do not Localize}
end;
end;
8:
{ ERROR }
begin
if Assigned(FOnCTCPQuery) then
begin
FOnCTCPQuery(Self, User, FChannels.Get(Token[2]), CTCP, Args, Suppress);
end;
end;
9:
{ DCC }
begin
ParseDCC(Args);
end;
end;
{ Release the user object. }
FUsers.Remove(User);
end;
{ Parse a CTCP reply and call the appropriate event handlers. }
procedure TIdIRC.ParseCTCPReply;
var
CTCP, Args: String;
Index, L: Integer;
User: TIdIRCUser;
begin
L := Length(Token[3]);
Index := Pos(' ', Token[3]); {Do not Localize}
if Index > 0 then
begin
{ CTCP command plus parameters. }
CTCP := Copy(Token[3], 2, Index - 2);
Args := Copy(Token[3], Index + 1, L - Index - 1);
end
else
begin
{ No parameters. }
CTCP := Copy(Token[3], 2, L - 2);
Args := ''; {Do not Localize}
end;
User := FUsers.Add(SenderNick, SenderAddress);
case MatchCTCP(CTCP) of
-1..8:
begin
if Assigned(FOnCTCPReply) then
begin
FOnCTCPReply(Self, User, FChannels.Get(Token[2]), CTCP, Args);
end;
end;
9:
{ DCC }
begin
{ FIXME: To be completed. }
end;
end;
{ Release the user object. }
FUsers.Remove(User);
end;
{ Evaluate the channel mode change command. }
function TIdIRC.ParseChannelModeChange(AChannelToken: Integer): Boolean;
var
i: Integer;
j: Integer;
Channel: TIdIRCChannel;
User, Target: TIdIRCUser;
ChangeType: TIdIRCChangeType;
NewChannelMode: TIdIRCChannelModes;
begin
Result := False;
ChangeType := ctAdd;
Channel := FChannels.Get(Token[AChannelToken]);
if Channel = nil then
begin
Exit;
end;
User := FUsers.Get(SenderNick);
NewChannelMode := Channel.Mode;
j := AChannelToken + 2; { Token 4 is the first parameter }
for i := 1 to Length(Token[AChannelToken + 1]) do
case Token[AChannelToken + 1][i] of
'+': {Do not Localize}
{ Add mode. }
ChangeType := ctAdd;
'-': {Do not Localize}
{ Remove mode. }
ChangeType := ctSubtract;
'b': {Do not Localize}
{ Set/Remove channel ban. }
if ChangeType = ctAdd then
begin
if Assigned(FOnBan) then
begin
FOnBan(Self, User, Channel, Token[j]);
end;
Inc(j);
end
else
begin
if Assigned(FOnUnban) then
begin
FOnUnban(Self, User, Channel, Token[j]);
end;
Inc(j);
end;
'i': {Do not Localize}
{ Invite only channel. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmInviteOnly];
end
else
begin
NewChannelMode := NewChannelMode - [cmInviteOnly];
end;
'k': {Do not Localize}
{ Set/Remove channel key. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmKey];
Channel.KeyChanged(Token[j]);
Inc(j);
end
else
begin
NewChannelMode := NewChannelMode - [cmKey];
Channel.KeyChanged(''); {Do not Localize}
end;
'l': {Do not Localize}
{ Set/Remove user limit. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmUserLimit];
Channel.LimitChanged(StrToIntDef(Token[j], 0));
Inc(j);
end
else
begin
NewChannelMode := NewChannelMode - [cmUserLimit];
Channel.LimitChanged(0);
end;
'm': {Do not Localize}
{ Moderated channel. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmModerated]
end
else
begin
NewChannelMode := NewChannelMode - [cmModerated];
end;
'n': {Do not Localize}
{ No External Messages. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmNoExternalMessages]
end
else
begin
NewChannelMode := NewChannelMode - [cmNoExternalMessages];
end;
'o': {Do not Localize}
{ Give or take operator priviliges. }
begin
Target := FUsers.Get(Token[j]);
if ChangeType = ctAdd then
begin
if Assigned(FOnOp) then
begin
FOnOp(Self, User, Channel, Target);
end;
{ Update the attributes. }
Channel.GotOp(Target);
Inc(j);
end
else
begin
if Assigned(FOnDeop) then
begin
FOnDeop(Self, User, Channel, FUsers.Get(Token[j]));
end;
{ Update the attributes. }
Channel.GotDeop(Target);
Inc(j);
end;
end;
'p': {Do not Localize}
{ Private channel. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmPrivate]
end
else
begin
NewChannelMode := NewChannelMode - [cmPrivate];
end;
's': {Do not Localize}
{ Secret channel. }
if ChangeType = ctAdd then
NewChannelMode := NewChannelMode + [cmSecret]
else
NewChannelMode := NewChannelMode - [cmSecret];
't': {Do not Localize}
{ Only operators set topic. }
if ChangeType = ctAdd then
begin
NewChannelMode := NewChannelMode + [cmOpsSetTopic]
end
else
begin
NewChannelMode := NewChannelMode - [cmOpsSetTopic];
end;
'v': {Do not Localize}
{ Give or take a voice on a moderated channel. }
begin
Target := FUsers.Get(Token[j]);
if ChangeType = ctAdd then
begin
if Assigned(FOnVoice) then
begin
FOnVoice(Self, User, Channel, Target);
end;
{ Update the attributes. }
Channel.GotVoice(Target);
Inc(j);
end
else
begin
if Assigned(FOnDevoice) then
begin
FOnDevoice(Self, User, Channel, Target);
end;
{ Update the attributes. }
Channel.GotDevoice(Target);
Inc(j);
end;
end;
end;
Result := (Channel.Mode <> NewChannelMode);
if Result then
begin
Channel.ModeChanged(NewChannelMode);
end;
end;
{ Evaluate user mode change. }
function TIdIRC.ParseUserModeChange: Boolean;
var
i: Integer;
ChangeType: TIdIRCChangeType;
NewUserMode: TIdIRCUserModes;
begin
ChangeType := ctAdd;
NewUserMode := FUserMode;
for i := 1 to Length(Token[3]) do
begin
if (Length(Token[3])>0) then
begin
case Token[3][i] of
'+': {Do not Localize}
{ Add mode. }
ChangeType := ctAdd;
'-': {Do not Localize}
{ Remove mode. }
ChangeType := ctSubtract;
'i': {Do not Localize}
{ Invisible. }
if ChangeType = ctAdd then
begin
NewUserMode := NewUserMode + [umInvisible]
end
else
begin
NewUserMode := NewUserMode - [umInvisible];
end;
'o': {Do not Localize}
{ IRC Operator. }
if ChangeType = ctAdd then
begin
NewUserMode := NewUserMode + [umOperator]
end
else
begin
NewUserMode := NewUserMode - [umOperator];
end;
's': {Do not Localize}
{ Receive server notices. }
if ChangeType = ctAdd then
begin
NewUserMode := NewUserMode + [umServerNotices]
end
else
begin
NewUserMode := NewUserMode - [umServerNotices];
end;
'w': {Do not Localize}
{ Receive wallops. }
if ChangeType = ctAdd then
begin
NewUserMode := NewUserMode + [umWallops]
end
else
begin
NewUserMode := NewUserMode - [umWallops];
end;
end;
end;
end;
Result := (FUserMode <> NewUserMode);
if Result then
begin
FUserMode := NewUserMode;
end;
end;
{ Return True if the string Channel is a channel name. }
function TIdIRC.IsChannel(AChannel: String): Boolean;
begin
Result := (Length(AChannel)>0) and (AChannel[1] in IRCChannelPrefixes);
end;
{ Return True if the string Nick is a channel operator. }
function TIdIRC.IsOp(ANick: String): Boolean;
begin
Result := (Length(Nick)>0) and (Nick[1] = '@'); {Do not Localize}
end;
{ Return True if the string Nick has a voice. }
function TIdIRC.IsVoice(ANick: String): Boolean;
begin
Result := (Length(Nick)>0) and (Nick[Length(Nick)] = '+'); {Do not Localize}
end;
{ Returns True if the address matches the hostmask. Uses a recursive method
to perform the check. }
function TIdIRC.MatchHostmask(AAddress, AHostmask: PChar): Boolean;
begin
if StrComp(AHostmask, '*') = 0 then {Do not Localize}
begin
Result := True;
end
else
begin
if (AAddress^ = #0) and (AHostmask^ <> #0) then
begin
Result := False;
end
else
begin
if (AAddress^ = #0) then
begin
Result := True;
end
else
case AHostmask^ of
'*': {Do not Localize}
if MatchHostmask(AAddress, AHostmask + 1) then
begin
Result := True;
end
else
begin
Result := MatchHostmask(AAddress + 1, AHostmask);
end;
'?': {Do not Localize}
Result := MatchHostmask(AAddress + 1, AHostmask + 1);
else
if AAddress^ = AHostmask^ then
begin
Result := MatchHostmask(AAddress + 1, AHostmask + 1)
end
else
begin
Result := False;
end;
end;
end;
end;
end;
{ Return a string representation of the user mode. }
function TIdIRC.GetModeString: String;
var
Element: TIdIRCUserMode;
begin
{ Only bother if there are actually modes to show. }
if FUserMode <> [] then
begin
Result := '+'; {Do not Localize}
{ Add all mode characters. }
for Element := umInvisible to umWallops do
begin
if Element in FUserMode then
begin
Result := Result + UserModeChars[Ord(Element)];
end;
end;
end
else
begin
Result := ''; {Do not Localize}
end;
end;
constructor TIdIRCReadThread.Create(AClient: TIdIRC);
begin
inherited Create(False);
FClient := AClient;
FreeOnTerminate := True;
end;
procedure TIdIRCReadThread.Run;
begin
FRecvData := FClient.ReadLn;
Synchronize(FClient.SocketDataAvailable);
FClient.CheckForDisconnect;
end;
procedure TIdIRCChannels.Sort;
{I found this procedure at:
http://groups.google.com/groups?q=Sort+TCollection&start=30&hl=en&safe=off&rnum=35&selm=904181166%40f761.n5030.z2.FidoNet.ftn
and it seems to look good.}
function DoCompare(AItem1, AItem2 : TIdIRCChannel) : Integer;
begin
if Assigned(FOnSortCompareChanels) then
begin
FOnSortCompareChanels(Self,AItem1, AItem2, Result);
end
else
begin
Result := 0;
end;
end;
procedure SwapItems(i, j : Integer);
var
T : TIdIRCChannel;
begin
T := Items[i];
Items[i] := Items[j];
Items[j] := T;
end;
procedure SortItems(iStart, iEnd : Integer);
var
i, j : Integer;
Med : TIdIRCChannel;
begin
while iStart < iEnd do
begin
i := iStart;
j := iEnd;
if iStart = iEnd-1 then
begin
if DoCompare(Items[iStart], Items[iEnd]) > 0 then
begin
SwapItems(iStart, iEnd);
end;
Break;
end;
Med := Items[(i + j) div 2];
repeat
while DoCompare(Items[i], Med) < 0 do
begin
Inc(i);
end;
while DoCompare(Items[j], Med) > 0 do
begin
Dec(j);
end;
if i <= j then
begin
SwapItems(i, j);
Inc(i);
Dec(j);
end;
until i > j;
if j-iStart > iEnd-i then
begin
SortItems(i, iEnd);
iEnd := j;
end
else
begin
SortItems(iStart, j);
iStart := i;
end;
end;
end;
begin
if Count > 0 then
begin
SortItems(0, Count - 1);
end;
end;
end.
|
{
Mystix
Copyright (C) 2005 Piotr Jura
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You can contact with me by e-mail: pjura@o2.pl
}
unit uAbout;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TAboutDialog = class(TForm)
Label1: TLabel;
lblVersion: TLabel;
Label3: TLabel;
Label4: TLabel;
Button1: TButton;
memContributors: TMemo;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure ReadLanguageData;
public
{ Public declarations }
end;
var
AboutDialog: TAboutDialog;
implementation
uses uMain, uMyIniFiles, uUtils;
{$R *.dfm}
procedure TAboutDialog.FormCreate(Sender: TObject);
begin
ReadLanguageData;
if FileExists(AppPath + 'Contributors.txt') then
memContributors.Lines.LoadFromFile(AppPath + 'Contributors.txt');
end;
procedure TAboutDialog.ReadLanguageData;
begin
with TMyIniFile.Create(Languages.Values[ActiveLanguage]) do
try
Caption := ReadString('AboutDialog', 'Caption', '');
lblVersion.Caption := Format(ReadString('AboutDialog', 'lblVersion.Caption', ''), [ProjectVersion]);
finally
Free;
end;
end;
end.
|
{***********************************************************************
Unit gfx_Effects.PAS v1.0 0799
(c) by Andreas Moser, amoser@amoser.de,
gfx_Effects is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
for more information about image processing look at this book:
Computer Graphics - Principles and Practice, Foley et al
********************************************************************************}
UNIT gfx_effects;
INTERFACE
USES Windows, Graphics,classes,sysutils{,forms},comctrls,gfx_basedef,math;
TYPE
{definiton used by EffectSwapChannels}
TSwapPlanes= (swapNone,swapRedBlue,swapRedGreen,swapBlueGreen);
{definition used by EffectArithmetic}
TGraphicArithmetic=(gaNone,gaAdd,gaSubstract,gaMultiply,gaDivide,gaDarkest,
gaLightest,gaDifference,gaBinaryOr,gaBinaryAnd,gaAverage);
{Static filters}
TStaticFilterType=(sfMedian,sfMin,sfMax);
{Filter types}
TFilterType=(ftStatic,ftLinear,ftMultiPass);
{Matrix size (3x3, 5x5, 7x7}
TMatrixSize = (mxDefault,mx3,mx5,mx7);
{TEffectMatrix used by EffectLinearFilterRGB}
TEffectMatrix = array[0..6,0..6] of Integer;
pEffectMatrix = ^TEffectMatrix;
{TGraphicFilter used by EffectLinearFilterRGB /EffectStaticFilterRGB}
TGraphicFilter = packed record
FilterType: TFilterType;
MatrixSize: TMatrixSize; // Size: mx3=3x3, mx5=5x5, mx7=7x7
Matrix: TEffectMatrix; // Every pixel of source would be calculated by the matrix
Divisor: Integer; // The result of calculation would be divided by divisor (>0!)
Bias: Integer; // Finally bias value would be added
FilterName: Array [0..128] of Char;
end;
pGraphicFilter=^TGraphicFilter;
{TMultiPassGraphicFilter used by EffectMultiPassFilter}
TMultiPassGraphicFilter=packed record
FilterType:TFilterType;
Filters:array [1..4] of pGraphicFilter;
Functions:array [1..3] of TGraphicArithmetic;
FilterName:Array [0..100] of Char;
end;
pMultiPassGraphicFilter=^TMultiPassGraphicFilter;
type TDirection = (TopToBtm, BtmToTop, LftToRgt,RgtToLft,TopLftToBtmRgt, BtmLftToTopRgt, All);
TEffectCallBack = procedure (const Min,Max,Pos:Integer);
procedure EffectAddNoise(SrcBitmap,DestBitmap:TBitmap;Value:Integer;MonoNoise:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectAntiAlias(SrcBitmap,DestBitmap:TBitmap;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectArithmetic(SrcBitmapOne,SrcBitmapTwo,DestBitmap:TBitmap;Arithmetic:TGraphicArithmetic;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectBlend(SrcBitmapOne,SrcBitmapTwo,DestBitmap:TBitmap;Multiplicator,MaxBlendValue:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectCircleAround(SrcBitmap,DestBitmap:TBitmap;Value:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectColorize(SrcBitmap,DestBitmap:TBitmap;Hue,Saturation,Lightness:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectContrast(SrcBitmap,DestBitmap:TBitmap;Value:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectEllipse(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectFishEye(SrcBitmap,DestBitmap:TBitmap;Value:Extended;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectGamma(SrcBitmap,DestBitmap:TBitmap;Gamma:Double;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectGreyScale(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectIncDecRGB(SrcBitmap,DestBitmap:TBitmap;dR,dG,dB:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectLightness(SrcBitmap,DestBitmap:TBitmap;Value:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectMosaic(SrcBitmap,DestBitmap:TBitmap;Width,Height:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectNegative(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectPosterize(SrcBitmap,DestBitmap:TBitmap;BitsPerChannel:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectSinus(SrcBitmap,DestBitmap:TBitmap;SinusAmpVert,VertDelta,SinusAmpHorz,HorzDelta,VertStart,HorzStart:Integer;ChngVertAtAnyCol:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectSolarize(SrcBitmap,DestBitmap:TBitmap;Threshold:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectSpray(SrcBitmap,DestBitmap:TBitmap;Value:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectStretch(SrcBitmap,DestBitmap:TBitmap;Low,High:Integer;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectSwapChannels(SrcBitmap,DestBitmap:TBitmap;WhichPlanes:TSwapPlanes;const EffectCallBack:TEffectCallBack);stdcall;
{Filter functions: For universal processing use EffectFilter..the class looks for itself which filter will be used}
procedure EffectFilter(SrcBitmap,DestBitmap:TBitmap;Filter:TGraphicFilter;Size:TMatrixSize;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectStaticFilter(SrcBitmap,DestBitmap:TBitmap;StaticFilterType:TStaticFilterType;Diameter:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectMultiPass(SrcBitmap,DestBitmap:TBitmap;MultiPassFilter:TMultiPassGraphicFilter;Passes:Integer;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure EffectLinearFilter(SrcBitmap,DestBitmap:TBitmap;Filter:TGraphicFilter;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
procedure SaveLinearFilterToFile(FileName:PChar;const Filter:TGraphicFilter);stdcall;
procedure LoadLinearFilterFromFile(FileName:PChar;var Filter:TGraphicFilter);stdcall;
procedure SaveMultipassFilterToFile(FileName:PChar;const Filter:TMultiPassGraphicFilter);stdcall;
procedure LoadMultiPassFilterFromFile(FileName:PChar;var Filter:TMultiPassGraphicFilter);stdcall;
{Default Filter (NULL-Filter}
CONST mxZero:TGraphicFilter
=(FilterType:ftLinear;
MatrixSize:mx3;
Matrix:
(( 0, 0, 0, 0, 0, 0, 0),
( 0, 0, 0, 0, 0, 0, 0),
( 0, 0, 0, 0, 0, 0, 0),
( 0, 0, 0, 1, 0, 0, 0),
( 0, 0, 0, 0, 0, 0, 0),
( 0, 0, 0, 0, 0, 0, 0),
( 0, 0, 0, 0, 0, 0, 0));
Divisor:1;
Bias:0;
FilterName:'Null (Linear)');
{Default static filters}
mxMedian:TGraphicFilter
=(FilterType:ftStatic;
FilterName:'Median (Static)');
mxMaximum:TGraphicFilter
=(FilterType:ftStatic;
FilterName:'Maximum (Static)');
mxMinimum:TGraphicFilter
=(FilterType:ftStatic;
FilterName:'Minimum (Static)');
IMPLEMENTATION
// -----------------------------------------------------------------------------
//
// Blending two Bitmaps
//
// Parameter:
// SrcBitmapOne : 1st Bitmap
// SrcBitmapOne : 2nd Bitmap
// DestBitmap : Result
// Multiplicator,
// MaxBlendValue : The mixing of the two pictures...
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectBlend(SrcBitmapOne,SrcBitmapTwo,DestBitmap:TBitmap;Multiplicator,MaxBlendValue:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var
bmpTwo :TBitmap;
r, n, l :Integer;
SrcRow1,SrcRow2,DestRow :pRGBArray;
begin
bmptwo:=TBitmap.Create;
try
BMPTwo.PixelFormat:=pf24Bit;
SetBitmapsEql(SrcBitmapOne,DestBitmap);
BmpTwo.Width:=SrcBitmapOne.Width;
BmpTwo.Height:=SrcBitmapOne.Height;
if SrcBitmapTwo.Empty = TRUE then
bmpTwo.Canvas.FillRect(Rect(0,0,SrcBitmapOne.Width,SrcBitmapOne.Height))
else
begin
bmpTwo.Canvas.StretchDraw(Rect(0,0,SrcBitmapOne.Width,SrcBitmapOne.Height),SrcBitmapTwo);
end;
if MaxBlendValue < 1 then raise EGraphicEffects.Create('BlendRate must be between 0 AND 256');
r:=Multiplicator;
for n := 0 to SrcBitmapOne.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((n/SrcBitmapOne.Height)*100));
SrcRow1 := SrcBitmapOne.Scanline[n];
SrcRow2 := bmpTwo.Scanline[n];
DestRow := DestBitmap.Scanline[n];
for l := 0 to SrcBitmapOne.Width - 1 do WITH DestRow[l] do
begin
rgbtRed:=SrcRow1[l].rgbtRed+MulDiv(r, (SrcRow2[l].rgbtRed-SrcRow1[l].rgbtRed), MaxBlendValue);
rgbtGreen:=SrcRow1[l].rgbtGreen+MulDiv(r, (SrcRow2[l].rgbtGreen-SrcRow1[l].rgbtGreen), MaxBlendValue);
rgbtBlue:= SrcRow1[l].rgbtBlue+MulDiv(r, (SrcRow2[l].rgbtBlue-SrcRow1[l].rgbtBlue), MaxBlendValue);
end;
end;
finally
bmpTwo.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// Arithmetic between two Bitmaps
//
// Parameter:
// SrcBitmapOne : 1st Bitmap
// SrcBitmapOne : 2nd Bitmap
// DestBitmap : Result
// Arithmetic : Arithmetic type
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectArithmetic(SrcBitmapOne,SrcBitmapTwo,DestBitmap:TBitmap;Arithmetic:TGraphicArithmetic;const EffectCallBack:TEffectCallBack);stdcall;
var
bmpTwo :TBitmap;
Row, Col :Integer;
SrcRow1,SrcRow2,DestRow :pRGBArray;
begin
bmptwo:=TBitmap.Create;
try
SetBitmapsEql(SrcBitmapOne,DestBitmap);
BmpTwo.Width:=SrcBitmapOne.Width;
BmpTwo.Height:=SrcBitmapOne.Height;
BmpTwo.PixelFormat:=pf24Bit;
if SrcBitmapTwo.Empty = TRUE then bmpTwo.Canvas.FillRect(Rect(0,0,SrcBitmapOne.Width,SrcBitmapOne.Height))
ELSE bmpTwo.Canvas.StretchDraw(Rect(0,0,SrcBitmapOne.Width,SrcBitmapOne.Height),SrcBitmapTwo);
for Row := 0 to SrcBitmapOne.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmapOne.Height)*100));
SrcRow1 := SrcBitmapOne.Scanline[Row];
SrcRow2 := bmpTwo.Scanline[Row];
DestRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmapOne.Width - 1 do
begin
WITH DestRow[Col] do
CASE Arithmetic of
gaNone:begin
rgbtRed:=SrcRow1[Col].rgbtRed;
rgbtGreen:=SrcRow1[Col].rgbtGreen;
rgbtBlue:=SrcRow1[Col].rgbtBlue;
end;
gaAdd:begin
rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed+SrcRow2[Col].rgbtRed);
rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen+SrcRow2[Col].rgbtGreen);
rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue+SrcRow2[Col].rgbtBlue);
end;
gaSubstract:begin
rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed-SrcRow2[Col].rgbtRed);
rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen-SrcRow2[Col].rgbtGreen);
rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue-SrcRow2[Col].rgbtBlue);
end;
gaMultiply:begin
rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed*SrcRow2[Col].rgbtRed);
rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen*SrcRow2[Col].rgbtGreen);
rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue*SrcRow2[Col].rgbtBlue);
end;
gaDivide:begin
if SrcRow2[Col].rgbtRed<>0 then rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed DIV SrcRow2[Col].rgbtRed);
if SrcRow2[Col].rgbtGreen<>0 then rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen DIV SrcRow2[Col].rgbtGreen);
if SrcRow2[Col].rgbtBlue<>0 then rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue DIV SrcRow2[Col].rgbtBlue);
end;
gaDifference:begin
rgbtRed:=Abs(SrcRow1[Col].rgbtRed-SrcRow2[Col].rgbtRed);
rgbtGreen:=Abs(SrcRow1[Col].rgbtGreen-SrcRow2[Col].rgbtGreen);
rgbtBlue:=Abs(SrcRow1[Col].rgbtBlue-SrcRow2[Col].rgbtBlue);
end;
gaDarkest:begin
rgbtRed:=MinInt2(SrcRow1[Col].rgbtRed,SrcRow2[Col].rgbtRed);
rgbtGreen:=MinInt2(SrcRow1[Col].rgbtGreen,SrcRow2[Col].rgbtGreen);
rgbtBlue:=MinInt2(SrcRow1[Col].rgbtBlue,SrcRow2[Col].rgbtBlue);
end;
gaLightest:begin
rgbtRed:=MaxInt2(SrcRow1[Col].rgbtRed,SrcRow2[Col].rgbtRed);
rgbtGreen:=MaxInt2(SrcRow1[Col].rgbtGreen,SrcRow2[Col].rgbtGreen);
rgbtBlue:=MaxInt2(SrcRow1[Col].rgbtBlue,SrcRow2[Col].rgbtBlue);
end;
gaAverage:begin
rgbtRed:=TrimInt(0,255,(SrcRow1[Col].rgbtRed+SrcRow2[Col].rgbtRed)DIV 2);
rgbtGreen:=TrimInt(0,255,(SrcRow1[Col].rgbtGreen+SrcRow2[Col].rgbtGreen)DIV 2);
rgbtBlue:=TrimInt(0,255,(SrcRow1[Col].rgbtBlue+SrcRow2[Col].rgbtBlue)DIV 2);
end;
gaBinaryOr:begin
rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed OR SrcRow2[Col].rgbtRed);
rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen OR SrcRow2[Col].rgbtGreen);
rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue OR SrcRow2[Col].rgbtBlue);
end;
gaBinaryAnd:begin
rgbtRed:=TrimInt(0,255,SrcRow1[Col].rgbtRed AND SrcRow2[Col].rgbtRed);
rgbtGreen:=TrimInt(0,255,SrcRow1[Col].rgbtGreen AND SrcRow2[Col].rgbtGreen);
rgbtBlue:=TrimInt(0,255,SrcRow1[Col].rgbtBlue AND SrcRow2[Col].rgbtBlue);
end;
end;
end;
end;
finally
bmpTwo.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// Swap colorchannels
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Which planes : see TSwapPlanes (at the top of this unit)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectSwapChannels(SrcBitmap,DestBitmap:TBitmap;WhichPlanes:TSwapPlanes;const EffectCallBack:TEffectCallBack);stdcall;
var Row,Col :Integer;
SrcRow,DestRow :pRGBArray;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
SrcRow:=SrcBitmap.ScanLine[Row];
DestRow:=DestBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do
begin
WITH DestRow[Col] do
CASE WhichPlanes of
swapRedGreen:begin
rgbtBlue:=SrcRow[Col].rgbtBlue;
rgbtGreen:=SrcRow[Col].rgbtRed;
rgbtRed:=SrcRow[Col].rgbtBlue;
end;
swapRedBlue:begin
rgbtBlue:=SrcRow[Col].rgbtRed;
rgbtGreen:=SrcRow[Col].rgbtGreen;
rgbtRed:=SrcRow[Col].rgbtBlue;
end;
swapBlueGreen:begin
rgbtBlue:=SrcRow[Col].rgbtGreen;
rgbtGreen:=SrcRow[Col].rgbtBlue;
rgbtRed:=SrcRow[Col].rgbtRed;
end;
end;
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Greyscale Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectGreyScale(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
var Row,Col :Integer;
SrcRow,DestRow :pRGBArray;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
SrcRow:=SrcBitmap.ScanLine[Row];
DestRow:=DestBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do WITH DestRow[Col] do
begin
rgbtBlue:=RgbLightness(SrcRow[Col]);
rgbtGreen:=RgbLightness(SrcRow[Col]);
rgbtRed:=RgbLightness(SrcRow[Col]);
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Posterize Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// BitsPerChannel : How many Bits per channel
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectPosterize(SrcBitmap,DestBitmap:TBitmap;BitsPerChannel:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var Row,Col :Integer;
SrcRow,DestRow :pRGBArray;
Mask :Byte;
begin
if not BitsPerChannel in [1..8] then exit;
SetBitmapsEql(SrcBitmap,DestBitmap);
mask:=$FF;
CASE BitsPerChannel of
7:Mask:=$fe;
6:Mask:=$fc;
5:Mask:=$f8;
4:Mask:=$f0;
3:Mask:=$e0;
2:Mask:=$c0;
1:Mask:=$80;
end;
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
SrcRow:=SrcBitmap.ScanLine[Row];
DestRow:=DestBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do WITH DestRow[Col] do
begin
rgbtBlue:=(SrcRow[Col].rgbtBlue AND Mask);
rgbtGreen:=(SrcRow[Col].rgbtGreen AND Mask);
rgbtRed:=(SrcRow[Col].rgbtRed AND Mask);
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Solarize Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Threshold : Process only pixels above this value
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectSolarize(SrcBitmap,DestBitmap:TBitmap;Threshold:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var Row,Col :Integer;
SrcRow,DestRow :pRGBArray;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
SrcRow:=SrcBitmap.ScanLine[Row];
DestRow:=DestBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do
begin
if SrcRow[Col].rgbtBlue>=Threshold then DestRow[Col].rgbtBlue:=not SrcRow[Col].rgbtBlue
else DestRow[Col].rgbtBlue:=SrcRow[Col].rgbtBlue;
if SrcRow[Col].rgbtGreen>=Threshold then DestRow[Col].rgbtGreen:=not SrcRow[Col].rgbtGreen
else DestRow[Col].rgbtGreen:=SrcRow[Col].rgbtGreen;
if SrcRow[Col].rgbtRed>=Threshold then DestRow[Col].rgbtRed:=not SrcRow[Col].rgbtRed
else DestRow[Col].rgbtRed:=SrcRow[Col].rgbtRed;
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Negative Bitmap
//
// Parameter: (Remark: this is just the same as Solarize, just a threshold of zero)
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectNegative(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
begin
EffectSolarize(SrcBitmap,DestBitmap,0,EffectCallBack);
end;
// -----------------------------------------------------------------------------
//
// Lighten/Darken Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Value to be added/substracted (-255..0..255)
// R,G,B : Apply filter to R,G,B Planes (Boolean)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectLightness(SrcBitmap,DestBitmap:TBitmap;Value:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
Row,Col :Integer;
TargetRow :pRGBArray;
SourceRows :PPRows;
begin
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
SrcBitmap.PixelFormat:=pf24Bit;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Width:=SrcBitmap.Width;
DestBitmap.Height:=SrcBitmap.Height;
for Row:= 0 to SrcBitmap.Height - 1 do
SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
if R then TargetRow[Col].rgbtRed :=TrimReal(0,255,(SourceRows[Row][Col].rgbtRed)+Value)ELSE TargetRow[Col].rgbtRed :=SourceRows[Row][Col].rgbtRed;
if G then TargetRow[Col].rgbtGreen :=TrimReal(0,255,(SourceRows[Row][Col].rgbtGreen)+Value) ELSE TargetRow[Col].rgbtGreen :=SourceRows[Row][Col].rgbtGreen;
if B then TargetRow[Col].rgbtBlue :=TrimReal(0,255,(SourceRows[Row][Col].rgbtBlue)+Value)ELSE TargetRow[Col].rgbtBlue :=SourceRows[Row][Col].rgbtBlue;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Change Contrast
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Value to be added/substracted (-255..0..255)
// R,G,B : Apply filter to R,G,B Planes (Boolean)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectContrast(SrcBitmap,DestBitmap:TBitmap;Value:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
i,Row,Col :Integer;
TargetRow :pRGBArray;
SourceRows :PPRows;
ColArray :Array [0..256] of Byte;
begin
for i:=0 to 126 do
begin
ColArray[i]:=TrimInt(0,255,i-((Abs(128-i)*Value)div 256));
end;
for i:=127 to 255 do
begin
ColArray[i]:=TrimInt(0,255,i+((Abs(128-i)*Value)div 256));
end;
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
SrcBitmap.PixelFormat:=pf24Bit;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Width:=SrcBitmap.Width;
DestBitmap.Height:=SrcBitmap.Height;
for Row:= 0 to SrcBitmap.Height - 1 do
SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
if R then TargetRow[Col].rgbtRed :=ColArray[SourceRows[Row][Col].rgbtRed] else TargetRow[Col].rgbtRed:= SourceRows[Row][Col].rgbtRed;
if G then TargetRow[Col].rgbtGreen :=ColArray[SourceRows[Row][Col].rgbtGreen] else TargetRow[Col].rgbtGreen:= SourceRows[Row][Col].rgbtGreen;
if B then TargetRow[Col].rgbtBlue :=ColArray[SourceRows[Row][Col].rgbtBlue] else TargetRow[Col].rgbtBlue:= SourceRows[Row][Col].rgbtBlue;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Colorize Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Hue : Value to be added to Hue (0..359)
// Saturation : Value to be added to Saturation (0..255)
// Value : Value to be added to Value (0..255)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectColorize(SrcBitmap,DestBitmap:TBitmap;Hue,Saturation,Lightness:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var
Row,Col :Integer;
TargetRow :pRGBArray;
hsl :THSLTriple;
SourceRows :PPRows;
begin
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
SrcBitmap.PixelFormat:=pf24Bit;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Width:=SrcBitmap.Width;
DestBitmap.Height:=SrcBitmap.Height;
for Row:= 0 to SrcBitmap.Height - 1 do
SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
RGBtoHSL(SourceRows[Row][Col],hSl);
hsl.hslHue:=hsl.hslHue+Hue;
hsl.hslSaturation:=hsl.hslSaturation+Saturation;
hsl.hslLightness:=hsl.hslLightness+Lightness;
hsl.hslHue:=LoopInt(0,359,hsl.hslHue);
hsl.hslSaturation:=TrimInt(0,255,hsl.hslSaturation);
hsl.hslLightness:=TrimInt(0,255,hsl.hslLightness);
HSLToRGB(hsl,TargetRow[Col]);
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// IncDecRGB Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// dR : Value to be added to Red (0..255)
// dG : Value to be added to Green (0..255)
// dB : Value to be added to Blue (0..255)
// EffectCallBack : CallBack for user interface
//
// (c) September 1998 by Andreas Moser, amoser@amoser.de
// -----------------------------------------------------------------------------
procedure EffectIncDecRGB(SrcBitmap,DestBitmap:TBitmap;dR,dG,dB:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var
Row,Col :Integer;
TargetRow :pRGBArray;
SourceRows :PPRows;
begin
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
SrcBitmap.PixelFormat:=pf24Bit;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Width:=SrcBitmap.Width;
DestBitmap.Height:=SrcBitmap.Height;
for Row:= 0 to SrcBitmap.Height - 1 do
SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
TargetRow[Col].rgbtRed :=TrimReal(0,255,(SourceRows[Row][Col].rgbtRed)+dR);
TargetRow[Col].rgbtGreen :=TrimReal(0,255,(SourceRows[Row][Col].rgbtGreen)+dG);
TargetRow[Col].rgbtBlue :=TrimReal(0,255,(SourceRows[Row][Col].rgbtBlue)+dB);
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Apply filter to Bitmap
// (just an interface for the 3 following procedures)
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Size : Optional:Size of the calculated area 1..7 (neighbours of the pixel)
// if set to 0, the default size for the filter will be used
// (normally for linear 3x3, for static filters a diameter of 3)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectFilter(SrcBitmap,DestBitmap:TBitmap;Filter:TGraphicFilter;Size:TMatrixSize;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var d:Integer;
sft:TStaticFilterType;
begin
CASE Filter.FilterType of
ftLinear:begin
if Size > mxDefault then
Filter.MatrixSize:=Size;
EffectLinearFilter(SrcBitmap,DestBitmap,Filter,ColorSpace,Channel1,Channel2,Channel3,EffectCallBack);
end;
ftStatic:begin
d:=3;
CASE Size of
mx3:d:=3;
mx5:d:=5;
mx7:d:=7;
end;
if Filter.FilterName='Minimum (Static)' then sft:=sfMin ELSE if
Filter.FilterName='Maximum (Static)' then sft:=sfMax ELSE sft:=sfMedian;
EffectStaticFilter(SrcBitmap,DestBitmap,sft,d,Channel1,Channel2,Channel3,EffectCallBack);
end
end;
end;
// -----------------------------------------------------------------------------
//
// Apply Median static filter to Bitmap
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Diameter : Size of the calculated area 1..7 (neighbours of the pixel)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectStaticFilter(SrcBitmap,DestBitmap:TBitmap;StaticFilterType:TStaticFilterType;Diameter:Integer;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
row,col :Integer;
k,i :Integer;
Medium,Min,Max :Integer;
m,mx,my :Integer;
HorzLine,VertLine :Integer;
MaxCol,MaxRow :Integer;
MinCol,MinRow :Integer;
SourceRows :PPRows;
TargetRow :pRGBArray;
lLightness :array[0..6,0..6] of Integer;
BorderDiffX,BorderDiffY :Integer;
begin
if Diameter in [3,5,7] then
begin
Diameter:=Diameter DIV 2;
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
SourceRows[Row]:=SrcBitmap.Scanline[Row];
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
MinRow:=-Diameter;
MaxRow:=Diameter;
MinCol:=-Diameter;
Maxcol:=Diameter;
for HorzLine:=MinRow to MaxRow do
begin
{To handle the borders of a Bitmap i use the variable BorderDiff.
In case of a borderpixel the pixelarray will be mirrored to the "illegal" coordinates}
if ((Row<= Diameter) AND (Horzline<0)) OR((Row>= SrcBitmap.Height-1-Diameter) AND (Horzline>0))
then BorderDiffY:=-1 ELSE BorderDiffY:=1;
for VertLine:=MinCol to MaxCol do
begin
if ((Col<= Diameter) AND (Vertline<0)) OR ((Col>= SrcBitmap.Width-1-Diameter) AND (Vertline>0))
then BorderDiffX:=-1 ELSE
BorderDiffX:=1;
lLightness[Horzline+3,Vertline+3]:=RGBLightness(SourceRows[Row+(HorzLine*BorderDiffY)][Col+(VertLine*BorderDiffX)]);
end;
end;
mx:=0;my:=0;
Min:=0;Max:=255;Medium:=lLightness[3,3];
for k:=MinRow to MaxRow do
begin
for i:=MinCol to MaxCol do
begin
m:=lLightness[k+3][i+3];
CASE StaticFilterType of
sfMedian:begin
if (m>Min) AND (m<Medium) then
begin
Min:=m
end;// ELSE
if (m<Max) AND (m>Medium) then
begin
Max:=m;
end;
if (m>=Min) AND (m<=Max) then
begin
Medium:=m;
mx:=k;my:=i;
end ;//ELSE
end;
sfMax: begin
if m>Min then begin
Min:=m;
mx:=k;my:=i;
end;
end;
sfMin: begin
if m<Max then begin
Max:=m;
mx:=k;my:=i;
end;
end;
end;
end;
end;
if ((Row<= Diameter) AND (mx<0)) OR((Row>= SrcBitmap.Height-1-Diameter) AND (mx>0))
then BorderDiffY:=-1 ELSE BorderDiffY:=1;
if ((Col<= Diameter) AND (my<0)) OR ((Col>= SrcBitmap.Width-1-Diameter) AND (my>0))
then BorderDiffX:=-1 ELSE
BorderDiffX:=1;
if b then TargetRow[Col].rgbtBlue :=SourceRows[Row+(mx*BorderDiffY)][Col+(my*BorderDiffX)].rgbtBlue;
if r then TargetRow[Col].rgbtRed :=SourceRows[Row+(mx*BorderDiffY)][Col+(my*BorderDiffX)].rgbtRed;
if g then TargetRow[Col].rgbtGreen :=SourceRows[Row+(mx*BorderDiffY)][Col+(my*BorderDiffX)].rgbtGreen;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Apply linear filter to Bitmap (RGB,HSV,HSL)
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Filter : Filter (see TGraphicFilter at the top of this unit)
// ColorSpace : Which colorspase should be used (csRGB,csHSV,csHSL)
// Channel 1-3 : Apply filter to Channel 1 -3
// csRGB R:Channel1 G:Channel 2 B: Channel 3
// csHSV H:Channel1 S:Channel 2 V: Channel 3
// csHSL H:Channel1 S:Channel 2 L: Channel 3
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectLinearFilter(SrcBitmap,DestBitmap:TBitmap;Filter:TGraphicFilter;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
row,col :Integer;
i,mxCount :Integer;
HorzLine,VertLine :Integer;
MaxCol,MaxRow :Integer;
MinCol,MinRow :Integer;
TargetRow :pRGBArray;
Val1,Val2,Val3 :array[0..6] of Integer;
Val1Sum,Val2Sum,Val3Sum :Integer;
h1,s1,vl1 :Integer;
hsv :THSVTriple;
hsl :THSLTriple;
SourceRows :PPRows;
BorderDiffX,BorderDiffY :Integer;
Intensity,Intensity2 :Integer;
begin
if (@Filter=nil) OR (Filter.Divisor=0) OR (Filter.FilterType<>ftLinear) then
begin
DestBitmap.Assign(SrcBitmap);
Exit;
end;
mxCount:=1;
CASE Filter.MatrixSize of
mx3:mxCount:=1;
mx5:mxCount:=2;
mx7:mxCount:=3;
end;
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
Val1Sum:=0;
Val2Sum:=0;
Val3Sum:=0;
MinRow:=-mxCount;
MaxRow:=mxCount;
MinCol:=-mxCount;
Maxcol:=mxCount;
for i:= MinRow to MaxRow do
begin
if Channel1 then Val1[i+3]:=0;
if Channel2 then Val2[i+3]:=0;
if Channel3 then Val3[i+3]:=0;
end;
for HorzLine:=MinRow to MaxRow do
begin
{to handle the borders of a Bitmap i use the variable BorderDiff.
In case of a borderpixel the pixelarray will be mirrored to the "illegal" coordinates}
if ((Row<= mxCount) AND (Horzline<0)) OR((Row>= SrcBitmap.Height-1-mxCount) AND (Horzline>0))
then BorderDiffY:=-1 ELSE BorderDiffY:=1;
for VertLine:=MinCol to MaxCol do
begin
if ((Col<= mxCount) AND (Vertline<0)) OR ((Col>= SrcBitmap.Width-1-mxCount) AND (Vertline>0))
then BorderDiffX:=-1 ELSE
BorderDiffX:=1;
CASE ColorSpace of
csRGB:begin
if Channel1 then Val1[HorzLine+3]:=Val1[HorzLine+3]+(SourceRows[Row+HorzLine*BorderDiffY][Col+VertLine*BorderDiffX].rgbtRed*Filter.Matrix[HorzLine+3,VertLine+3]);
if Channel2 then Val2[HorzLine+3]:=Val2[HorzLine+3]+(SourceRows[Row+HorzLine*BorderDiffY][Col+VertLine*BorderDiffX].rgbtGreen*Filter.Matrix[HorzLine+3,VertLine+3]);
if Channel3 then Val3[Horzline+3]:=Val3[HorzLine+3]+(SourceRows[Row+HorzLine*BorderDiffY][Col+VertLine*BorderDiffX].rgbtBlue*Filter.Matrix[HorzLine+3,VertLine+3]);
end;
csHSV,csHSL:begin
case ColorSpace of
csHSV:begin
RGBtoHSV(SourceRows[Row+HorzLine*BorderDiffY][Col+VertLine*BorderDiffX],hsv);
if Channel1 then Val1[HorzLine+3]:=Val1[HorzLine+3]+(hsv.hsvHue*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val1[HorzLine+3]:=hsv.hsvHue;
if Channel2 then Val2[HorzLine+3]:=Val2[HorzLine+3]+(hsv.hsvSaturation*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val2[HorzLine+3]:=hsv.hsvSaturation;
if Channel3 then Val3[Horzline+3]:=Val3[HorzLine+3]+(hsv.hsvValue*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val3[HorzLine+3]:=hsv.hsvValue;
end;
csHSL:begin
RGBtoHSL(SourceRows[Row+HorzLine*BorderDiffY][Col+VertLine*BorderDiffX],hsl);
if Channel1 then Val1[HorzLine+3]:=Val1[HorzLine+3]+(hsl.hslHue*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val1[HorzLine+3]:=hsl.hslHue;
if Channel2 then Val2[HorzLine+3]:=Val2[HorzLine+3]+(hsl.hslSaturation*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val2[HorzLine+3]:=hsl.hslSaturation;
if Channel3 then Val3[Horzline+3]:=Val3[HorzLine+3]+(hsl.hslLightness*Filter.Matrix[HorzLine+3,VertLine+3])
ELSE Val3[HorzLine+3]:=hsl.hslLightness;
end;
end;
end;
end;
end;
end;
for i:=MinRow to MaxRow do
begin
if Channel1 then Val1Sum:=Val1Sum+Val1[i+3] else Val1Sum:=Val1[3];
if Channel2 then Val2Sum:=Val2Sum+Val2[i+3] else Val2Sum:=Val2[3];
if Channel3 then Val3Sum:=Val3Sum+Val3[i+3] else Val3Sum:=Val3[3];
end;
CASE ColorSpace of
csRGB:begin
if Channel1 then TargetRow[Col].rgbtRed := TrimReal(0,255,(Val1Sum*(1/Filter.Divisor))+Filter.Bias)
ELSE TargetRow[Col].rgbtRed:=SourceRows[Row][Col].rgbtRed;
if Channel2 then TargetRow[Col].rgbtGreen :=TrimReal(0,255,(Val2Sum*(1/Filter.Divisor))+Filter.Bias)
ELSE TargetRow[Col].rgbtGreen:=SourceRows[Row][Col].rgbtGreen;
if Channel3 then TargetRow[Col].rgbtBlue :=TrimReal(0,255,(Val3Sum*(1/Filter.Divisor))+Filter.Bias)
ELSE TargetRow[Col].rgbtBlue:=SourceRows[Row][Col].rgbtBlue;
end;
csHSV:begin
HSV.hsvHue:= LoopReal(0,359,((1/Filter.Divisor)*Val1Sum)+Filter.Bias);
HSV.hsvSaturation:= TrimReal(0,255,((1/Filter.Divisor)*Val2Sum)+Filter.Bias);
HSV.hsvValue:= TrimReal(0,255,((1/Filter.Divisor)*Val3Sum)+Filter.Bias);
HSVToRGB(HSV,TargetRow[Col]);
end;
csHSL:begin
HSL.hslHue:= LoopReal(0,359,((1/Filter.Divisor)*Val1Sum)+Filter.Bias);
HSL.hslSaturation:= TrimReal(0,255,((1/Filter.Divisor)*Val2Sum)+Filter.Bias);
HSL.hslLightness:= TrimReal(0,255,((1/Filter.Divisor)*Val3Sum)+Filter.Bias);
HSLToRGB(HSL,TargetRow[Col]);
end;
end;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Apply multi-pass filter to Bitmap (RGB-Model)
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// MultiPassFilter : MultiPassFilter (see TMultiPassGraphicFilter at the top of this unit)
// R,G,B : Apply filter to R,G,B Planes (Boolean)
// Passes : Nr of filters to be applied
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectMultiPass(SrcBitmap,DestBitmap:TBitmap;MultiPassFilter:TMultiPassGraphicFilter;Passes:Integer;ColorSpace:TColorSpace;Channel1,Channel2,Channel3:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var Bmp1,Bmp2,Bmp3:TBitmap;
procedure ClearBitmap(Bitmap:TBitmap);
begin
Bitmap.Canvas.Brush.Color:=clWhite;
Bitmap.Canvas.FillRect(Rect(0,0,Bitmap.Width,Bitmap.Height));
end;
begin
if not (passes in [1..4]) OR (MultiPassFilter.FilterType<>ftMultiPass) then exit;
SetBitmapsEql(SrcBitmap,DestBitmap);
Bmp1:=TBitmap.Create;
Bmp2:=TBitmap.Create;
Bmp3:=TBitmap.Create;
Bmp1.PixelFormat:=pf24Bit;
Bmp2.PixelFormat:=pf24Bit;
Bmp3.PixelFormat:=pf24Bit;
Bmp1.Assign(SrcBitmap);
try
if Passes>=2 then
begin
EffectFilter(Bmp1,Bmp2,MultiPassFilter.Filters[1]^,mxDefault,ColorSpace,Channel1,Channel2,Channel3,EffectCallBack);
EffectFilter(Bmp2,Bmp3,MultiPassFilter.Filters[2]^,mxDefault,ColorSpace,Channel1,Channel2,Channel3,EffectCallBack);
ClearBitmap(Bmp1);
if MultiPassFilter.Functions[1]<>gaNone then EffectArithmetic(bmp2,bmp3,bmp1,MultiPassFilter.Functions[1],EffectCallBack)
ELSE Bmp1.Assign(Bmp3);
ClearBitmap(Bmp2);
ClearBitmap(Bmp3);
if Passes>=3 then
begin
EffectFilter(Bmp1,Bmp2,MultiPassFilter.Filters[3]^,mxDefault,ColorSpace,Channel1,Channel2,Channel3,EffectCallBack);
if MultiPassFilter.Functions[2]<>gaNone then
begin
EffectArithmetic(bmp1,bmp2,bmp3,MultiPassFilter.Functions[2],EffectCallBack);
ClearBitmap(Bmp1);
Bmp1.Assign(Bmp3);
end ELSE
begin
ClearBitmap(Bmp1);
Bmp1.Assign(Bmp2);
end;
ClearBitmap(Bmp3);
ClearBitmap(Bmp2);
if Passes = 4 then
begin
EffectFilter(Bmp1,Bmp2,MultiPassFilter.Filters[4]^,mxDefault,ColorSpace,Channel1,Channel2,Channel3,EffectCallBack);
if MultiPassFilter.Functions[3]<>gaNone then
begin
EffectArithmetic(bmp1,bmp2,bmp3,MultiPassFilter.Functions[3],EffectCallBack);
ClearBitmap(Bmp1);
Bmp1.Assign(Bmp3);
end ELSE
begin
ClearBitmap(Bmp1);
Bmp1.Assign(Bmp2);
end;
ClearBitmap(Bmp3);
ClearBitmap(Bmp2);
end;
end;
end;
DestBitmap.Assign(Bmp1);
finally
Bmp1.Free;
Bmp2.Free;
Bmp3.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// Sinus effect
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// SinusAmpVer : Amplitude vertical
// VertDelta : Delta vertical
// SinusAmpHorz : Amplitude horizontal
// HorzDleta : Delta horizontal
// VertStart : Vertical start
// VertStart : Vertical start
// R,G,B : Apply antialias to R,G,B Planes (Boolean)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectSinus(SrcBitmap,DestBitmap:TBitmap;SinusAmpVert,VertDelta,SinusAmpHorz,HorzDelta,
VertStart,HorzStart:Integer;
ChngVertAtAnyCol:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
Row,Col,s,ds,t,dt :Integer;
TargetRow :pRGBArray;
SourceRows :PPRows;
begin
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
dt:=HorzStart;
if VertDelta=0 then VertDelta:=1;
if HorzDelta=0 then HorzDelta:=1;
SrcBitmap.PixelFormat:=pf24Bit;
DestBitmap.PixelFormat:=pf24Bit;
DestBitmap.Width:=SrcBitmap.Width;
DestBitmap.Height:=SrcBitmap.Height;
for Row:= 0 to SrcBitmap.Height - 1 do
SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if not ChngVertAtAnyCol then if dt/HorzDelta<360 then inc(dt,1) else dt:=0;
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow := DestBitmap.Scanline[Row];
ds:=VertStart;
for Col := 0 to SrcBitmap.Width - 1 do
begin
s:=Round(SinusAmpVert*Sin(ds / VertDelta));
if ds/VertDelta<360 then inc(ds,1) else ds:=0;
if ChngVertAtAnyCol then if dt/HorzDelta<360 then inc(dt,1) else dt:=0;
if (Row+s<0) or (Row+s> SrcBitmap.Height - 1 )then s:=0;
t:=Round(SinusAmpHorz*Sin(dt / HorzDelta));
if (Col+t<0) or (Col+t> SrcBitmap.Width - 1 )then t:=0;
TargetRow[Col] := SourceRows[Row+S][Col+T];
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Spray effect
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Intensity
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectSpray(SrcBitmap,DestBitmap:TBitmap;Value:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var
TargetRow :pRGBArray;
SourceRows :PPRows;
Row,Col,fCol,fRow,f :Integer;
begin
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
try
SetBitmapsEql(SrcBitmap,DestBitmap);
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/SrcBitmap.Height)*100));
TargetRow:=DestBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do begin
f:=Random(Value);
fCol:=Col+f-Random(f*2);
fRow:=Row+f-Random(f*2);
if(fCOl>-1)and(fCol<SrcBitmap.Width-1)and(fRow>-1)and(fRow<SrcBitmap.Height-1)then
begin
TargetRow[Col].rgbtRed:=SourceRows[fRow][fCol].rgbtRed;
TargetRow[Col].rgbtBlue:=SourceRows[fRow][fCol].rgbtBlue;
TargetRow[Col].rgbtGreen:=SourceRows[fRow][fCol].rgbtGreen;
end;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
// -----------------------------------------------------------------------------
//
// Add noise
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// MonoNoise : Should noisevalue calculated for each plane or not
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectAddNoise(SrcBitmap,DestBitmap:TBitmap;Value:Integer;MonoNoise:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
TargetRow :pRGBArray;
SourceRow :pRGBArray;
Row,Col,f :Integer;
function Calculate(V:Integer):Integer;
begin
result:=Random(Value)-(Value shr 1);
end;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((Row/TBitmap(@SrcBitmap).Height)*100));
TargetRow:=DestBitmap.ScanLine[Row];
SourceRow:=SrcBitmap.ScanLine[Row];
for Col:=0 to DestBitmap.Width-1 do begin
f:=Calculate(Value);
TargetRow[Col].rgbtRed:=TrimInt(0,255,SourceRow[Col].rgbtRed+f);
if (not MonoNoise) then f:=Calculate(Value);
TargetRow[Col].rgbtBlue:=TrimInt(0,255,SourceRow[Col].rgbtBlue+f);
if (not MonoNoise) then f:=Calculate(Value);
TargetRow[Col].rgbtGreen:=TrimInt(0,255,SourceRow[Col].rgbtGreen+f);
end;
end;
end;
// -----------------------------------------------------------------------------
//
// Anti-aliasing
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// R,G,B : Apply antialias to R,G,B Planes (Boolean)
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectAntiAlias(SrcBitmap,DestBitmap:TBitmap;R,G,B:Boolean;const EffectCallBack:TEffectCallBack);stdcall;
var
SourceRows :PPRows;
TargetRow :pRGBArray;
nbhood :array[0..3] of TRGBTriple;
rr,gg,bb :Integer;
Row,Col,i :Integer;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
TargetRow:=DestBitmap.Scanline[Row];
for Col := 0 to SrcBitmap.Width - 1 do
begin
if Col>0 then nbhood[0]:=SourceRows[Row][Col-1] else nbhood[0]:=SourceRows[Row][Col+1];
if Col<SrcBitmap.Width-1 then nbhood[1]:=SourceRows[Row][Col+1] else nbhood[1]:=SourceRows[Row][Col-1];
if Row>0 then nbhood[2]:=SourceRows[Row-1][Col] else nbhood[2]:=SourceRows[Row+1][Col];
if Row<SrcBitmap.Height-1 then nbhood[3]:=SourceRows[Row+1][Col] else nbhood[3]:=SourceRows[Row-1][Col];
rr:=0;gg:=0;bb:=0;
for i:=0 to 3 do
begin
rr:=rr+nbhood[i].rgbtRed;
gg:=gg+nbhood[i].rgbtGreen;
bb:=bb+nbhood[i].rgbtBlue;
end;
rr:=rr div 4;
gg:=gg div 4;
bb:=bb div 4;
if b then TargetRow[Col].rgbtBlue := bb;
if r then TargetRow[Col].rgbtRed := rr;
if g then TargetRow[Col].rgbtGreen := gg;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure LoadLinearFilterFromFile(FileName:PChar;var Filter:TGraphicFilter);stdcall;
var Stream:TFileStream;
header: Array [0..5] of Char;
begin
Stream:=TFileStream.Create(FileNAme,fmOpenRead);
try
ZeroMemory(PChar(@header),sizeof(header));
Stream.Read(header,4);
if header<>'fxlf' then raise EGraphicEffects.Create('Not a valid linear filter file') else
begin
Stream.Read(Filter,SizeOf(TGraphicFilter));
end;
finally
Stream.Free;
end;
end;
procedure SaveLinearFilterToFile(FileName:PChar;const Filter:TGraphicFilter);stdcall;
var stream:TFileStream;
const c ='Created by pView (c) 1999 by A.Moser';
begin
Stream:=TFileStream.Create(FileNAme,fmCreate);
try
Stream.Write('fxlf',4);
Stream.Write(Filter,SizeOf(TGraphicFilter));
Stream.Write(c,Length(c));
finally
Stream.Free;
end;
end;
procedure LoadMultiPassFilterFromFile(FileName:PChar;var Filter:TMultiPassGraphicFilter);stdcall;
var Stream:TFileStream;
header: Array [0..5] of Char;
begin
Stream:=TFileStream.Create(FileNAme,fmOpenRead);
try
ZeroMemory(PChar(@header),sizeof(header));
Stream.Read(header,4);
if header<>'fxmf' then raise EGraphicEffects.Create('Not a valid linear filter file') else
begin
Stream.Read(Filter,SizeOf(TMultiPassGraphicFilter));
end;
finally
Stream.Free;
end;
end;
procedure SaveMultipassFilterToFile(FileName:PChar;const Filter:TMultiPassGraphicFilter);stdcall;
var stream:TFileStream;
const c ='Created by pView (c) 1999 by A.Moser';
begin
Stream:=TFileStream.Create(FileNAme,fmCreate);
try
Stream.Write('fxmf',4);
Stream.Write(Filter,SizeOf(TMultiPassGraphicFilter));
Stream.Write(c,Length(c));
finally
Stream.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// Stretch
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
//
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
procedure EffectStretch(SrcBitmap,DestBitmap:TBitmap;Low,High:Integer;const EffectCallBack:TEffectCallBack);stdcall;
var
SourceRows :PPRows;
TargetRow :pRGBArray;
Row,Col :Integer;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
TargetRow:=DestBitmap.Scanline[Row];
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
for Col := 0 to SrcBitmap.Width - 1 do
begin
if RGBIntensity(SourceRows[Row][Col])<=Low then
begin
TargetRow[Col].rgbtBlue := 0;
TargetRow[Col].rgbtRed := 0;
TargetRow[Col].rgbtGreen := 0;
end
else
if RGBIntensity(SourceRows[Row][Col])>=High then
begin
TargetRow[Col].rgbtBlue := 255;
TargetRow[Col].rgbtRed := 255;
TargetRow[Col].rgbtGreen := 255;
end
else
TargetRow[Col]:=SourceRows[Row][Col];
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure EffectGamma(SrcBitmap,DestBitmap:TBitmap;Gamma:Double;const EffectCallBack:TEffectCallBack);stdcall;
// -----------------------------------------------------------------------------
//
// Gamma correction
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Gamma value
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
var
SourceRows :PPRows;
TargetRow :pRGBArray;
Row,Col,i :Integer;
GammaArray :Array [0..255] of Byte;
begin
for i:=0 to 255 do
GammaArray[i]:=IntGamma(Gamma,i);
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row := 0 to SrcBitmap.Height - 1 do
begin
TargetRow:=DestBitmap.Scanline[Row];
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
for Col := 0 to SrcBitmap.Width - 1 do
begin
TargetRow[Col].rgbtBlue := GammaArray[SourceRows[Row][Col].rgbtBlue];
TargetRow[Col].rgbtGreen := GammaArray[SourceRows[Row][Col].rgbtGreen];
TargetRow[Col].rgbtRed := GammaArray[SourceRows[Row][Col].rgbtRed];
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure EffectEllipse(SrcBitmap,DestBitmap:TBitmap;const EffectCallBack:TEffectCallBack);stdcall;
// -----------------------------------------------------------------------------
//
// Ellipse
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
var
x, y, x1, y1:Integer;
fx, fy, xmid, ymid, ar:double;
SourceRows :PPRows;
TargetRow :pRGBArray;
Row :Integer;
function ComputePixel(x, y:double;var x1,y1:double):Integer; //float &x1, float &y1)
var
r, nn : double;
begin
if (x=0) and (y=0) then
begin
x1 := x;
y1 := y;
result:=1;
end
else
begin
nn := sqrt(x*x*0.5 + y*y);
if (abs(x) > abs(y)) then r:=abs(nn/x) else r:=abs(nn/y);
x1 := (r*x);
y1 := (r*y);
result:= 1;
end;
end;
begin
xmid := SrcBitmap.Width /2.0;
ymid := SrcBitmap.Height/2.0;
ar := SrcBitmap.Height/SrcBitmap.Width ;
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
Row:=0;
for y:=0 to DestBitmap.Height -1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
TargetRow:=DestBitmap.Scanline[y];
for x:=0 to DestBitmap.Width-1 do
begin
ComputePixel(ar*(x-xmid), y-ymid, fx, fy);
x1 := Round(xmid+fx/ar);
y1 := Round(ymid+fy);
if (y1>0) and (y1< SrcBitmap.Height-1) and
(x1>0) and (x1< SrcBitmap.Width-1) then
TargetRow[x]:=SourceRows[y1][x1]
else
begin
TargetRow[x].rgbtBlue := 0;
TargetRow[x].rgbtGreen := 0;
TargetRow[x].rgbtRed := 0;
end;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure EffectMosaic(SrcBitmap,DestBitmap:TBitmap;Width,Height:Integer;const EffectCallBack:TEffectCallBack);stdcall;
// -----------------------------------------------------------------------------
//
// Mosaic effect
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Width,Height : Dimension of blocks
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
var
SourceRows :PPRows;
TargetRow :pRGBArray;
Row,Col :Integer;
source_row,source_col:Integer;
inc_x,inc_y,
half_x, half_y: Integer;
begin
if(Width<1) or (Height<1) then Exit;
half_x:=(Width shr 1)+(Width and 1);
half_y:=(Height shr 1)+(Height and 1);
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
source_Row:=half_y;
inc_y:=0;
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
source_Col:=half_x;
inc_x:=0;
TargetRow:=DestBitmap.Scanline[Row];
for Col:=0 to DestBitmap.Width-1 do
begin
TargetRow[Col]:=SourceRows[source_row][source_col];
inc(inc_x);
if inc_x>=Width then
begin
source_col:=source_col+Width;
if source_col>SrcBitmap.Width-1 then source_col:=SrcBitmap.Width-1;
inc_x:=0;
end;
end;
// increment the position in source_bitmap;
inc(inc_y);
if inc_y>=Height then
begin
source_row:=source_row+Height;
if source_row>SrcBitmap.Height-1 then source_row:=SrcBitmap.Height-1;
inc_y:=0;
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure EffectCircleAround(SrcBitmap,DestBitmap:TBitmap;Value:Integer;const EffectCallBack:TEffectCallBack);stdcall;
// -----------------------------------------------------------------------------
//
// Picture distortion
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Amount
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
var
SourceRows :PPRows;
TargetRow :pRGBArray;
Row,Col :Integer;
half_x, half_y: Integer;
max_x,max_y:Double;
dx,dy,r:Double;
dsx,dsy:Double;
sx,sy:Integer;
theta:double;
begin
half_x:=SrcBitmap.Width div 2;
half_y:=SrcBitmap.Height div 2;
dx:=SrcBitmap.Width-1;
dy:=SrcBitmap.Height-1;
r:=sqrt(dx*dx + dy*dy);
if r>=SrcBitmap.Width then max_x:=SrcBitmap.Width-1 else max_x:=r;
if r>=SrcBitmap.Height then max_y:=SrcBitmap.Height-1 else max_y:=r;
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row:=0 to Round(max_y) do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
TargetRow:=DestBitmap.Scanline[Row];
for Col:=0 to Round(max_x) do
begin
dx:=Col-half_x;
dy:=Row-half_y;
r:=sqrt(dx*dx+dy*dy);
if r=0 then
begin
dsx:=0;
dsy:=0;
end else
begin
if Value=0 then Value:=1;
theta:=xArcTan2(dx,dy)-r/Value - (-(Pi / 2));
dsx:=r* cos(theta);
dsy:=r* sin(theta);
end;
dsx:=dsx+ half_x;
dsy:=dsy+ half_y;
sx:=Trunc(dsx);
sy:=Trunc(dsy);
if sy>=SrcBitmap.Height then sy:= SrcBitmap.Height-1;
if sx>=SrcBitmap.Width then sx:= SrcBitmap.Width-1;
if sx<0 then sx:=0;
if sy<0 then sy:=0;
TargetRow[Col]:=SourceRows[sy][sx];
end;
end;
finally
FreeMem(SourceRows);
end;
end;
procedure EffectFishEye(SrcBitmap,DestBitmap:TBitmap;Value:Extended;const EffectCallBack:TEffectCallBack);stdcall;
// -----------------------------------------------------------------------------
//
// FishEye effect
//
// Parameter:
// SrcBitmap : Bitmap to be processed
// DestBitmap : Result
// Value : Amount
// EffectCallBack : CallBack for user interface
//
//
// -----------------------------------------------------------------------------
var
SourceRows :PPRows;
TargetRow :pRGBArray;
Row,Col :Integer;
half_x, half_y: Integer;
dx,dy,radius1,radius2,radiusMax:Double;
dsx,dsy:Double;
sx,sy:Integer;
begin
half_x:=SrcBitmap.Width div 2;
half_y:=SrcBitmap.Height div 2;
radiusMax:= SrcBitmap.Width * Value;
SetBitmapsEql(SrcBitmap,DestBitmap);
GetMem(SourceRows, SrcBitmap.Height * SizeOf(pRGBArray));
try
for Row:= 0 to SrcBitmap.Height - 1 do SourceRows[Row]:=SrcBitmap.Scanline[Row];
for Row:=0 to DestBitmap.Height-1 do
begin
if Assigned(EffectCallBack) then EffectCallBack(0,100,Round((row/SrcBitmap.Height)*100));
TargetRow:=DestBitmap.Scanline[Row];
for Col:=0 to DestBitmap.Width-1 do
begin
dx:=Col-half_x;
dy:=Row-half_y;
radius1:=sqrt(dx*dx+dy*dy);
if radius1=0 then
begin
dsx:=0;
dsy:=0;
end else
begin
if radius1=radiusMax then radius1:=radius1+1;
radius2:=radiusMax / 2 *(1/(1-radius1/radiusMax)-1);
dsx:=dx*radius2 /radius1 +half_x;
dsy:=dy*radius2 /radius1 +half_y;
end;
sx:=Trunc(dsx);
sy:=Trunc(dsy);
// if sy>=SrcBitmap.Height then sy:= SrcBitmap.Height-1;
// if sx>=SrcBitmap.Width then sx:= SrcBitmap.Width-1;
// if sx<0 then sx:=0;
// if sy<0 then sy:=0;
if (sy>=SrcBitmap.Height) or
(sx>=SrcBitmap.Width) or
(sx<0) or
(sy<0) then
begin
TargetRow[Col].rgbtBlue:=0;
TargetRow[Col].rgbtGreen:=0;
TargetRow[Col].rgbtRed:=0;
end
else
TargetRow[Col]:=SourceRows[sy][sx];
end;
end;
finally
FreeMem(SourceRows);
end;
end;
end.
|
unit DMHelper.View.Styles.Colors;
interface
const
COLOR_BACKGROUND = $FF2d2f32;
COLOR_BACKGROUND_TOP = $FF8B0000;
COLOR_BACKGROUND_TOP_SUBMENU = $00fcfaf9;
COLOR_BACKGROUND_MENU = $FF8B0000;
COLOR_BACKGROUND_DESTAK = $FFDC143C;
FONT_COLOR = $FFF8F8FF;
FONT = 'Bookmania';
// COLOR_BACKGROUND = $00322f2d;
// COLOR_BACKGROUND_TOP = $00b48145;
// COLOR_BACKGROUND_MENU = $004a4136;
// COLOR_BACKGROUND_DESTAK = $0082aa47;
// COLOR_FONT = $00FFFFFF;
FONT_H1 = 22;
FONT_H2 = 20;
FONT_H3 = 18;
FONT_H4 = 16;
FONT_H5 = 14;
FONT_H6 = 12;
implementation
end.
|
var
n: integer := 5;
x: array of real := (1, 2, 3, 5, 4);
M, D: real;
function Sum(var x: array of real; f: (integer, real) -> real): real;
begin
var res: real;
for var i := 0 to x.Length - 1 do
begin
res += f(i, x[i]);
end;
result := res;
end;
begin
M := Sum(x, (i, x) -> x * i) / n;
D := sqrt(Sum(x, (i, x) -> sqr(x * i - M)) / (n - 1));
writeln('M: ', M);
writeln('D: ', D);
end. |
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{*******************************************************}
{ Generic SQL Property Editor }
{*******************************************************}
unit WideSqlEdit;
interface
uses Forms, SysUtils,
ActnList, StdCtrls, Controls, Graphics, ExtCtrls, SqlEdit,
// IDEWideStdCtrls,
// IDEWideControls,
WideStrings, Classes;
type
TGetTableNamesProcW = procedure(List: TWideStrings; SystemTables: Boolean) of object;
TGetTableNamesForSchemaProcW = procedure(List: TWideStrings; SchemaName: WideString; SystemTables: Boolean) of object;
TGetFieldNamesProcW = procedure(const TableName: WideString; List: TWideStrings) of Object;
TGetFieldNamesForSchemaProcW = procedure (const TableName: WideString; SchemaName: WideString; List: TWideStrings) of object;
TRequiresQuoteCharProcW = function(const Name: WideString): Boolean of Object;
TWideSQLEditForm = class(TSQLEditForm)
procedure FormShow(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure TableFieldsSplitterCanResize(Sender: TObject; var NewSize: Integer;
var Accept: Boolean);
procedure MetaInfoSQLSplitterCanResize(Sender: TObject;
var NewSize: Integer; var Accept: Boolean);
procedure MetaInfoSQLSplitterMoved(Sender: TObject);
procedure TableListClick(Sender: TObject);
procedure AddTableButtonClick(Sender: TObject);
procedure AddFieldButtonClick(Sender: TObject);
procedure SQLMemoExit(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SQLMemoEnter(Sender: TObject);
procedure FormUpdateActionUpdate(Sender: TObject);
private
CharHeight: Integer;
FQuoteChar: WideString;
SQLCanvas: TControlCanvas;
procedure InsertText(Text: WideString; AddComma: Boolean = True);
procedure DrawCaretPosIndicator;
protected
FStartTable: WideString;
FSchemaName: WideString;
NameRequiresQuoteCharW : TRequiresQuoteCharProcW;
GetTableNamesForSchemaW : TGetTableNamesForSchemaProcW;
GetTableNamesW: TGetTableNamesProcW;
GetFieldNamesW: TGetFieldNamesProcW;
GetFieldNamesForSchemaW: TGetFieldNamesForSchemaProcW;
procedure PopulateTableList;
procedure PopulateFieldList;
property QuoteChar: WideString read FQuoteChar write FQuoteChar;
property StartTable: WideString read FStartTable write FStartTable;
end;
function EditSQL(var SQL: WideString;
AGetTableNames: TGetTableNamesProcW;
AGetFieldNames: TGetFieldNamesProcW;
AStartTblName : WideString = '';
AQuoteChar : WideString = '';
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = Nil): Boolean; overload;
function EditSQL(var SQL: WideString;
AGetTableNamesForSchema: TGetTableNamesForSchemaProcW;
AGetFieldNames: TGetFieldNamesProcW;
AStartTblName : WideString = '';
AQuoteChar : WideString = '';
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = nil;
SchemaName : WideString = ''): Boolean; overload;
function EditSQL(SQL: TWideStrings;
AGetTableNames: TGetTableNamesProcW;
AGetFieldNames: TGetFieldNamesProcW;
AStartTblName : WideString = '';
AQuoteChar : WideString = '';
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = nil): Boolean; overload;
function EditSQLSchema(var SQL: WideString;
AGetTableNamesForSchema: TGetTableNamesForSchemaProcW;
AGetFieldNamesForSchema: TGetFieldNamesForSchemaProcW;
AStartTblName : WideString = '';
AQuoteChar : WideString = '';
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = Nil;
SchemaName : WideString = ''): Boolean; overload;
function DefaultReqQuoteChar( Name: WideString): Boolean;
implementation
uses
//IDEWideGraphics,
WideStrUtils;
{$R *.dfm}
const
SSelect = 'select'; { Do not localize }
SFrom = 'from'; { Do not localize }
function BaseEditSQL(var SQL: WideString;
AGetTableNames: TGetTableNamesProcW;
AGetTableNamesForSchema: TGetTableNamesForSchemaProcW = Nil;
AGetFieldNames: TGetFieldNamesProcW = nil;
AGetFieldNamesForSchema: TGetFieldNamesForSchemaProcW = Nil;
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = nil;
AStartTblName : WideString = '';
AQuoteChar : WideString = '';
ASchemaName : WideString = ''): Boolean; overload;
begin
with TWideSQLEditForm.Create(nil) do
try
GetTableNamesForSchemaW := AGetTableNamesForSchema;
GetTableNamesW := AGetTableNames;
GetFieldNamesForSchemaW := AGetFieldNamesForSchema;
GetFieldNamesW := AGetFieldNames;
QuoteChar := AQuoteChar;
StartTable := AStartTblName;
FSchemaName := ASchemaName;
NameRequiresQuoteCharW := ANeedsQuoteCharFunc;
SQLMemo.Lines.Text := SQL;
Result := ShowModal = mrOK;
if Result then
SQL := SQLMemo.Lines.Text;
finally
Free;
end;
end;
function EditSQL(var SQL: Widestring; AGetTableNamesForSchema: TGetTableNamesForSchemaProcW;
AGetFieldNames: TGetFieldNamesProcW; AStartTblName : Widestring = ''; AQuoteChar : Widestring = '';
ANeedsQuoteCharFunc: TRequiresQuoteCharProcW = nil; SchemaName : Widestring = ''): Boolean; overload;
var
AGTNP: TGetTableNamesProcW;
AGFNFSP: TGetFieldNamesForSchemaPRocW;
begin
AGTNP := nil;
AGFNFSP := nil;
Result := BaseEditSQL(SQL, AGTNP, AGetTableNamesForSchema, AGetFieldNames, AGFNFSP,
ANeedsQuoteCharFunc, AStartTblName, AQuoteChar, SchemaName);
end;
function EditSQL(var SQL: Widestring; AGetTableNames: TGetTableNamesProcW;
AGetFieldNames: TGetFieldNamesProcW; AStartTblName : Widestring = '';
AQuoteChar : Widestring = ''; ANeedsQuoteCharFunc:
TRequiresQuoteCharProcW = nil): Boolean; overload;
var
AGTNFS: TGetTableNamesForSchemaProcW;
AGFNFSP: TGetFieldNamesForSchemaProcW;
begin
AGTNFS := Nil;
AGFNFSP := Nil;
Result := BaseEditSQL(SQL, AGetTableNames, AGTNFS, AGetFieldNames, AGFNFSP,
ANeedsQuoteCharFunc, AStartTblName, AQuoteChar, '');
end;
function EditSQL(SQL: TWideStrings; AGetTableNames: TGetTableNamesProcW;
AGetFieldNames: TGetFieldNamesProcW; AStartTblName : Widestring = '';
AQuoteChar : Widestring = ''; ANeedsQuoteCharFunc:
TRequiresQuoteCharProcW = nil ): Boolean; overload;
var
SQLText: WideString;
begin
SQLText := SQL.Text;
Result := EditSQL(SQLText, AGetTableNames, AGetFieldNames,
AStartTblName, AQuoteChar, ANeedsQuoteCharFunc);
if Result then
SQL.Text := SQLText;
end;
function EditSQLSchema(var SQL: Widestring; AGetTableNamesForSchema: TGetTableNamesForSchemaProcW;
AGetFieldNamesForSchema: TGetFieldNamesForSchemaProcW;
AStartTblName : Widestring = ''; AQuoteChar : Widestring = ''; ANeedsQuoteCharFunc:
TRequiresQuoteCharProcW = Nil; SchemaName : Widestring = ''): Boolean; overload;
var
AGTN: TGetTableNamesProcW;
AGFN: TGetFieldNamesProcW;
begin
AGTN := Nil;
AGFN := Nil;
Result := BaseEditSql(SQL, AGTN, AGetTableNamesForSchema, AGFN,
AGetFieldNamesForSchema, ANeedsQuoteCharFunc,
AStartTblName, AQuoteChar, SchemaName);
end;
procedure TWideSQLEditForm.FormShow(Sender: TObject);
begin
TableList.Sorted := True;
HelpContext := 27271; //hcDADOSQLEdit
SQLCanvas := TControlCanvas.Create;
SQLCanvas.Control := SQLMemo;
CharHeight := SQLCanvas.TextHeight('0');
PopulateTableList;
// FPopulateThread := TPopulateThread.Create(PopulateTableList);
end;
procedure TWideSQLEditForm.FormDestroy(Sender: TObject);
begin
if Assigned(FPopulateThread) then
begin
FPopulateThread.Terminate;
FPopulateThread.WaitFor;
FPopulateThread.Free;
end;
SQLCanvas.Free;
end;
procedure TWideSQLEditForm.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TWideSQLEditForm.PopulateTableList;
var
I: integer;
wList : TWideStringList;
begin
if (@GetTableNamesW = Nil) and (@GetTableNamesForSchemaW = Nil) then Exit;
try
Screen.Cursor := crHourGlass;
wList := TWideStringList.Create;
try
if @GetTableNamesW = Nil then
GetTableNamesForSchemaW(wList, FSchemaName, False)
else
GetTableNamesW(wList, False);
TableList.Items.Assign(wList);
finally
wList.Free;
end;
Screen.Cursor := crDefault;
if FStartTable <> '' then
begin
for I := 0 to TableList.Items.Count -1 do
begin
if WideCompareStr( FStartTable, TableList.Items[I] ) = 0 then
begin
TableList.ItemIndex := I;
TableListClick(nil);
break;
end;
end;
end;
if TerminatePopulateThread then Exit;
if (TableList.Items.Count > 0) and (TableList.ItemIndex = -1) then
begin
TableList.ItemIndex := 0;
TableListClick(nil);
end;
except
Screen.Cursor := crDefault;
end;
end;
procedure TWideSQLEditForm.TableFieldsSplitterCanResize(Sender: TObject;
var NewSize: Integer; var Accept: Boolean);
begin
Accept := (NewSize > 44) and (NewSize < (MetaInfoPanel.Height - 65));
end;
procedure TWideSQLEditForm.MetaInfoSQLSplitterCanResize(Sender: TObject;
var NewSize: Integer; var Accept: Boolean);
begin
Accept := (NewSize > 100) and (NewSize < (ClientWidth - 100));
end;
procedure TWideSQLEditForm.MetaInfoSQLSplitterMoved(Sender: TObject);
begin
SQLLabel.Left := SQLMemo.Left;
end;
procedure TWideSQLEditForm.PopulateFieldList;
var
wList: TWideStringList;
begin
FieldList.Items.Clear;
if (@GetFieldNamesW = nil) and (@GetFieldNamesForSchemaW = nil) then Exit;
try
wList := TWideStringList.Create;
try
if @GetFieldNamesW = Nil then
GetFieldNamesForSchemaW(TableList.Items[TableList.ItemIndex], FSchemaName, wList)
else
GetFieldNamesW(TableList.Items[TableList.ItemIndex], wList);
FieldList.Items.Assign(wList);
finally
wList.Free;
end;
if (FieldList.Items.Count > 0) then
begin
FieldList.Items.Insert(0, '*');
FieldList.Selected[0] := True;
end;
except
end;
end;
procedure TWideSQLEditForm.TableListClick(Sender: TObject);
begin
PopulateFieldList;
end;
procedure TWideSQLEditForm.InsertText(Text: WideString; AddComma: Boolean = True);
var
StartSave: Integer;
S: WideString;
begin
S := SQLMemo.Text;
StartSave := SQLMemo.SelStart;
if (S <> '') and (StartSave > 0) and not InOpSet(S[StartSave], [' ','(']) and
not (Text[1] = ' ') then
begin
if AddComma and (S[StartSave] <> ',') then
Text := ', '+Text else
Text := ' ' + Text;
end;
System.Insert(Text, S, StartSave+1);
SQLMemo.Text := S;
SQLMemo.SelStart := StartSave + Length(Text);
SQLMemo.Update;
DrawCaretPosIndicator;
end;
procedure TWideSQLEditForm.AddTableButtonClick(Sender: TObject);
var
TableName,
SQLText: WideString;
NeedsQuote, Blank: Boolean;
begin
if TableList.ItemIndex > -1 then
begin
SQLText := SQLMemo.Text;
TableName := TableList.Items[TableList.ItemIndex];
if (QuoteChar <>'') and (QuoteChar <> ' ') then
begin
if Assigned(NameRequiresQuoteChar) then
NeedsQuote := NameRequiresQuoteChar(TableName)
else
NeedsQuote := DefaultReqQuoteChar(TableName);
if NeedsQuote then
TableName := QuoteChar + TableName + QuoteChar;
end;
Blank := SQLText = '';
if Blank or (Copy(SQLText, 1, 6) = SSelect) then
InsertText(WideFormat(' %s %s', [SFrom, TableName]), False)
else
InsertText(TableName, False);
if Blank then
begin
SQLMemo.SelStart := 0;
SQLMemo.Update;
InsertText(SSelect+' ', False);
end;
end;
end;
procedure TWideSQLEditForm.AddFieldButtonClick(Sender: TObject);
var
I: Integer;
ColumnName: WideString;
NeedsQuote: Boolean;
begin
if FieldList.ItemIndex > -1 then
begin
{ Help the user and assume this is a select if starting with nothing }
if SQLMemo.Text = '' then
begin
SQLMemo.Text := SSelect;
SQLMemo.SelStart := Length(SQLMemo.Text);
end;
for I := 0 to FieldList.Items.Count - 1 do
if FieldList.Selected[I] then
begin
ColumnName := FieldList.Items[I];
if (ColumnName <> '*') and (QuoteChar <> '') and (QuoteChar <> ' ') then
begin
if Assigned(NameRequiresQuoteChar) then
NeedsQuote := NameRequiresQuoteChar(ColumnName)
else
NeedsQuote := DefaultReqQuoteChar(ColumnName);
if NeedsQuote then
ColumnName := QuoteChar + ColumnName + QuoteChar;
end;
InsertText(ColumnName, (SQLMemo.Text <> SSelect) and (ColumnName <> '*'));
end;
end;
end;
procedure TWideSQLEditForm.SQLMemoExit(Sender: TObject);
begin
DrawCaretPosIndicator;
end;
procedure TWideSQLEditForm.SQLMemoEnter(Sender: TObject);
begin
{ Erase the CaretPos indicator }
SQLMemo.Invalidate;
end;
procedure TWideSQLEditForm.DrawCaretPosIndicator;
var
XPos, YPos: Integer;
begin
with SQLMemo.CaretPos do
begin
YPos := (Y+1)*CharHeight;
XPos := SQLCanvas.TextWidth(Copy(SQLMemo.Lines[Y], 1, X)) - 3;
SQLCanvas.Draw(XPos ,YPos, Image1.Picture.Graphic);
end;
end;
function DefaultReqQuoteChar( Name: WideString): Boolean;
var
p: PWideChar;
begin
p := PWideChar(Name);
Result := False;
repeat
if not InOpSet(p^, ['A'..'Z', '0'..'9', '_']) then
begin
Result := True;
break;
end;
Inc(p)
until p^ = #0;
end;
procedure TWideSQLEditForm.FormUpdateActionUpdate(Sender: TObject);
begin
AddTableButton.Enabled := TableList.Items.Count > 0;
AddFieldButton.Enabled := FieldList.Items.Count > 0;
end;
end.
|
unit Router4D.History;
{$I Router4D.inc}
interface
uses
Classes,
SysUtils,
{$IFDEF HAS_FMX}
FMX.Forms,
FMX.Types,
{$ELSE}
Vcl.Forms,
Vcl.ExtCtrls,
{$ENDIF}
System.Generics.Collections,
Router4D.Interfaces,
Router4D.Props;
type
TCachePersistent = record
FPatch : String;
FisVisible : Boolean;
FSBKey : String;
FPersistentClass : TPersistentClass;
end;
TRouter4DHistory = class
private
FListCache : TObjectDictionary<String, TObject>;
{$IFDEF HAS_FMX}
FListCacheContainer : TObjectDictionary<String, TFMXObject>;
FMainRouter : TFMXObject;
FIndexRouter : TFMXObject;
{$ELSE}
FListCacheContainer : TObjectDictionary<String, TPanel>;
FMainRouter : TPanel;
FIndexRouter : TPanel;
{$ENDIF}
FListCache2 : TDictionary<String, TCachePersistent>;
FInstanteObject : iRouter4DComponent;
FListCacheOrder : TList<String>;
FIndexCache : Integer;
FMaxCacheHistory : Integer;
procedure CreateInstancePersistent( aPath : String);
//procedure CacheKeyNotify(Sender: TObject; const Key: string; Action: TCollectionNotification);
public
constructor Create;
destructor Destroy; override;
{$IFDEF HAS_FMX}
function MainRouter ( aValue : TFMXObject ) : TRouter4DHistory; overload;
function MainRouter : TFMXObject; overload;
function IndexRouter ( aValue : TFMXObject ) : TRouter4DHistory; overload;
function IndexRouter : TFMXObject; overload;
function AddHistoryConteiner ( aKey : String; aObject : TFMXObject) : TRouter4DHistory; overload;
function GetHistoryContainer ( aKey : String ) : TFMXObject;
{$ELSE}
function MainRouter ( aValue : TPanel ) : TRouter4DHistory; overload;
function MainRouter : TPanel; overload;
function IndexRouter ( aValue : TPanel ) : TRouter4DHistory; overload;
function IndexRouter : TPanel; overload;
function AddHistoryConteiner ( aKey : String; aObject : TPanel) : TRouter4DHistory; overload;
function GetHistoryContainer ( aKey : String ) : TPanel;
{$ENDIF}
function AddHistory ( aKey : String; aObject : TObject ) : iRouter4DComponent; overload;
function AddHistory ( aKey : String; aObject : TPersistentClass ) : iRouter4DComponent; overload;
function AddHistory ( aKey : String; aObject : TPersistentClass; aSBKey : String; isVisible : Boolean ) : iRouter4DComponent; overload;
function RemoveHistory ( aKey : String ) : TRouter4DHistory;
function GetHistory ( aKey : String ) : iRouter4DComponent;
function RoutersList : TDictionary<String, TObject>;
function RoutersListPersistent : TDictionary<String, TCachePersistent>;
function InstanteObject : iRouter4DComponent;
function GoBack : String;
function BreadCrumb(aDelimiter: char = '/') : String;
function addCacheHistory(aKey : String) : TRouter4DHistory;
function IndexCache : Integer;
end;
var
Router4DHistory : TRouter4DHistory;
implementation
{ TRouter4DHistory }
{$IFDEF HAS_FMX}
function TRouter4DHistory.MainRouter(aValue: TFMXObject): TRouter4DHistory;
begin
Result := Self;
FMainRouter := aValue;
end;
function TRouter4DHistory.MainRouter: TFMXObject;
begin
Result := FMainRouter;
end;
function TRouter4DHistory.IndexRouter(aValue: TFMXObject): TRouter4DHistory;
begin
Result := Self;
FIndexRouter := aValue;
end;
function TRouter4DHistory.IndexRouter: TFMXObject;
begin
Result := FIndexRouter;
end;
function TRouter4DHistory.AddHistoryConteiner( aKey : String; aObject : TFMXObject) : TRouter4DHistory;
var
auxObject : TFMXObject;
begin
Result := Self;
if not FListCacheContainer.TryGetValue(aKey, auxObject) then
FListCacheContainer.Add(aKey, aObject);
end;
function TRouter4DHistory.GetHistoryContainer(aKey: String): TFMXObject;
begin
FListCacheContainer.TryGetValue(aKey, Result);
end;
{$ELSE}
function TRouter4DHistory.MainRouter(aValue: TPanel): TRouter4DHistory;
begin
Result := Self;
FMainRouter := aValue;
end;
function TRouter4DHistory.MainRouter: TPanel;
begin
Result := FMainRouter;
end;
function TRouter4DHistory.IndexRouter(aValue: TPanel): TRouter4DHistory;
begin
Result := Self;
FIndexRouter := aValue;
end;
function TRouter4DHistory.IndexRouter: TPanel;
begin
Result := FIndexRouter;
end;
function TRouter4DHistory.AddHistoryConteiner( aKey : String; aObject : TPanel) : TRouter4DHistory;
var
auxObject : TPanel;
begin
Result := Self;
if not FListCacheContainer.TryGetValue(aKey, auxObject) then
FListCacheContainer.Add(aKey, aObject);
end;
function TRouter4DHistory.GetHistoryContainer(aKey: String): TPanel;
begin
FListCacheContainer.TryGetValue(aKey, Result);
end;
{$ENDIF}
function TRouter4DHistory.IndexCache: Integer;
begin
Result := Self.FIndexCache;
end;
function TRouter4DHistory.BreadCrumb(aDelimiter: char): String;
var
i : integer;
begin
Result := '';
if Self.FIndexCache = -1 then
Exit;
Result := Self.FListCacheOrder[Self.FIndexCache];
for i := Self.FIndexCache-1 downto 0 do
begin
Result := Self.FListCacheOrder[i] + ADelimiter + Result;
end;
end;
function TRouter4DHistory.GoBack: String;
begin
if Self.FIndexCache > 0 then
Dec(Self.FIndexCache);
Result := Self.FListCacheOrder[Self.FIndexCache];
end;
function TRouter4DHistory.AddHistory( aKey : String; aObject : TObject ) : iRouter4DComponent;
var
mKey : String;
vObject : TObject;
begin
if not Supports(aObject, iRouter4DComponent, Result) then
raise Exception.Create('Form not Implement iRouter4DelphiComponent Interface');
try GlobalEventBus.RegisterSubscriber(aObject); except end;
if FListCache.Count > 25 then
for mKey in FListCache.Keys do
begin
FListCache.Remove(aKey);
exit;
end;
if not FListCache.TryGetValue(aKey, vObject) then
FListCache.Add(aKey, aObject);
end;
function TRouter4DHistory.AddHistory(aKey: String;
aObject: TPersistentClass): iRouter4DComponent;
var
CachePersistent : TCachePersistent;
vPesersistentClass : TCachePersistent;
begin
CachePersistent.FPatch := aKey;
CachePersistent.FisVisible := True;
CachePersistent.FPersistentClass := aObject;
CachePersistent.FSBKey := 'SBIndex';
if not FListCache2.TryGetValue(aKey, vPesersistentClass) then
FListCache2.Add(aKey, CachePersistent);
end;
function TRouter4DHistory.addCacheHistory(aKey: String): TRouter4DHistory;
var
I: Integer;
begin
Result := Self;
for I := Pred(FListCacheOrder.Count) downto Succ(FIndexCache) do
FListCacheOrder.Delete(I);
if FListCacheOrder.Count > FMaxCacheHistory then
FListCacheOrder.Delete(0);
FListCacheOrder.Add(aKey);
FIndexCache := Pred(FListCacheOrder.Count);
end;
function TRouter4DHistory.AddHistory(aKey: String; aObject: TPersistentClass;
aSBKey : String; isVisible: Boolean): iRouter4DComponent;
var
CachePersistent : TCachePersistent;
vPesersistentClass : TCachePersistent;
begin
CachePersistent.FPatch := aKey;
CachePersistent.FisVisible := isVisible;
CachePersistent.FPersistentClass := aObject;
CachePersistent.FSBKey := aSBKey;
if not FListCache2.TryGetValue(aKey, vPesersistentClass) then
FListCache2.Add(aKey, CachePersistent);
end;
constructor TRouter4DHistory.Create;
begin
FListCache := TObjectDictionary<String, TObject>.Create;
FListCache2 := TDictionary<String, TCachePersistent>.Create;
FListCacheOrder := TList<String>.Create;
FMaxCacheHistory := 10;
{$IFDEF HAS_FMX}
FListCacheContainer := TObjectDictionary<String, TFMXObject>.Create;
{$ELSE}
FListCacheContainer := TObjectDictionary<String, TPanel>.Create;
{$ENDIF}
end;
procedure TRouter4DHistory.CreateInstancePersistent( aPath : String);
var
aPersistentClass : TCachePersistent;
begin
if not FListCache2.TryGetValue(aPath, aPersistentClass) then
raise Exception.Create('Not Register Router ' + aPath);
Self.AddHistory(
aPath,
TComponentClass(
FindClass(
aPersistentClass
.FPersistentClass
.ClassName
)
).Create(Application)
);
end;
destructor TRouter4DHistory.Destroy;
begin
FListCache.Free;
FListCache2.Free;
FListCacheContainer.Free;
FListCacheOrder.Free;
inherited;
end;
function TRouter4DHistory.GetHistory(aKey: String): iRouter4DComponent;
var
aObject : TObject;
begin
if not FListCache.TryGetValue(aKey, aObject) then
Self.CreateInstancePersistent(aKey);
if not Supports(FListCache.Items[aKey], iRouter4DComponent, Result) then
raise Exception.Create('Object not Implements Interface Component');
FInstanteObject := Result;
end;
function TRouter4DHistory.InstanteObject: iRouter4DComponent;
begin
Result := FInstanteObject;
end;
function TRouter4DHistory.RemoveHistory(aKey: String): TRouter4DHistory;
begin
Result := Self;
FListCache.Remove(aKey);
end;
function TRouter4DHistory.RoutersList: TDictionary<String, TObject>;
begin
Result := FListCache;
end;
function TRouter4DHistory.RoutersListPersistent: TDictionary<String, TCachePersistent>;
begin
Result := FListCache2;
end;
initialization
Router4DHistory := TRouter4DHistory.Create;
finalization
Router4DHistory.Free;
end.
|
unit Bank_impl;
{This file was generated on 10 Jun 2000 11:31:17 GMT by version 03.03.03.C1.04}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : Bank_impl }
{derived from IDL module : Bank }
interface
uses
SysUtils,
CORBA,
Bank_i,
Bank_c;
type
TAccount = class;
TAccount = class(TInterfacedObject, Bank_i.Account)
protected
_balance : Single;
public
constructor Create;
function balance : Single;
function get_rates(const myRates : Bank_i.Rates): Single;
end;
implementation
uses ServerMain;
constructor TAccount.Create;
begin
inherited;
_balance := Random * 10000;
end;
function TAccount.balance : Single;
begin
Result := _balance;
Form1.Memo1.Lines.Add('Got a balance call from the client...');
end;
function TAccount.get_rates(const myRates : Bank_i.Rates): Single;
begin
result := myRates.get_interest_rate;
Form1.Memo1.Lines.Add('Interest Rate from Rates arg call = ' +
FormatFloat('##0.00%', result));
end;
initialization
randomize;
end. |
unit MainDM;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TdmMain }
TdmMain = class
private
public
function GetLazarusVersion(const ADir: string): string;
function FindFileLaz(const ADir: string): boolean;
end;
implementation
uses
ResStr;
{ TdmMain }
function TdmMain.GetLazarusVersion(const ADir: string): string;
var
FileName: string;
TmpTSFile: TStringList;
begin
FileName := ADir + PathDelim + 'ide' + PathDelim + 'version.inc';
if FileExists(FileName) then
begin
TmpTSFile := TStringList.Create;
try
TmpTSFile.LoadFromFile(FileName);
Result := StringReplace(TmpTSFile[0], '''', '',
[rfIgnoreCase, rfReplaceAll]);
finally
TmpTSFile.Free;
end;
end
else
Result := rsFileNotFound;
end;
function TdmMain.FindFileLaz(const ADir: string): boolean;
var
FileName: string;
begin
FileName := ADir + PathDelim + 'lazarus';
{$IfDef Windows}
FileName := FileName + '.exe';
{$EndIf}
Result := FileExists(FileName);
end;
end.
|
unit AdminQuery;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, DBGrids, ExtCtrls, DB, DBTables, Buttons,
ADODB, FuncXE,FileCtrl;
type
TFM_Query = class(TForm)
PA_Program: TPanel;
Panel1: TPanel;
DataSource1: TDataSource;
Label1: TLabel;
Label2: TLabel;
ED_content: TEdit;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
Panel7: TPanel;
ED1_queryname: TEdit;
ED_groupname: TEdit;
Panel9: TPanel;
Panel10: TPanel;
Panel2: TPanel;
ED_seqno: TEdit;
ED_queryname: TEdit;
ED_usersql: TMemo;
BT_Find: TButton;
BT_Add: TButton;
BT_Save: TButton;
BT_Del: TButton;
ED1_username: TEdit;
SpeedButton1: TSpeedButton;
ED_username: TEdit;
SpeedButton2: TSpeedButton;
Grid1: TDBGrid;
ADOQuery1: TADOQuery;
ADOSave2: TADOQuery;
BT_FileSave: TButton;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure BT_FindClick(Sender: TObject);
procedure BT_AddClick(Sender: TObject);
procedure BT_SaveClick(Sender: TObject);
procedure Grid1ApplyCellAttribute(Sender: TObject; Field: TField;
Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
procedure Grid1DblClick(Sender: TObject);
procedure BT_DelClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure ED1_querynameKeyPress(Sender: TObject; var Key: Char);
procedure BT_FileSaveClick(Sender: TObject);
function RemoveSpecialChar(sSrc: string): string;
private
{ Private declarations }
FL_Start : Boolean;
FL_Ins : Boolean;
function FL_Get_seqno : Integer;
public
{ Public declarations }
end;
var
FM_Query: TFM_Query;
implementation
uses AUserPopup, AdminMain;
{$R *.dfm}
procedure TFM_Query.FormCreate(Sender: TObject);
begin
FL_Start := True;
ADOQuery1.Connection := ADO_Session;
ADOSave2.Connection := ADO_Session;
end;
procedure TFM_Query.FormPaint(Sender: TObject);
begin
if FL_Start then
begin
FL_Start := False;
Application.ProcessMessages;
end;
end;
function TFM_Query.FL_Get_seqno : Integer;
var
FL_Sql : String;
begin
Result := 0;
FM_Main.StBar_Help.Panels[1].Text := ' 일련번호를 읽고 있는 중입니다...';
FM_Main.StBar_Help.Perform(WM_PAINT,0,0);
with ADOSave2 do
begin
Close;
Sql.Clear;
FL_Sql := 'SELECT /*+ index_desc (A) */ NVL(MAX(seqno),0) + 1 cnt '+
' FROM AQUSERQUERY A '+
' WHERE rownum = 1 '+
' AND userid = ''%s''';
FL_Sql := Format(FL_Sql,[ED_username.Hint]);
Sql.Text := FL_Sql;
Open;
if not Eof then
Result := FieldByName('cnt').AsInteger;
Close;
end;
FM_Main.StBar_Help.Panels[1].Text := '';
end;
procedure TFM_Query.Grid1ApplyCellAttribute(Sender: TObject; Field: TField; Canvas: TCanvas; Rect: TRect; State: TGridDrawState);
begin
if ADOQuery1.FieldByName('username').AsString = '' then
begin
Canvas.Font.Color := clRed;
Canvas.Font.Style := [fsStrikeOut];
end;
end;
procedure TFM_Query.BT_FileSaveClick(Sender: TObject);
var
F : TextFile;
FileName, FilePath : string;
sStr : String;
begin
if SelectDirectory('저장할 폴더위치를 선택하세요.','',sStr) then FilePath := sStr + '\'
else exit;
ADOQuery1.First;
while not ADOQuery1.Recordset.EOF do
begin
FileName := FilePath + RemoveSpecialChar(ADOQuery1.FieldByName('queryname').AsString) + '.sql';
try
try
AssignFile(F, FileName);
Rewrite(F);
Writeln(F, ADOQuery1.FieldByName('usersql').AsString);
except
on E: Exception do ;
end;
finally
CloseFile(F);
ADOQuery1.Next;
end;
end;
end;
//특수문자 제외 추가..
function TFM_Query.RemoveSpecialChar(sSrc: string): string;
var
I: integer;
begin
result :='';
for I:=1 to Length(sSrc) do
if (sSrc[I] in ['!','@','#','$','%','^','&','*','\','/','|','`','''','~']) then result := result + '_'
else result := result + sSrc[I];
end;
procedure TFM_Query.BT_FindClick(Sender: TObject);
var
FL_Sql : String;
begin
with ADOQuery1 do
begin
Close;
Sql.Clear;
FL_Sql := Format('SELECT T1.userid, T2.username, T1.groupname, T1.queryname, T1.content, T1.usersql, T1.seqno '+
' FROM AQUSERQUERY T1, AQUSER T2 '+
' WHERE T1.userid = ''%s'' '+
' AND T1.queryname LIKE ''%s'' '+
' AND T1.userid = T2.userid(+) '+
' ORDER BY T1.groupname, T1.seqno ',
[ED1_username.Hint, '%'+ED1_queryname.Text+'%']);
Sql.Add(FL_Sql);
Open;
end;
end;
procedure TFM_Query.Grid1DblClick(Sender: TObject);
begin
FL_Ins := False;
ED_username.Hint := ADOQuery1.FieldByName('userid').AsString;
ED_username.Text := ADOQuery1.FieldByName('username').AsString;
ED_seqno.Text := ADOQuery1.FieldByName('seqno').AsString;
ED_groupname.Text := ADOQuery1.FieldByName('groupname').AsString;
ED_queryname.Text := ADOQuery1.FieldByName('queryname').AsString;
ED_usersql.Text := ADOQuery1.FieldByName('usersql').AsString;
ED_content.Text := ADOQuery1.FieldByName('content').AsString;
ED_username.Enabled := False;
ED_seqno.Enabled := False;
end;
procedure TFM_Query.SpeedButton1Click(Sender: TObject);
begin
FM_UserPopup := TFM_UserPopup.Create(Self);
Try
FM_UserPopup.ShowModal;
if FM_UserPopup.FUserID = '' then exit;
ED1_username.Hint := FM_UserPopup.FUserID;
ED1_username.Text := FM_UserPopup.FUserName;
Finally
FM_UserPopup.Free;
end;
end;
procedure TFM_Query.SpeedButton2Click(Sender: TObject);
begin
FM_UserPopup := TFM_UserPopup.Create(Self);
Try
FM_UserPopup.ShowModal;
if FM_UserPopup.FUserID = '' then exit;
ED_username.Hint := FM_UserPopup.FUserID;
ED_username.Text := FM_UserPopup.FUserName;
Finally
FM_UserPopup.Free;
end;
end;
procedure TFM_Query.BT_AddClick(Sender: TObject);
var
FL_Key1 : String;
FL_Key2 : String;
begin
FL_Ins := True;
FL_Key1 := ED_username.Hint;
FL_Key2 := ED_username.Text;
ED_username.Enabled := True;
ED_seqno.Enabled := True;
ED_username.Hint := '';
ED_username.Text := '';
ED_groupname.Text := '';
ED_queryname.Text := '';
ED_usersql.Text := '';
ED_content.Text := '';
ED_username.Hint := FL_Key1;
ED_username.Text := FL_Key2;
if Trim(ED_username.Hint) <> '' then
begin
ED_seqno.Text := inttoStr(FL_Get_Seqno);
end;
ED_groupname.SetFocus;
end;
procedure TFM_Query.BT_SaveClick(Sender: TObject);
var
FL_Sql : String;
FStream : TMemoryStream;
begin
if trim(ED_username.Text) = '' then
begin
MessageDlg('사용자명을 입력하세요...',mtInformation,[mbOK],0);
ED_username.SetFocus;
System.Exit;
end;
if trim(ED_queryname.Text) = '' then
begin
MessageDlg('사용자 질의명을 입력하세요...',mtInformation,[mbOK],0);
ED_queryname.SetFocus;
System.Exit;
end;
if trim(ED_usersql.Lines.Text) = '' then
begin
MessageDlg('SQL문장을 입력하세요...',mtInformation,[mbOK],0);
ED_usersql.SetFocus;
System.Exit;
end;
try
FStream := nil;
FStream := TMemoryStream.Create;
ED_usersql.Lines.SaveToStream(FStream);
if FL_Ins then
begin
with ADOSave2 do
begin
Close;
Sql.Clear;
FL_Sql := Format('INSERT INTO AQUSERQUERY '+
' (seqno, userid, groupname, queryname, usersql, content) '+
' VALUES '+
'(%d, ''%s'',''%s'', ''%s'', :pusersql, ''%s'') ',
[StrToInt(ED_seqno.Text), ED_username.Hint, ED_groupname.Text, ED_queryname.Text, ED_content.Text]);
Sql.Text := FL_Sql;
Parameters.ParamByName('pusersql').LoadFromStream(FStream, ftBlob);
EXECSQL;
end;
end
else
begin
with ADOSave2 do
begin
Close;
Sql.Clear;
FL_Sql := Format('UPDATE AQUSERQUERY SET '+
' groupname = ''%s'', '+
' queryname = ''%s'', '+
' usersql = :pusersql,'+
' content = ''%s'' '+
' WHERE userid = ''%s'' '+
' AND seqno = %d ',
[ED_groupname.Text, ED_queryname.Text, ED_content.Text, ED_username.Hint, StrToInt(ED_seqno.Text)]);
Sql.Text := FL_Sql;
Parameters.ParamByName('pusersql').LoadFromStream(FStream, ftBlob);
EXECSQL;
end;
end;
FStream.Free;
FStream := nil;
except on E : EDBEngineError do
begin
MessageDlg('질의 수행중 에러가 발생했습니다...('+E.Message+')',mtInformation,[mbOK],0);
System.Exit;
end;
end;
BT_FindClick(Sender);
MessageDlg('데이타가 저장 되었습니다...',mtInformation,[mbOK],0);
end;
procedure TFM_Query.ED1_querynameKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
BT_FindClick(Sender);
end;
procedure TFM_Query.BT_DelClick(Sender: TObject);
var
FL_Sql : String;
begin
if MessageDlg('데이타를 삭제 하시겠습니까 ?.',mtConfirmation,[mbYES,mbNO],0) = mrNO then
System.Exit;
try
with ADOSave2 do
begin
Close;
Sql.Clear;
FL_Sql := Format('DELETE FROM AQUSERQUERY '+
' WHERE userid = ''%s'' '+
' AND seqno = %d ',
[ED_username.Hint, StrToInt(ED_seqno.Text)]);
Sql.Add(FL_Sql);
EXECSQL;
end;
except on E : EDBEngineError do
begin
MessageDlg('질의 수행중 에러가 발생했습니다...('+E.Message+')',mtInformation,[mbOK],0);
System.Exit;
end;
end;
BT_FindClick(Sender);
MessageDlg('데이타가 삭제 되었습니다...',mtInformation,[mbOK],0);
end;
end.
|
unit UnitTask;
{$mode objfpc}{$H+}
interface
type
Task = record
id : LongInt; // identyfikator
ExecutionTime : LongInt; // czas wykonania
AvailabilityTime : LongInt; // minimalny czas dostępności (algorytm go uzupełni)
CommenceTime : LongInt; // czas faktyczny wykonania (j.w.)
AssignedMachine : LongInt; // przypisana maszyna (j.w.)
GraphPosX : LongInt;
GraphPosY : LongInt;
PrevTasks : array of LongInt; // wymagane taski
NextTasks : array of LongInt; // taski wychodzące
Visited : Boolean; // używane do sprawdzania cyklicznosci
end;
type
TaskDB = record
Content : array of Task;
MachinesCount : LongInt;
HasCycles : Boolean;
end;
type TTasks = array of Task;
type TLongInts = array of LongInt;
function loadDBFromFile(filename : String; cpucount : LongInt) : TaskDB;
function getComputersCount(filename : String) : LongInt;
procedure printDBContent(db : TaskDB);
procedure dropDB(var db : TaskDB);
function applyCPM(var db : TaskDB) : LongInt;
function buildSchedule(var db : TaskDB; maxl : LongInt; cpucount : LongInt) : LongInt;
procedure drawSchedule(db : TaskDB; maxl : LongInt; filename : String);
procedure drawGraph(db : TaskDB; filename : String);
implementation
uses
Classes, SysUtils, Math;
// ========== Utils
function table_min(tab : array of LongInt) : LongInt;
var
i : LongInt;
s : LongInt;
begin
s := tab[0];
for i := 1 to Length(tab)-1 do
if (tab[i] < s) then s := tab[i];
table_min := s;
end;
function table_max(tab : array of LongInt) : LongInt;
var
i : LongInt;
s : LongInt;
begin
s := tab[0];
for i := 1 to Length(tab)-1 do
if (tab[i] > s) then s := tab[i];
table_max := s;
end;
function table_empty(tab : array of LongInt) : Boolean;
var
i : LongInt;
s : Boolean;
begin
s := true;
for i := 0 to Length(tab)-1 do
if (tab[i] <> -1) then s := false;
table_empty := s;
end;
// ========== DB Management
function buildTask(id, execution_time : LongInt) : Task;
var
pom : Task;
begin
pom.id := id;
pom.ExecutionTime := execution_time;
pom.AvailabilityTime := -1;
pom.CommenceTime := -1;
pom.AssignedMachine := -2;
pom.GraphPosX := -1;
pom.GraphPosY := -1;
SetLength(pom.PrevTasks, 0);
SetLength(pom.NextTasks, 0);
pom.Visited := false;
buildTask := pom;
end;
procedure addDependency(var destination : Task; var origin : Task);
var
i, j : LongInt;
begin
i := Length(destination.PrevTasks);
j := Length(origin.NextTasks);
SetLength(destination.PrevTasks, i+1);
SetLength(origin.NextTasks, j+1);
destination.PrevTasks[i] := origin.id;
origin.NextTasks[j] := destination.id;
end;
function getTaskDBAddress(db : TaskDB; id : LongInt) : LongInt;
var
found : Boolean;
index : LongInt;
i : Task;
begin
index := 0;
found := false;
for i in db.Content do
begin
if (i.id = id) then
begin
found := true;
break;
end;
Inc(index);
end;
if not (found) then getTaskDBAddress := -1
else getTaskDBAddress := index;
end;
function getTaskByID(db : TaskDB; id : LongInt) : Task;
begin
getTaskByID := db.Content[getTaskDBAddress(db, id)];
end;
procedure replaceTaskByID(var db : TaskDB; newtask : Task);
begin
db.Content[getTaskDBAddress(db, newtask.id)] := newtask;
end;
function setTasks(filename : String; cpucount : LongInt) : TaskDB;
var
db : TaskDB;
pom : array of Task;
fp : Text;
L : TStrings;
line : String;
i : LongInt;
begin
i := 0;
SetLength(pom, i);
assignfile(fp, filename);
reset(fp);
L := TStringlist.Create;
L.Delimiter := ' ';
L.StrictDelimiter := false;
while not eof(fp) do
begin
readln(fp, line);
L.DelimitedText := line;
if (L[0] = 'add') and (L[1] = 'task') and (L[3] = 'that') and (L[4] = 'lasts') then
begin
SetLength(pom, i+1);
pom[i] := buildTask(StrToInt(L[2]), StrToInt(L[5]));
Inc(i);
end;
end;
L.Free;
closefile(fp);
db.Content := pom;
db.MachinesCount := cpucount;
SetLength(pom, 0);
setTasks := db;
end;
function getComputersCount(filename : String) : LongInt;
var
fp : Text;
L : TStrings;
line : String;
ct : LongInt;
begin
ct := 0;
assignfile(fp, filename);
reset(fp);
L := TStringlist.Create;
L.Delimiter := ' ';
L.StrictDelimiter := false;
while not eof(fp) do
begin
readln(fp, line);
L.DelimitedText := line;
if (L[0] = 'use') and (L[1] = 'unlimited') and (L[2] = 'number') and (L[3] = 'of') and (L[4] = 'computers') then ct := 0;
if (L[0] = 'use') and (L[1] = '1') and (L[2] = 'computer') then ct := 1;
if (L[0] = 'use') and (L[2] = 'computers') then ct := StrToInt(L[1]);
end;
L.Free;
closefile(fp);
getComputersCount := ct;
end;
procedure buildDependencies(var db : TaskDB; filename : String);
var
fp : Text;
L : TStrings;
line : String;
destination : Task;
origin : Task;
begin
assignfile(fp, filename);
reset(fp);
L := TStringlist.Create;
L.Delimiter := ' ';
L.StrictDelimiter := false;
while not eof(fp) do
begin
readln(fp, line);
L.DelimitedText := line;
if (L[0] = 'make') and (L[1] = 'task') and (L[3] = 'dependent') and (L[4] = 'on') and (L[5] = 'task') then
begin
destination := getTaskByID(db, StrToInt(L[2]));
origin := getTaskByID(db, StrToInt(L[6]));
addDependency(destination, origin);
replaceTaskByID(db, destination);
replaceTaskByID(db, origin);
end;
end;
L.Free;
closefile(fp);
end;
function allVisited(db : TaskDB) : Boolean;
var
tk : Task;
s : Boolean;
begin
s := true;
for tk in db.Content do
if not (tk.Visited) then s := false;
allVisited := s;
end;
function table_allVisited(db : TTasks) : Boolean;
var
tk : Task;
s : Boolean;
begin
s := true;
for tk in db do
if not (tk.Visited) then s := false;
table_allVisited := s;
end;
function getAllNextTasks(db : TaskDB; tk : Task) : TTasks;
var
pom : TTasks;
i, j : LongInt;
tl : Task;
begin
SetLength(pom, Length(tk.NextTasks));
j := 0;
for i in tk.NextTasks do
begin
tl := getTaskByID(db, i);
pom[j] := tl;
j := j + 1;
end;
getAllNextTasks := pom;
end;
function getAllIDs(db : TaskDB) : TLongInts;
var
pom : TLongInts;
i : Task;
j : LongInt;
begin
SetLength(pom, Length(db.Content));
j := 0;
for i in db.Content do
begin
pom[j] := i.id;
j := j + 1;
end;
getAllIDs := pom;
end;
function getAllPrevTasks(db : TaskDB; tk : Task) : TTasks;
var
pom : TTasks;
i, j : LongInt;
tl : Task;
begin
SetLength(pom, Length(tk.PrevTasks));
j := 0;
for i in tk.PrevTasks do
begin
tl := getTaskByID(db, i);
pom[j] := tl;
j := j + 1;
end;
getAllPrevTasks := pom;
end;
function hasCycles(var db : TaskDB) : Boolean;
var
queue : array of Task;
lcursor : LongInt;
rcursor : LongInt;
i, j, k : LongInt;
index : LongInt;
tk, tl : Task;
tks, tls : TTasks;
answer : Boolean;
begin
SetLength(queue, Length(db.Content));
lcursor := 0;
rcursor := 0;
for i := 0 to Length(db.Content)-1 do
if Length(db.Content[i].PrevTasks) = 0 then
begin
if (rcursor = Length(queue)) then SetLength(queue, rcursor+1);
db.Content[i].Visited := true;
queue[rcursor] := db.Content[i];
Inc(rcursor);
end;
//write('Queue: '); for k := 0 to Length(queue)-1 do write(queue[k].id,' '); writeln();
while (lcursor < rcursor) or (rcursor = Length(db.Content)-1) do
begin
//write('Queue: '); for k := 0 to Length(queue)-1 do write(queue[k].id,' '); writeln();
//writeln(lcursor, ' ', rcursor);
tk := queue[lcursor];
Inc(lcursor);
tks := getAllNextTasks(db, tk);
//write('Next: '); for k := 0 to Length(tks)-1 do write(tks[k].id,' '); writeln();
for tl in tks do
begin
if (table_allVisited(getAllPrevTasks(db, tl))) then
begin
index := getTaskDBAddress(db, tl.id);
if (rcursor = Length(queue)) then SetLength(queue, rcursor+1);
db.Content[index].Visited := true;
queue[rcursor] := db.Content[index];
Inc(rcursor);
end;
end;
end;
answer := not (allVisited(db));
SetLength(queue, 0);
hasCycles := answer;
end;
function loadDBFromFile(filename : String; cpucount : LongInt) : TaskDB;
var
db : TaskDB;
begin
db := setTasks(filename, cpucount);
buildDependencies(db, filename);
if (hasCycles(db)) then
begin
writeln('ERROR: Graph contains cyclic dependencies!');
db.HasCycles := true;
end else begin
db.HasCycles := false;
end;
loadDBFromFile := db;
end;
procedure printDBContent(db : TaskDB);
var
dep, ava : String;
com, ass : String;
tk : Task;
i : LongInt;
begin
for tk in db.Content do
begin
if (Length(tk.PrevTasks) = 0) then
begin
dep := ', is independent';
end else begin
dep := ', is dependent on [';
for i in tk.PrevTasks do dep := dep + ' ' + IntToStr(i);
dep := dep + ' ]'
end;
if (tk.AvailabilityTime = -1) then
begin
ava := '';
end else begin
if (tk.AvailabilityTime = 0) then ava := ' and begins immediately at best'
//if (tk.AvailabilityTime = tk.ExecutionTime) then ava := ' and begins immediately at best'
else ava := ' and begins at ' + IntToStr(tk.AvailabilityTime) + ' at best';
end;
if (tk.CommenceTime = -1) then
begin
com := '';
end else begin
com := ', but in fact it begins at '+IntToStr(tk.CommenceTime);
end;
if (tk.AssignedMachine = -2) then
begin
ass := '';
end else begin
ass := '. This task is assigned to a machine no. '+IntToStr(tk.AssignedMachine);
end;
writeln('The task ', tk.id, ' lasts ', tk.ExecutionTime, dep, ava, com, ass, '.');
end;
end;
procedure dropDB(var db : TaskDB);
begin
SetLength(db.Content, 0);
end;
// ============ CPM and Schedule Building
function findCriticalPath(var db : TaskDB; var tk : Task) : LongInt;
var
i : LongInt;
pom : Task;
tab : array of LongInt;
s : LongInt;
begin
SetLength(tab, Length(tk.PrevTasks));
for i := 0 to Length(tk.PrevTasks)-1 do
begin
pom := getTaskByID(db, tk.PrevTasks[i]);
tab[i] := pom.ExecutionTime + pom.AvailabilityTime;
end;
s := table_max(tab);
SetLength(tab, 0);
findCriticalPath := s;
end;
function applyCPM(var db : TaskDB) : LongInt;
var
i, j : LongInt;
tab : array of LongInt;
maxs : array of LongInt;
begin
SetLength(tab, Length(db.Content));
SetLength(maxs, Length(db.Content));
for i := 0 to Length(db.Content)-1 do tab[i] := db.Content[i].id;
for i in tab do
begin
j := getTaskDBAddress(db, i);
if Length(db.Content[j].PrevTasks) = 0 then
begin
db.Content[j].AvailabilityTime := 0;
maxs[j] := db.Content[j].ExecutionTime;
end else begin
db.Content[j].AvailabilityTime := findCriticalPath(db, db.Content[j]);
maxs[j] := db.Content[j].ExecutionTime + db.Content[j].AvailabilityTime;
end;
end;
applyCPM := table_max(maxs);
end;
// ========== Schedule Generation
function buildSchedule(var db : TaskDB; maxl : LongInt; cpucount : LongInt) : LongInt;
var
sched : array of array of Integer;
i, j : LongInt;
index, jndex : LongInt;
assigned : Boolean;
cursor : LongInt;
usedcpus : LongInt;
s, xsize : LongInt;
expanded : Boolean;
maxs : array of LongInt;
begin
SetLength(sched, 0, 0);
SetLength(maxs, Length(db.Content));
xsize := maxl;
expanded := false;
if (cpucount <= 0) then // whether a count of CPUs is unbounded
begin
//writeln('lots of PCs');
usedcpus := 1;
SetLength(sched, usedcpus, maxl);
for i := 0 to maxl-1 do
sched[usedcpus-1][i] := 0;
//writeln('OK');
//for tk in db.Content do
for index := 1 to Length(db.Content) do
begin
//writeln('OK ', index);
//writeln('CPUs ', usedcpus);
jndex := getTaskDBAddress(db, index);
//writeln('Index: ', jndex);
assigned := false;
cursor := db.Content[jndex].AvailabilityTime;
for i := 0 to usedcpus-1 do
if (sched[i][cursor] = 0) then
begin
for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[i][cursor+j] := 1;
db.Content[jndex].CommenceTime := cursor;
db.Content[jndex].AssignedMachine := i+1;
assigned := true;
break;
end;
if not assigned then
begin
Inc(usedcpus);
SetLength(sched, usedcpus, maxl);
for i := 0 to maxl-1 do
sched[usedcpus-1][i] := 0;
for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[usedcpus-1][cursor+j] := 1;
db.Content[jndex].CommenceTime := cursor;
db.Content[jndex].AssignedMachine := usedcpus;
assigned := true;
end;
end;
db.MachinesCount := usedcpus;
//writeln('Done');
end else begin // or is fixed
SetLength(sched, cpucount, xsize);
for i := 0 to cpucount-1 do
for j := 0 to maxl-1 do
sched[i][j] := 0;
//for index := 1 to Length(db.Content) do
for index in getAllIDs(db) do
begin
//writeln(index);
jndex := getTaskDBAddress(db, index);
assigned := false;
cursor := db.Content[jndex].AvailabilityTime;
repeat
for i := 0 to cpucount-1 do
if (sched[i][cursor] <> 1) then
begin
if (cursor + db.Content[jndex].ExecutionTime + 1 > xsize) then
begin
//write(xsize);
xsize := cursor + db.Content[jndex].ExecutionTime + 1;
SetLength(sched, cpucount, xsize);
//writeln('expands to ', xsize);
expanded := true;
end;
for j := 0 to db.Content[jndex].ExecutionTime-1 do sched[i][cursor+j] := 1;
db.Content[jndex].CommenceTime := cursor;
db.Content[jndex].AssignedMachine := i+1;
assigned := true;
break;
end;
Inc(cursor);
if (cursor = xsize) then break;
until assigned;
end;
end;
SetLength(sched, 0, 0);
if expanded then xsize := xsize - 1;
buildSchedule := xsize;
end;
procedure drawSchedule(db : TaskDB; maxl : LongInt; filename : String);
var
fp : Text;
schedSizeX : LongInt;
schedSizeY : LongInt;
i : LongInt;
CPUCount : LongInt;
tk : Task;
TaskX, TaskY : LongInt;
TaskLength : LongInt;
begin
CPUCount := db.MachinesCount;
schedSizeX := maxl*100 + 200;
schedSizeY := CPUCount*100 + 200;
assignfile(fp, filename);
rewrite(fp);
writeln(fp, '<svg xmlns="http://www.w3.org/2000/svg" width="',schedSizeX,'" height="',schedSizeY,'" viewBox="0 0 ',schedSizeX,' ',schedSizeY,'">');
writeln(fp, '<rect width="',schedSizeX,'" height="',schedSizeY,'" style="fill:rgb(255,255,255);stroke-width:0;stroke:rgb(0,0,0)" />');
//writeln(fp, '<text x="20" y="50" font-family="Verdana" font-size="25" style="font-weight:bold">CPU</text>');
writeln(fp, '<text x="10" y="',CPUCount*100+150,'" font-family="Verdana" font-size="25" style="font-weight:bold">Czas</text>');
for i := 1 to CPUCount do
writeln(fp, '<text x="10" y="',i*100+55,'" font-family="Verdana" font-size="20">CPU ',i,'</text>');
for i := 0 to maxl do
begin
writeln(fp, '<text x="',i*100+100,'" y="',CPUCount*100+150,'" font-family="Verdana" font-size="20">',i,'</text>');
writeln(fp, '<line x1="',i*100+100,'" y1="80" x2="',i*100+100,'" y2="',CPUCount*100+120,'" style="stroke:rgb(0,0,0);stroke-width:1" />');
end;
for tk in db.Content do
begin
TaskX := tk.CommenceTime*100+100;
TaskY := tk.AssignedMachine*100;
TaskLength := tk.ExecutionTime*100;
writeln(fp, '<rect x="',TaskX,'" y="',TaskY,'" width="',TaskLength,'" height="100" style="fill:rgb(128,128,255);stroke-width:2;stroke:rgb(0,0,0)" />');
writeln(fp, '<text x="',TaskX+10,'" y="',TaskY+60,'" font-family="Verdana" font-size="18" fill="white">Task ',tk.id,'</text>');
end;
writeln(fp, '</svg>');
closefile(fp);
writeln('A schedule image has been generated to the file "', filename, '".');
end;
procedure drawGraph(db : TaskDB; filename : String);
var
fp : Text;
schedSizeX : LongInt;
schedSizeY : LongInt;
i : LongInt;
MiddleX : LongInt;
MiddleY : LongInt;
tk, tl : Task;
TaskX, TaskY : LongInt;
atan : Extended;
angle : LongInt;
posX, posY : LongInt;
begin
schedSizeX := 1000;
schedSizeY := 1000;
MiddleX := schedSizeX div 2;
MiddleY := schedSizeY div 2;
for i := 0 to Length(db.Content)-1 do
begin
db.Content[i].GraphPosX := MiddleX - trunc((MiddleX-150)*(cos(i/(Length(db.Content)) *2*pi()+0.01)));
db.Content[i].GraphPosY := MiddleY - trunc((MiddleY-150)*(sin(i/(Length(db.Content)) *2*pi()+0.01)));
end;
assignfile(fp, filename);
rewrite(fp);
writeln(fp, '<svg xmlns="http://www.w3.org/2000/svg" width="',schedSizeX,'" height="',schedSizeY,'" viewBox="0 0 ',schedSizeX,' ',schedSizeY,'">');
writeln(fp, '<rect width="',schedSizeX,'" height="',schedSizeY,'" style="fill:rgb(255,255,255);stroke-width:0;stroke:rgb(0,0,0)" />');
for tk in db.Content do
begin
for i := 0 to Length(tk.PrevTasks)-1 do
begin
tl := getTaskByID(db, tk.PrevTasks[i]);
atan := (1.0 * tk.GraphPosX - tl.GraphPosX)/(1.0 * tk.GraphPosY - tl.GraphPosY);
angle := trunc(radtodeg(arctan(atan))) - 90;
if (angle < 0) then angle := 360 - angle;
writeln(fp, '<line x1="',tk.GraphPosX,'" y1="',tk.GraphPosY,'" x2="',tl.GraphPosX,'" y2="',tl.GraphPosY,'" style="stroke:rgb(0,0,0);stroke-width:2" />');
if (tk.GraphPosY < tl.GraphPosY) then
writeln(fp, '<polygon points="2,7 0,0 11,7 0,14" transform="translate(',tk.GraphPosX+trunc(50*cos(degtorad(angle))),' ',tk.GraphPosY+trunc(50*sin(degtorad(angle))),') rotate(',angle+180,' 0 0) translate(-2 -7)" stroke="black" fill="black" />')
else
writeln(fp, '<polygon points="2,7 0,0 11,7 0,14" transform="translate(',tk.GraphPosX-trunc(50*cos(degtorad(angle))),' ',tk.GraphPosY-trunc(50*sin(degtorad(angle))),') rotate(',angle,' 0 0) translate(-2 -7)" stroke="black" fill="black" />');
end;
end;
for i := 0 to Length(db.Content)-1 do
begin
tk := db.Content[i];
if (i*4 < (Length(db.Content))) or (i*4.0/3 > (Length(db.Content))) then posX := tk.GraphPosX-130
else posX := tk.GraphPosX+30;
if (i*2 < (Length(db.Content))) then posY := tk.GraphPosY-50
else posY := tk.GraphPosY+60;
writeln(fp, '<circle cx="',tk.GraphPosX,'" cy="',tk.GraphPosY,'" r="40" stroke="black" stroke-width="3" fill="#008844" />');
writeln(fp, '<text x="',posX,'" y="',posY,'" font-family="Verdana" font-size="24" fill="black">Task ',tk.id,'</text>');
writeln(fp, '<text x="',tk.GraphPosX-10,'" y="',tk.GraphPosY+10,'" font-family="Verdana" font-size="24" fill="white">',tk.ExecutionTime,'</text>');
end;
writeln(fp, '</svg>');
closefile(fp);
writeln('A graph image has been generated to the file "', filename, '".');
end;
end.
|
program ImaginaryArithmetics;
type
cm = ^complex;
complex = record
re, im : integer;
end;
procedure PrintComplex(A : cm);
begin
writeln('(', A^.re, ',', A^.im, 'i)');
end;
function NewComplex(re, im : integer) : cm;
var
A : cm;
begin
new(A);
A^.re := re;
A^.im := im;
NewComplex := A;
end;
function AddComplex(A, B : cm) : cm;
begin
AddComplex := NewComplex(A^.re+B^.re, A^.im+B^.im);
end;
function MultiplyComplex(A, B : cm) : cm;
begin
MultiplyComplex := NewComplex(A^.re*B^.re-A^.im*B^.im, A^.re*B^.im+A^.im*B^.re);
end;
var
A, B : cm;
begin
A := NewComplex(3, 2);
B := NewComplex(1, 4);
PrintComplex(AddComplex(A,B));
PrintComplex(MultiplyComplex(A,B));
end.
|
unit Pickdate;
interface
uses Windows, Classes, Graphics, Forms, Controls, Buttons,
SysUtils, StdCtrls, Grids, Calendar, ExtCtrls;
type
TBrDateForm = class(TForm)
Calendar1: TCalendar;
OkBtn: TButton;
CancelBtn: TButton;
TitleLabel: TLabel;
PrevMonthBtn: TSpeedButton;
NextMonthBtn: TSpeedButton;
Bevel1: TBevel;
procedure PrevMonthBtnClick(Sender: TObject);
procedure NextMonthBtnClick(Sender: TObject);
procedure Calendar1Change(Sender: TObject);
private
procedure SetDate(Date: TDateTime);
function GetDate: TDateTime;
public
property Date: TDateTime read GetDate write SetDate;
end;
var
BrDateForm: TBrDateForm;
implementation
{$R *.DFM}
procedure TBrDateForm.SetDate(Date: TDateTime);
begin
Calendar1.CalendarDate := Date;
end;
function TBrDateForm.GetDate: TDateTime;
begin
Result := Calendar1.CalendarDate;
end;
procedure TBrDateForm.PrevMonthBtnClick(Sender: TObject);
begin
Calendar1.PrevMonth;
end;
procedure TBrDateForm.NextMonthBtnClick(Sender: TObject);
begin
Calendar1.NextMonth;
end;
procedure TBrDateForm.Calendar1Change(Sender: TObject);
begin
TitleLabel.Caption := FormatDateTime('MMMM, YYYY', Calendar1.CalendarDate);
end;
end.
|
unit VisCom;
interface
uses
ExtCtrls, Contnrs, Graphics, Classes, StringValidators;
type
TMap = class; // forward
//==============================================================================
// VisCom
// Viscoms are components for visualization of map elements.
// TVisCom is the base class for VisComs. A TVisCom object has the following
// features:
// - code: a short string used for identification purposes
// - data: a reference to an object whose data is represented by this VisCom
// - selection: facilities for selection of this VisCom
// - marking: facilities for marking this VisCom
// - drawing: facilities for drawing this VisCom on a Map
//==============================================================================
TVisCom =
class(TObject)
protected
// fields ------------------------------------------------------------------
FCode: String;
FData: TObject; // shared
FSelected: Boolean;
FMark: String;
public
// construction/destruction ------------------------------------------------
constructor Create(ACode: String; AData: TObject);
// pre: True
// post: (GetCode = ACode) and (GetData = AData) and (IsSelected = False)
// and (GetMark ='')
// primitive queries -------------------------------------------------------
function GetCode: String; virtual;
function GetData: TObject; virtual;
function CanSelect: Boolean; virtual;
// ret: False (may be overridden in descendants)
function CanMark(AMark:String): Boolean; virtual;
// ret: False (may be overridden in descendants)
function IsSelected: Boolean; virtual;
function GetMark: String;
function Contains(AMap: TMap; AX, AY: Integer): Boolean; virtual; abstract;
// pre: True
// ret: "the image of this object drawn on map AMap contains point (AX, AY)"
// derived queries ---------------------------------------------------------
function IsMarked: Boolean; virtual;
// pre: True
// ret: GetMark <> ''
// commands ----------------------------------------------------------------
procedure Select; virtual;
// pre: CanSelect
// post: IsSelected
procedure UnSelect; virtual;
// pre: True
// post: not(IsSelected)
procedure Mark(AMark: String); virtual;
// pre: Canmark(AMark)
// post: GetMark = AMark
procedure UnMark; virtual;
// pre: True
// post: GetMark = ''
procedure Draw(AMap: TMap); virtual; abstract;
// pre: AMap <> nil
// post: this VisCom has been drawn on AMap
end;
TMap =
class(TImage)
protected
FName: String;
FBlankBitmap: TBitmap;
FBackgroundBitmap: TBitmap;
FBackgroundFileName: String;
FBackgroundShown: Boolean;
FMultiSelect: Boolean;
FViscoms: TObjectList; // shared
FMarked: TObjectList; // shared
FSelected: TObjectList; // owner
// protected invariants ----------------------------------------------------
// FBlankPicture <> nil; refers to an all blank bitmap
// FBackgroundPicture <> nil
public
// construction/destruction
constructor Create(AName: String; AOwner: TComponent;
ABlankBitmap, ABackgroundBitmap: TBitmap; AFileName: String);
// pre: True
// post: (inherited.Create.post) and
// (MultiSelect = False) and
// (AbstrVisCom = {} ) and (AbstrMarked = {} ) and
// (AbstrSelected = {} )and
// BackgroundShown and (BackgroundBitmap = ABackgroundBitmap) and
// BlankBitmap = ABlankBitmap and
// FBackgroundFileName = AFileName
constructor CreateEmpty(AName: String; AOwner: TComponent);
// pre: True
// post: (inherited.Create.post) and
// (MultiSelect = False) and
// (AbstrVisCom = {} ) and (AbstrMarked = {} )and
// (AbstrSelected = {} ) and
// BackgroundShown and
// BackgroundBitmap is an instantiated bitmap object and
// BlankBitmap is an instatiated bitmap object and
// (GetBackgroundFileName = '<unknown>' )
destructor Destroy; override;
// primitive queries -------------------------------------------------------
function GetMapName: String;
function GetBackgroundBitmap: TBitmap;
function GetBackgroundFileName: String;
function BackgroundShown: Boolean;
function MultiSelect: Boolean;
function VisComCount: Integer;
// pre: True
// ret: |AbstrVisCom|
function GetVisCom(I: Integer): TVisCom;
// pre: 0 <= I < VisComCount
// ret: AbstrVisCom[I]
function MarkedCount: Integer;
// pre: True
// ret: |AbstrMarked|
function GetMarked(I: Integer): TVisCom;
// pre: 0 <= I < MarkedCount
// ret: AbstrMarked[I]
function SelectedCount: Integer;
// pre: True
// ret: |AbstrSelected|
function GetSelected(I: Integer): TVisCom;
// pre: True
// ret: AbstrSelected[I]
// derived queries ---------------------------------------------------------
function Has(AVisCom: TVisCom): Boolean;
// pre: True
// ret: (exists I: 0 <= I < VisComCount: GetVisCom(I) = AVisCom)
// preconditions -----------------------------------------------------------
function CanAdd(AVisCom: TVisCom): Boolean; virtual;
// pre: True
// ret: not Has(AVisCom)
function CanDelete(AVisCom: TVisCom): Boolean; virtual;
// pre: True
// ret: Has(AVisCom)
function CanSelect(AVisCom: TVisCom): Boolean; virtual;
// pre: True
// ret: Has(AVisCom) and AVisCom.CanSelect
function CanUnselect(AVisCom: TVisCom): Boolean; virtual;
// pre: True
// ret: Has(AVisCom)
function CanMark(AVisCom: TVisCom; AMark: String): Boolean; virtual;
// pre: True
// ret: Has(AVisCom) and AVisCom.CanMark(AMark)
function CanUnmark(AVisCom: TVisCom): Boolean; virtual;
// pre: True
// ret: Has(AVisCom)
// commands ----------------------------------------------------------------
procedure SetMapName(AName: String);
// pre: ValidMapName(AName)
// post: GetMapName = AName
procedure SetBackgroundBitmap(ABackgroundBitmap: TBitmap); virtual;
// pre: ABackgroundBitmap <> nil
// post: GetBackgroundBitmap = ABackgroundBitmap
procedure SetBlankBitmap(ABlankBitmap: TBitmap); virtual;
// pre: ABlankBitmap <> nil
// post: FBlankBitmap = ABlankBitmap
procedure SetBackgroundFileName(AString: String);
// pre: True
// post: GetBackgroundFileName = AString
procedure ShowBackground;
// pre: True
// post: BackgroundShown
procedure HideBackground;
// pre: True
// post: not BackgroundShown
procedure SetMultiSelect(AMultiSelect: Boolean); virtual;
// pre: True
// post: MultiSelect = AMultiSelect
procedure ClearSelected;
// pre: True
// post: SelectedCount = 0
procedure ClearMarked;
// pre: True
// post: MarkedCount = 0
procedure HideAll; virtual;
// pre: True
// post: clear all Viscoms on the map
procedure ShowAll; virtual;
// pre: True
// effect: draw all VisComs on the map
procedure Add(AVisCom: TVisCom);
// pre: CanAdd(AVisCom)
// post: AbstrVisCom = AbstrVisCom U {AVisCom}
procedure Replace(AOldVisCom: TVisCom; ANewVisCom: TVisCom);
// pre: Has(AOldVisCom)
// post: AbstrVisCom = (AbstrVisCom \ {AOldVisCom}) U {ANewVisCom}
procedure Delete(AVisCom: TVisCom);
// pre: CanDelete(AVisCom)
// post: AbstrVisCom = AbstrVisCom \ {AVisCom}
procedure Select(AVisCom: TVisCom);
// pre: CanSelect(AVisCom)
// post: AVisCom.IsSelected
procedure UnSelect(AVisCom: TVisCom);
// pre: CanUnselect(AVisCom)
// post: not AVisCom.IsSelected
procedure Mark(AVisCom: TVisCom; AMark: String);
// pre: CanMark(AVisCom, AMark)
// post: AVisCom.IsMarked
procedure Unmark(AVisCom: TVisCom);
// pre: CanUnmark(AVisCom)
// post: not AVisCom.IsMarked
// model variables ---------------------------------------------------------
// AbstrVisCom: set of TVisCom
// AbstrSelected: set of TVisCom
// AbstrMarked: set of TVisCom
// public invariants -------------------------------------------------------
// A0: AbstrVisCom =
// (set I: 0 <= I < FVisComs.Count: FVisComs[I] as TVisCom)
// A1: AbstrSelected =
// (set I: 0 <= I < FSelected.Count: FSelected[I] as TVisCom)
// A2: AbstrMarked =
// (set I: 0 <= I < FMarked.Count: FMarked[I] as TVisCom)
//
// Unique:
// (forall I, J: 0 <= I < J < VisComCount: GetVisCom(I) <> GetVisCom(J))
// SelectedExists: (forall I: 0 <= I < SelectedCount: Has(GetSelected(I)))
// MarkedExists: (forall I: 0 <= I < MarkedCount: Has(GetMarked(I)))
// MultiSelection: not MultiSelect implies (SelectedCount <= 1)
//
// WellformedPicture:
// (Image.Picture = FBlankBitmap) or (Image.Picture = FBackgroundBitmap)
//
// BackgroundShown <=> Image.Picture = FBackgroundBitmap
end;
implementation //===============================================================
{ TVisCom }
function TVisCom.CanMark(AMark: String): Boolean;
begin
Result := False;
end;
function TVisCom.CanSelect: Boolean;
begin
Result := False;
end;
constructor TVisCom.Create(ACode: String; AData: TObject);
begin
inherited Create;
FCode := ACode;
FData := AData;
FSelected := False;
FMark := '';
end;
function TVisCom.GetCode: String;
begin
Result := FCode;
end;
function TVisCom.GetData: TObject;
begin
Result := FData;
end;
function TVisCom.GetMark: String;
begin
Result := FMark;
end;
function TVisCom.IsMarked: Boolean;
begin
Result := GetMark = '';
end;
function TVisCom.IsSelected: Boolean;
begin
Result := FSelected;
end;
procedure TVisCom.Mark(AMark: String);
begin
Assert(CanMark(AMark), ''); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
FMark := AMark;
end;
procedure TVisCom.Select;
begin
Assert(CanSelect, ''); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
FSelected := True;
end;
procedure TVisCom.UnMark;
begin
FMark := '';
end;
procedure TVisCom.UnSelect;
begin
FSelected := False;
end;
{ TMap }
procedure TMap.Add(AVisCom: TVisCom);
begin
Assert(CanAdd(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
FVisComs.Add(AVisCom);
end;
procedure TMap.Replace(AOldVisCom: TVisCom; ANewVisCom: TVisCom);
begin
with FVisComs do begin
Add(ANewVisCom);
Exchange(IndexOf(AOldVisCom), IndexOf(ANewVisCom));
Remove(AOldVisCom)
end
end;
function TMap.GetBackgroundBitmap: TBitmap;
begin
Result := FBackgroundBitmap;
end;
function TMap.BackgroundShown: Boolean;
begin
Result := FBackgroundShown;
end;
function TMap.CanAdd(AVisCom: TVisCom): Boolean;
begin
Result := not Has(AVisCom);
end;
function TMap.CanDelete(AVisCom: TVisCom): Boolean;
begin
Result := Has(AVisCom);
end;
function TMap.CanMark(AVisCom: TVisCom; AMark: String): Boolean;
begin
Result := Has(AVisCom) and AVisCom.CanMark(AMark);
end;
function TMap.CanSelect(AVisCom: TVisCom): Boolean;
begin
Result := Has(AVisCom) and AVisCom.CanSelect;
end;
function TMap.CanUnmark(AVisCom: TVisCom): Boolean;
begin
Result := Has(AVisCom);
end;
function TMap.CanUnselect(AVisCom: TVisCom): Boolean;
begin
Result := Has(AVisCom);
end;
procedure TMap.ClearMarked;
var
I: Integer;
begin
with FMarked do
begin
for I := Count - 1 downto 0 do //N.B. direction important
begin
(Items[I] as TVisCom).UnMark;
Delete(I);
end;{for}
end;{with}
end;
procedure TMap.ClearSelected;
var
I: Integer;
begin
with FSelected do
begin
for I := Count - 1 downto 0 do //N.B. direction important
begin
(Items[I] as TVisCom).UnSelect;
Delete(I);
end;{for}
end;{with}
end;
constructor TMap.Create(AName: String; AOwner: TComponent;
ABlankBitmap, ABackgroundBitmap: TBitmap;
AFileName: String);
begin
inherited Create(AOwner);
FName := AName;
FBlankBitmap := ABlankBitmap;
FBackgroundBitmap := ABackgroundBitmap;
FBackgroundFileName := AFileName;
ShowBackground;
FMultiSelect := True;
FViscoms := TObjectList.Create(False); // shared
FMarked := TObjectList.Create(False); // shared
FSelected := TObjectList.Create(True); // owner
end;
constructor TMap.CreateEmpty(AName: String; AOwner: TComponent);
begin
inherited Create(AOwner);
FName := AName;
FBlankBitmap := TBitmap.Create;
FBackgroundBitmap := TBitmap.Create;
FBackgroundFileName := '<unknown>';
ShowBackground;
FMultiSelect := True;
FViscoms := TObjectList.Create(False); // shared
FMarked := TObjectList.Create(False); // shared
FSelected := TObjectList.Create(True); // owner
end;
procedure TMap.Delete(AVisCom: TVisCom);
begin
Assert(CanDelete(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
FSelected.Remove(AVisCom);
FMarked.Remove(AVisCom);
FVisComs.Remove(AVisCom);
end;
destructor TMap.Destroy;
begin
// N.B.: Order is important
FSelected.Free; // shares
FMarked.Free; // shares
FVisComs.Free; // owns
FBlankBitmap.Free;
FBackgroundBitmap.Free;
inherited;
end;
function TMap.GetMarked(I: Integer): TVisCom;
begin
Assert( (0 <= I) and (I < MarkedCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := FMarked.Items[I] as TVisCom;
end;
function TMap.GetSelected(I: Integer): TVisCom;
begin
Assert( (0 <= I) and (I < SelectedCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := FSelected.Items[I] as TVisCom;
end;
function TMap.GetVisCom(I: Integer): TVisCom;
begin
Assert( (0 <= I) and (I < VisComCount), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Result := FVisComs.Items[I] as TVisCom;
end;
function TMap.Has(AVisCom: TVisCom): Boolean;
begin
Result := FVisComs.IndexOf(AVisCom) <> -1;
end;
procedure TMap.HideAll;
begin
Picture.Assign(FBackgroundBitmap);
Repaint; // <<<<<<<<<<<<<<<<<<<<<<<<<< Necessary?
end;
procedure TMap.HideBackground;
begin
Picture.Assign(FBlankBitmap);
FBackgroundShown := False;
end;
procedure TMap.Mark(AVisCom: TVisCom; AMark: String);
begin
Assert(CanMark(AVisCom, AMark), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
AVisCom.Mark(AMark);
end;
function TMap.MarkedCount: Integer;
begin
Result := FMarked.Count;
end;
function TMap.MultiSelect: Boolean;
begin
Result := FMultiSelect;
end;
procedure TMap.Select(AVisCom: TVisCom);
begin
Assert(CanSelect(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
AVisCom.Select;
end;
function TMap.SelectedCount: Integer;
begin
Result := FSelected.Count;
end;
procedure TMap.SetBackgroundBitmap(ABackgroundBitmap: TBitmap);
begin
FBackgroundBitmap.Free;
FBackgroundBitmap := ABackgroundBitmap
end;
procedure TMap.SetBlankBitmap(ABlankBitmap: TBitmap);
begin
FBlankBitmap.Free;
FBlankBitmap := ABlankBitmap
end;
procedure TMap.SetBackgroundFileName(AString: String);
begin
FBackgroundFileName := AString;
end;
function TMap.GetBackgroundFileName: String;
begin
Result := FBackgroundFileName;
end;
procedure TMap.SetMultiSelect(AMultiSelect: Boolean);
begin
FMultiSelect := AMultiSelect;
if not AMultiSelect then
begin
ClearSelected;
ClearMarked;
end;
end;
procedure TMap.ShowAll;
var
I: integer;
begin
for I := 0 to VisComCount - 1 do
begin
GetVisCom(I).Draw(Self);
end;
end;
procedure TMap.ShowBackground;
begin
Picture.Assign(FBackgroundBitmap);
FBackgroundShown := True;
end;
procedure TMap.Unmark(AVisCom: TVisCom);
begin
Assert(CanUnmark(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
AVisCom.UnMark;
end;
procedure TMap.UnSelect(AVisCom: TVisCom);
begin
Assert(CanUnselect(AVisCom), ''); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
AVisCom.UnSelect;
end;
function TMap.VisComCount: Integer;
begin
Result := FVisComs.Count;
end;
function TMap.GetMapName: String;
begin
Result := FName
end;
procedure TMap.SetMapName(AName: String);
begin
Assert(ValidMapName(AName),
'TMap.SetName.Pre: ValidMapName(AName)');
FName := AName
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: ObserverIntf
Author: Erwien Saputra
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2002.
Purpose: Provides ISubject and IObserver interfaces.
History: New methods added as I have been inspired from Joanna Carter's
MVP paper. Now I added BeginUpdate and EndUpdate method.
-----------------------------------------------------------------------------}
unit IntfObserver;
interface
type
IObserver = interface;
ISubject = interface
['{A9447E2C-64B9-4A17-9DC8-0C96B96F4598}']
//Property methods
function GetEnabled : boolean;
function GetIsUpdating : boolean;
procedure SetEnabled (const AValue : boolean);
//Main method to notify all the observers.
procedure Notify; overload;
//Method to notify all observers and tell what interface has been changed.
//This method cannot be used with BeginUpdate - EndUpdate.
procedure Notify (const AIntf : IInterface); overload;
//Attach observer to the Subject
procedure AttachObserver (const AObserver : IObserver);
//Detach observer from the Subject
procedure DetachObserver (const AObserver : IObserver);
//Start the update process of the Subject
procedure BeginUpdate;
//End the update process of the Subjet.
procedure EndUpdate;
//Set this observer enabled or disabled
property Enabled : boolean read GetEnabled write SetEnabled;
//Flag, returning this observer is currently updating or not.
property IsUpdating : boolean read GetIsUpdating;
end;
IObserver = interface
['{F82F3F63-CA48-4F5C-BF3E-E4F17804BF4E}']
procedure Update (const Subject : ISubject; const AIntf : IInterface = nil);
end;
implementation
end.
|
{------------------------------------------------------------------------------
TDzXMLTable component
Developed by Rodrigo Depine Dalpiaz (digao dalpiaz)
Flexible dynamic table stored as XML file
https://github.com/digao-dalpiaz/DzXMLTable
Please, read the documentation at GitHub link.
------------------------------------------------------------------------------}
unit DzXMLTable;
interface
uses System.Classes, System.Generics.Collections, Xml.XMLIntf;
const
STR_XML_DATA_IDENT = 'data';
STR_XML_RECORD_IDENT = 'record';
type
TDzXMLTable = class;
TDzField = class
private
FName: string;
FValue: Variant;
public
property Name: string read FName;
property Value: Variant read FValue write FValue;
end;
TDzRecord = class
private
Table: TDzXMLTable;
Fields: TObjectList<TDzField>;
function GetField(const Name: string): Variant;
procedure SetField(const Name: string; const Value: Variant);
function GetFieldIdx(Index: Integer): TDzField;
function GetFieldCount: Integer;
public
constructor Create(Table: TDzXMLTable);
destructor Destroy; override;
property Field[const Name: string]: Variant read GetField write SetField; default;
property FieldIdx[Index: Integer]: TDzField read GetFieldIdx;
property FieldCount: Integer read GetFieldCount;
function GetEnumerator: TEnumerator<TDzField>;
function ReadDef(const Name: string; const DefValue: Variant): Variant;
function FindField(const Name: string): TDzField;
function FieldExists(const Name: string): Boolean;
procedure ClearFields;
end;
TDzXMLTable = class(TComponent)
private
FAbout: string;
Data: TObjectList<TDzRecord>;
FRequiredFile: Boolean;
FFileName: string;
FRequiredField: Boolean;
procedure ReadRecord(N: IXMLNode);
function GetRecCount: Integer;
function GetRecord(Index: Integer): TDzRecord;
function GetRecordOrNilByIndex(Index: Integer): TDzRecord;
public
property Rec[Index: Integer]: TDzRecord read GetRecord; default;
property RecCount: Integer read GetRecCount;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear;
procedure Load;
procedure Save;
function New(Index: Integer = -1): TDzRecord;
procedure Delete(Index: Integer);
function FindIdxByField(const Name: string; const Value: Variant): Integer;
function FindRecByField(const Name: string; const Value: Variant): TDzRecord;
function FindIdxBySameText(const Name: string; const Value: string): Integer;
function FindRecBySameText(const Name: string; const Value: string): TDzRecord;
function GetEnumerator: TEnumerator<TDzRecord>;
procedure Move(CurIndex, NewIndex: Integer);
published
property RequiredFile: Boolean read FRequiredFile write FRequiredFile default False;
property FileName: string read FFileName write FFileName;
property RequiredField: Boolean read FRequiredField write FRequiredField default False;
end;
procedure Register;
implementation
uses Xml.XMLDoc, System.SysUtils, System.Variants;
const STR_VERSION = '1.2';
procedure Register;
begin
RegisterComponents('Digao', [TDzXMLTable]);
end;
//
constructor TDzXMLTable.Create(AOwner: TComponent);
begin
inherited;
FAbout := 'Digao Dalpiaz / Version '+STR_VERSION;
Data := TObjectList<TDzRecord>.Create;
end;
destructor TDzXMLTable.Destroy;
begin
Data.Free;
inherited;
end;
procedure TDzXMLTable.Clear;
begin
Data.Clear;
end;
procedure TDzXMLTable.Load;
var
X: TXMLDocument;
Root: IXMLNode;
I: Integer;
begin
Data.Clear;
if (not FRequiredFile) and (not FileExists(FFileName)) then Exit;
X := TXMLDocument.Create(Self);
try
X.LoadFromFile(FFileName);
Root := X.DocumentElement;
if Root.NodeName<>STR_XML_DATA_IDENT then
raise Exception.CreateFmt('Invalid root element name (expected "%s", found "%s")',
[STR_XML_DATA_IDENT, Root.NodeName]);
for I := 0 to Root.ChildNodes.Count-1 do
ReadRecord(Root.ChildNodes[I]);
finally
X.Free;
end;
end;
procedure TDzXMLTable.ReadRecord(N: IXMLNode);
var
I: Integer;
R: TDzRecord;
F: TDzField;
XMLFld: IXMLNode;
begin
if N.NodeName<>STR_XML_RECORD_IDENT then
raise Exception.CreateFmt('Invalid record element name (expected "%s", found "%s")',
[STR_XML_RECORD_IDENT, N.NodeName]);
R := TDzRecord.Create(Self);
Data.Add(R);
for I := 0 to N.ChildNodes.Count-1 do
begin
F := TDzField.Create;
R.Fields.Add(F);
XMLFld := N.ChildNodes[I];
F.FName := XMLFld.NodeName;
F.FValue := XMLFld.NodeValue;
if VarIsNull(F.FValue) then F.FValue := Unassigned;
end;
end;
procedure TDzXMLTable.Save;
var
X: TXMLDocument;
Root, XMLRec: IXMLNode;
R: TDzRecord;
F: TDzField;
begin
X := TXMLDocument.Create(Self);
try
X.Active := True;
Root := X.AddChild(STR_XML_DATA_IDENT);
for R in Data do
begin
XMLRec := Root.AddChild(STR_XML_RECORD_IDENT);
for F in R.Fields do
XMLRec.AddChild(F.FName).NodeValue := F.FValue;
end;
X.SaveToFile(FFileName);
finally
X.Free;
end;
end;
function TDzXMLTable.GetRecord(Index: Integer): TDzRecord;
begin
Result := Data[Index];
end;
function TDzXMLTable.GetRecCount: Integer;
begin
Result := Data.Count;
end;
function TDzXMLTable.GetRecordOrNilByIndex(Index: Integer): TDzRecord;
begin
if Index<>-1 then
Result := Data[Index]
else
Result := nil;
end;
function TDzXMLTable.GetEnumerator: TEnumerator<TDzRecord>;
begin
Result := Data.GetEnumerator;
end;
function TDzXMLTable.New(Index: Integer): TDzRecord;
begin
Result := TDzRecord.Create(Self);
if Index = -1 then
Data.Add(Result)
else
Data.Insert(Index, Result);
end;
procedure TDzXMLTable.Delete(Index: Integer);
begin
Data.Delete(Index);
end;
procedure TDzXMLTable.Move(CurIndex, NewIndex: Integer);
begin
Data.Move(CurIndex, NewIndex);
end;
function TDzXMLTable.FindIdxByField(const Name: string;
const Value: Variant): Integer;
var
I: Integer;
F: TDzField;
begin
for I := 0 to Data.Count-1 do
begin
F := Data[I].FindField(Name);
if F<>nil then
if F.FValue = Value then Exit(I);
end;
Exit(-1);
end;
function TDzXMLTable.FindIdxBySameText(const Name, Value: string): Integer;
var
I: Integer;
F: TDzField;
begin
for I := 0 to Data.Count-1 do
begin
F := Data[I].FindField(Name);
if F<>nil then
if SameText(F.FValue, Value) then Exit(I);
end;
Exit(-1);
end;
function TDzXMLTable.FindRecByField(const Name: string;
const Value: Variant): TDzRecord;
begin
Result := GetRecordOrNilByIndex(FindIdxByField(Name, Value));
end;
function TDzXMLTable.FindRecBySameText(const Name, Value: string): TDzRecord;
begin
Result := GetRecordOrNilByIndex(FindIdxBySameText(Name, Value));
end;
{ TDzRecord }
constructor TDzRecord.Create(Table: TDzXMLTable);
begin
Self.Table := Table;
Fields := TObjectList<TDzField>.Create;
end;
destructor TDzRecord.Destroy;
begin
Fields.Free;
end;
procedure TDzRecord.ClearFields;
begin
Fields.Clear;
end;
function TDzRecord.GetEnumerator: TEnumerator<TDzField>;
begin
Result := Fields.GetEnumerator;
end;
function TDzRecord.FindField(const Name: string): TDzField;
var
F: TDzField;
begin
for F in Fields do
if SameText(F.FName, Name) then Exit(F);
Exit(nil);
end;
function TDzRecord.FieldExists(const Name: string): Boolean;
begin
Result := FindField(Name) <> nil;
end;
function TDzRecord.GetField(const Name: string): Variant;
var
F: TDzField;
begin
F := FindField(Name);
if F=nil then
begin
if Table.FRequiredField then
raise Exception.CreateFmt('Field "%s" not found', [Name]);
Result := Unassigned;
end else
Result := F.FValue;
end;
function TDzRecord.GetFieldCount: Integer;
begin
Result := Fields.Count;
end;
function TDzRecord.ReadDef(const Name: string; const DefValue: Variant): Variant;
var
F: TDzField;
begin
F := FindField(Name);
if F=nil then
Result := DefValue
else
Result := F.FValue;
end;
procedure TDzRecord.SetField(const Name: string; const Value: Variant);
var
F: TDzField;
begin
F := FindField(Name);
if F=nil then
begin
F := TDzField.Create;
Fields.Add(F);
F.FName := Name;
end;
F.FValue := Value
end;
function TDzRecord.GetFieldIdx(Index: Integer): TDzField;
begin
Result := Fields[Index];
end;
end.
|
unit crtsock;
{
CrtSocket for Delphi 32
Copyright (C) 1999-2001 Paul Toth <tothpaul@free.fr>
http://tothpaul.free.fr
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
interface
uses windows, sysfuncs;
{-$define debug}
// Server side :
// - start a server
// - wait for a client
function StartServer(Port:word):integer;
function WaitClient(Server:integer):integer;
function WaitClientEx(Server:integer; var ip:string):integer;
// Client side :
// - call a server
function CallServer(Server:string;Port:word):integer;
// Both side :
// - Assign CRT Sockets
// - Disconnect server
procedure AssignCrtSock(Socket:integer; Var Input,Output:TextFile);
procedure Disconnect(Socket:integer);
// BroadCasting (UDP)
function StartBroadCast(Port:word):integer;
function SendBroadCast(Server:integer; Port:word; s:string):integer;
function SendBroadCastTo(Server:integer; Port:word; ip,s:string):integer;
function ReadBroadCast(Server:integer; Port:word):string;
function ReadBroadCastEx(Server:integer; Port:word; var ip:string):string;
// BlockRead
function SockAvail(Socket:integer):integer;
function DataAvail(Var F:TextFile):integer;
Function BlockReadsock(Var F:TextFile; var s:string):boolean;
Function send(socket:integer; data:pointer; datalen,flags:integer):integer; stdcall; far;
Function recv(socket:integer; data:pchar; datalen,flags:integer):integer; stdcall; far;
// some usefull SOCKET apis
type
PHost = ^THost;
THost = packed record
name : PChar;
aliases : ^PChar;
addrtype : Smallint;
length : Smallint;
addr : ^pointer;
end;
TSockAddr=packed record
Family:word;
Port:word;
Addr:LongInt;
Zeros:array[0..7] of byte;
end;
TTimeOut=packed record
sec:integer;
usec:integer;
end;
Const
fIoNbRead = $4004667F;
Function socket(Family,Kind,Protocol:integer):integer; stdcall;
Function closesocket(socket:Integer):integer; stdcall;
Function gethostbyname(HostName:PChar):PHost; stdcall;
Function gethostname(name:pchar; size:integer):integer; stdcall;
Function bind(Socket:Integer; Var SockAddr:TSockAddr; AddrLen:integer):integer; stdcall;
Function WSAGetLastError:integer; stdcall;
Function ioctlsocket(socket:integer; cmd: integer; var arg: integer): Integer; stdcall;
// Convert an IP Value to xxx.xxx.xxx.xxx string
Function LongToIp(Long:LongInt):string;
Function IpToLong(ip:string):longint;
Function HostToLong(AHost:string):LongInt;
//Select
Function select(nfds:integer; readfds, writefds, exceptfds:pointer; var timeout:TTimeOut):integer; stdcall; far;
Var
EofSock:boolean;
implementation
Const
WinSock='wsock32.dll'; { 32bits socket DLL }
Internet=2; { Internat familly }
Stream=1; { Streamed socket }
Datagrams=2;
// fIoNbRead = $4004667F;
sol_socket=$FFFF;
SO_BROADCAST = $0020; { permit sending of broadcast msgs }
//------ winsock -------------------------------------------------------
Type
TWSAData = packed record
wVersion: Word;
wHighVersion: Word;
szDescription: array[0..256] of Char;
szSystemStatus: array[0..128] of Char;
iMaxSockets: Word;
iMaxUdpDg: Word;
lpVendorInfo: PChar;
end;
{ Winsock }
Function WSAStartup(Version:word; Var Data:TwsaData):integer; stdcall; far; external winsock;
Function socket(Family,Kind,Protocol:integer):integer; stdcall; far; external winsock;
Function shutdown(Socket,How:Integer):integer; stdcall; far; external winsock;
Function closesocket(socket:Integer):integer; stdcall; far; external winsock;
Function WSACleanup:integer; stdcall; far; external winsock;
//Function WSAAsyncSelect(Socket:Integer; Handle:Hwnd; Msg:word; Level:Longint):longint; stdcall; far; external winsock;
Function bind(Socket:Integer; Var SockAddr:TSockAddr; AddrLen:integer):integer; stdcall; far; external winsock;
Function listen(socket,flags:Integer):integer; stdcall; far; external winsock;
Function connect(socket:Integer; Var SockAddr:TSockAddr; AddrLen:integer):integer; stdcall; far; external winsock;
Function accept(socket:Integer; Var SockAddr:TSockAddr; Var AddrLen:Integer):integer; stdcall; far; external winsock;
Function WSAGetLastError:integer; stdcall; far; external winsock;
Function recv(socket:integer; data:pchar; datalen,flags:integer):integer; stdcall; far; external winsock;
Function send(socket:integer; data:pointer; datalen,flags:integer):integer; stdcall; far; external winsock;
//Function getpeername(socket:integer; var SockAddr:TSockAddr; Var AddrLen:Integer):Integer; stdcall; far; external winsock;
Function gethostbyname(HostName:PChar):PHost; stdcall; far; external winsock;
//Function getsockname(socket:integer; var SockAddr:TSockAddr; Var AddrLen:Integer):integer; stdcall; far; external winsock;
//Function inet_ntoa(addr:longint):PChar; stdcall; far; external winsock;
Function WSAIsBlocking:boolean; stdcall; far; external winsock;
Function WSACancelBlockingCall:integer; stdcall; far; external winsock;
Function ioctlsocket(socket:integer; cmd: integer; var arg: integer): Integer; stdcall; far; external winsock;
//Function gethostbyaddr(var addr:longint; size,atype:integer):PHost; stdcall; far; external winsock;
Function gethostname(name:pchar; size:integer):integer; stdcall; far; external winsock;
function select(nfds:integer; readfds, writefds, exceptfds:pointer; var timeout:TTimeOut):integer; stdcall; far; external winsock;
function setsockopt(socket,level,optname:integer;var optval; optlen:integer):integer; stdcall; far; external winsock;
Function sendto(socket:integer; data:pointer; datalen,flags:integer; var SockAddr:TSockAddr; AddrLen:Integer):integer; stdcall; far; external winsock;
Function recvfrom(socket:integer; data:pointer; datalen,flags:integer; var SockAddr:TSockAddr; var AddrLen:Integer):integer; stdcall; far; external winsock;
Function IpToLong(ip:string):LongInt;
var
x,i:byte;
ipx:array[0..3] of byte;
v:integer;
begin
Result:=0;
longint(ipx):=0; i:=0;
for x:=1 to length(ip) do
if ip[x]='.' then begin
inc(i);
if i=4 then exit;
end else begin
if not (ip[x] in ['0'..'9']) then exit;
v:=ipx[i]*10+ord(ip[x])-ord('0');
if v>255 then exit;
ipx[i]:=v;
end;
result:=longint(ipx);
end;
Function HostToLong(AHost:string):LongInt;
Var
Host:PHost;
begin
Result:=IpToLong(AHost);
if Result=0 then begin
Host:=GetHostByName(PChar(AHost));
if Host<>nil then Result:=longint(Host^.Addr^^);
end;
end;
Function LongToIp(Long:LongInt):string;
var
ipx:array[0..3] of byte;
i:byte;
begin
longint(ipx):=long;
Result:='';
for i:=0 to 3 do result:=result+IntToStr(ipx[i])+'.';
SetLength(Result,Length(Result)-1);
end;
//--- Server Side ------------------------------------------------------------------------
function StartServer(Port:word):integer;
Var
SockAddr:TSockAddr;
begin
Result:=socket(Internet,Stream,0);
if Result=-1 then exit;
FillChar(SockAddr,SizeOf(SockAddr),0);
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
if (Bind(Result,SockAddr,SizeOf(SockAddr))<>0)
or (Listen(Result,0)<>0) then begin
CloseSocket(Result);
Result:=-2;
end;
end;
function WaitClient(Server:integer):integer;
var
Client:TSockAddr;
Size:integer;
begin
Size:=SizeOf(Client);
Result:=Accept(Server,Client,Size);
end;
function WaitClientEx(Server:integer; var ip:string):integer;
var
Client:TSockAddr;
Size:integer;
begin
Size:=SizeOf(Client);
Result:=Accept(Server,Client,Size);
ip:=LongToIp(Client.Addr);
end;
function SockReady(Socket:integer):boolean;
var
sockset:packed record
count:integer;
socks:{array[0..63] of} integer;
end;
timeval:TTimeOut;
begin
sockSet.count:=1;
sockSet.socks:=Socket;
timeval.sec :=0;
timeval.usec :=0;
result:=Select(0,@sockSet,nil,nil,timeval)>0;
end;
function SockAvail(Socket:integer):integer;
var
rdy:boolean;
begin
rdy:=SockReady(Socket); // before IoCtlSocket to be sure (?) that we don't get some data between the 2 calls
if IoctlSocket(Socket, fIoNbRead,Result)<0 then
Result:=-1
else begin
if (Result=0) and RDY then result:=-1; // SockReady is TRUE when Data ara Avaible AND when Socket is closed
end;
end;
function DataAvail(Var F:TextFile):integer;
var
s:integer;
begin
// cause of TexTFile Buffer, we need to check both Buffer & Socket !
With TTextRec(F) do begin
Result:=BufEnd-BufPos;
s:=SockAvail(Handle);
end;
if Result=0 then Result:=s else if s>0 then Inc(Result,s);
end;
Function BlockReadSock(Var F:TextFile; var s:string):boolean;
Var
Handle:THandle;
Size:integer;
begin
Result:=False;
Handle:=TTextRec(F).Handle;
Repeat
if (IoctlSocket(Handle, fIoNbRead, Size)<0) then exit;
if Size=0 then exit
until (Size>0);
SetLength(s,Size);
Recv(Handle,pchar(s),Size,0);
Result:=True;
end;
// Client Side--------------------------------------------------------------------------
function CallServer(Server:string; Port:word):integer;
var
SockAddr:TSockAddr;
begin
Result:=socket(Internet,Stream,0);
if Result=-1 then exit;
FillChar(SockAddr,SizeOf(SockAddr),0);
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
SockAddr.Addr:=HostToLong(Server);
if Connect(Result,SockAddr,SizeOf(SockAddr))<>0 then begin
Disconnect(Result);
Result:=-1;
end;
end;
// BroadCasting-------------------------------------
function StartBroadCast(Port:word):integer;
Var
SockAddr:TSockAddr;
bc:integer;
begin
Result:=socket(Internet,Datagrams,17); // 17 for UDP ... work also with 0 ?!
if Result=-1 then exit;
FillChar(SockAddr,SizeOf(SockAddr),0);
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
// SockAddr.Addr:=0; ?
bc:=SO_BROADCAST;
if (Bind(Result,SockAddr,SizeOf(SockAddr))<>0)
or (setsockopt(Result,SOL_SOCKET,SO_BROADCAST,bc,SizeOf(bc))<>0) then begin
CloseSocket(Result);
Result:=-1;
end;
end;
function SendBroadCast(Server:integer; Port:word; s:string):integer;
Var
SockAddr:TSockAddr;
begin
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
SockAddr.Addr:=-1;
Result:=SendTo(Server,@s[1],length(s),0,SockAddr,SizeOf(SockAddr));
end;
function SendBroadCastTo(Server:integer; Port:word; ip,s:string):integer;
Var
SockAddr:TSockAddr;
begin
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
SockAddr.Addr:=IpToLong(ip);
Result:=SendTo(Server,@s[1],length(s),0,SockAddr,SizeOf(SockAddr));
end;
function ReadBroadCast(Server:integer; Port:word):string;
Var
SockAddr:TSockAddr;
SockLen:integer;
len:integer;
begin
FillChar(SockAddr,SizeOf(SockAddr),0);
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
SockLen:=SizeOf(SockAddr);
setlength(result,1024);
len:=recvfrom(Server,@result[1],1024,0,SockAddr,SockLen);
if len>0 then SetLength(result,len) else result:='';
end;
function ReadBroadCastEx(Server:integer; Port:word; var ip:string):string;
Var
SockAddr:TSockAddr;
SockLen:integer;
len:integer;
begin
FillChar(SockAddr,SizeOf(SockAddr),0);
SockAddr.Family:=Internet;
SockAddr.Port:=swap(Port);
SockLen:=SizeOf(SockAddr);
setlength(result,1024);
len:=recvfrom(Server,@result[1],1024,0,SockAddr,SockLen);
if len>0 then SetLength(result,len) else result:='';
ip:=LongToIp(SockAddr.Addr);
end;
//------------ CrtSock -----------------
Var
InitOk:boolean;
function OutputSock(Var F:TTextRec):integer; far;
begin
{$ifdef debug}writeln('out ',F.BufPtr);{$endif}
if F.BufPos<>0 then begin
Send(F.Handle,F.BufPtr,F.BufPos,0);
F.BufPos:=0;
end;
Result:=0;
end;
function InputSock(var F: TTextRec): Integer; far;
Var
Size:integer;
begin
F.BufEnd:=0;
F.BufPos:=0;
Result:=0;
Repeat
if (IoctlSocket(F.Handle, fIoNbRead, Size)<0) then begin
EofSock:=True;
exit;
end;
until (Size>=0);
//if Size>0 then
F.BufEnd:=Recv(F.Handle,F.BufPtr,F.BufSize,0);
EofSock:=(F.BufEnd=0);
{$ifdef debug}writeln('in ',F.BufPtr);{$endif}
end;
procedure Disconnect(Socket:integer);
var
dummy:array[0..1024] of char;
begin
ShutDown(Socket,1);
repeat until recv(Socket,dummy,1024,0)<=0;
CloseSocket(Socket);
end;
function CloseSock(var F:TTextRec):integer; far;
begin
Disconnect(F.Handle);
F.Handle:=-1;
Result:=0;
end;
function OpenSock(var F: TTextRec): Integer; far;
begin
F.BufPos:=0;
F.BufEnd:=0;
if F.Mode = fmInput then begin // ReadLn
EofSock:=False;
F.InOutFunc := @InputSock;
F.FlushFunc := nil;
end else begin // WriteLn
F.Mode := fmOutput;
F.InOutFunc := @OutputSock;
F.FlushFunc := @OutputSock;
end;
F.CloseFunc := @CloseSock;
Result:=0;
end;
Procedure AssignCrtSock(Socket:integer; Var Input,Output:TextFile);
begin
with TTextRec(Input) do begin
Handle := Socket;
Mode := fmClosed;
BufSize := SizeOf(Buffer);
BufPtr := @Buffer;
OpenFunc := @OpenSock;
end;
with TTextRec(Output) do begin
Handle := Socket;
Mode := fmClosed;
BufSize := SizeOf(Buffer);
BufPtr := @Buffer;
OpenFunc := @OpenSock;
end;
Reset(Input);
Rewrite(Output);
end;
//----- Initialization/Finalization--------------------------------------------------
Procedure InitCrtSock;
var
wsaData:TWSAData;
begin
//if InitOk Then exit;
InitOk:=wsaStartup($101,wsaData)=0;
{$ifdef debug}allocconsole{$endif}
end;
Procedure DoneCrtSock;
begin
if not InitOk then exit;
if wsaIsBlocking then wsaCancelBlockingCall;
wsaCleanup;
end;
Initialization InitCrtSock;
Finalization DoneCrtSock;
end.
|
unit uxpldeterminators;
{$mode objfpc}{$H+}
interface
uses Classes,u_xml_xpldeterminator, uxplsettings;
Type
{ TxPLDeterminatorList }
TxPLDeterminatorList = class(TStringList)
private
fBaseDir : string;
function Get_Determinator(index : integer): TXMLxpldeterminatorsFile;
function ReferenceAFile(const aFName : string) : integer;
public
constructor Create(const axPLSettings : TxPLSettings);
destructor Destroy; override;
property Elements[index : integer] : TXMLxpldeterminatorsFile read Get_Determinator; default;
function TextContent(const aSGUID: string) : AnsiString;
function Add(const aSGUID :string; const aStringList : TStringList) : string; overload;
function Delete(const aSGUID :string) : boolean; overload;
procedure ListRules(const aGUID : string; aOut : TStringList);
procedure ListGroups(aOut : TStringList);
end;
implementation // ==================================================================================
uses uxPLConst, SysUtils, cStrings, DOM, XMLRead, XMLWrite, u_xml;
{ TxPLDeterminatorList }
function TxPLDeterminatorList.Get_Determinator(index: integer ): TXMLxpldeterminatorsFile;
begin
result := TXMLxpldeterminatorsFile( Objects[index]);
end;
constructor TxPLDeterminatorList.Create(const axPLSettings : TxPLSettings);
var
searchResult : TSearchRec;
fName,fExt : string;
begin
inherited Create;
fBaseDir := axPLSettings.SharedConfigDir + 'determinator\';
TxPLSettings.EnsureDirectoryExists(fBaseDir);
Duplicates:=dupIgnore;
Sorted := true;
SetCurrentDir(fBaseDir);
if FindFirst('*' + K_FEXT_XML, faAnyFile, searchResult) = 0 then begin
repeat
StrSplitAtChar(SearchResult.Name,'.',fName,fExt); // Get filename without extension
ReferenceAFile(fName);
until FindNext(searchResult) <> 0;
FindClose(searchResult);
end;
end;
destructor TxPLDeterminatorList.Destroy;
var i : integer;
aDoc : TXMLDocument;
begin
for i:=0 to count-1 do begin
aDoc := TXMLxplDeterminatorsFile(Objects[i]).Document;
WriteXMLFile(aDoc,fBaseDir + Strings[i] + K_FEXT_XML);
aDoc.Free;
end;
inherited Destroy;
end;
function TxPLDeterminatorList.TextContent(const aSGUID: string): AnsiString;
var ts : tstringlist;
i : integer;
begin
i := IndexOf(aSGUID);
if i=-1 then exit;
ts := TStringList.Create;
ts.LoadFromFile(fBaseDir + aSGUID + K_FEXT_XML);
result := ts.text;
ts.Destroy;
end;
function TxPLDeterminatorList.Add(const aSGUID: string; const aStringList: TStringList): string;
var i : integer;
guid : TGUID;
begin
i := IndexOf(aSGUID);
if i=-1 then begin // It is a new determinator
sysutils.CreateGUID(guid);
result := StrRemoveChar(GuidToString(guid),['{','-','}']);
end else begin // We replace an existing determinator
result := aSGUID;
Delete(aSGUID);
end;
aStringList.Text:=StrReplace('
','',aStringList.Text); // For an unknown reason xPLHal manager gives me this shit
aStringList.Text:=StrReplace('
','',aStringList.Text);
aStringList.SaveToFile(fBaseDir + result + K_FEXT_XML);
ReferenceAFile(Result);
end;
function TxPLDeterminatorList.Delete(const aSGUID: string): boolean;
var i : integer;
aDeterminator : TXMLxpldeterminatorsfile;
begin
i := IndexOf(aSGUID);
result := i<>-1;
if not result then exit;
aDeterminator := TXMLxpldeterminatorsFile(Objects[i]);
aDeterminator.Destroy;
DeleteFile(fBaseDir + Strings[i] + K_FEXT_XML);
Delete(i);
end;
procedure TxPLDeterminatorList.ListRules(const aGUID : string; aOut : TStringList);
const sFormatRule = '%s'#9'%s'#9'%s';
var i : integer;
begin
for i:=0 to Count-1 do
if not Elements[i][0].IsGroup then begin
if (Elements[i][0].groupname = aGUID) or (aGUID='{ALL}') then
aOut.Add(Format(sFormatRule,[Strings[i],Elements[i][0].Name_,Elements[i][0].EnabledAsString]));
end;
end;
procedure TxPLDeterminatorList.ListGroups(aOut : TStringList);
const sFormatGroup = '%s'#9'%s';
var i : integer;
begin
for i:=0 to Count-1 do
if Elements[i][0].IsGroup then aOut.Add(Format(sFormatGroup,[Strings[i],Elements[i][0].Name_,'']));
end;
function TxPLDeterminatorList.ReferenceAFile(const aFName: string) : integer;
var aDocument : TXMLDocument;
begin
result := Add(afName);
aDocument := TXMLDocument.Create; // I must create one document for every file
ReadXMLFile(aDocument, fBaseDir + aFNAME + K_FEXT_XML);
Objects[result] := TXMLxpldeterminatorsFile.Create(aDocument,K_XML_STR_Determinator);
end;
end.
|
unit UnitAutoEMail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.NumberBox,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdExplicitTLSClientServerBase, IdMessageClient, IdSMTPBase, IdSMTP,
Vcl.ExtCtrls, Vcl.Menus, IdMessage, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdSSL, IdSSLOpenSSL;
type
TFormMain = class(TForm)
TrayIcon: TTrayIcon;
IdSMTP: TIdSMTP;
EditHost: TEdit;
LabelHostname: TLabel;
EditUsername: TEdit;
LabelUsername: TLabel;
EditPassword: TEdit;
LabelPassword: TLabel;
LabelPort: TLabel;
EditPort: TNumberBox;
LabelSecurity: TLabel;
ComboBoxSecurity: TComboBox;
PopupMenu: TPopupMenu;
MenuItemQuit: TMenuItem;
MenuItemShow: TMenuItem;
LabelSubject: TLabel;
EditSubject: TEdit;
MemoBody: TMemo;
LabelBody: TLabel;
LabelInterval: TLabel;
EditInterval: TNumberBox;
LabelRecipient: TLabel;
EditRecipient: TEdit;
LabelMinutes: TLabel;
CheckBoxEnabled: TCheckBox;
Timer: TTimer;
IdMessage: TIdMessage;
IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
EditSender: TEdit;
LabelSender: TLabel;
procedure MenuItemQuitClick(Sender: TObject);
procedure MenuItemShowClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditPortChangeValue(Sender: TObject);
procedure EditPasswordChange(Sender: TObject);
procedure EditUsernameChange(Sender: TObject);
procedure EditHostChange(Sender: TObject);
procedure ComboBoxSecurityChange(Sender: TObject);
procedure CheckBoxEnabledClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure TimerTimer(Sender: TObject);
procedure EditIntervalChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditSenderChange(Sender: TObject);
procedure EditSubjectChange(Sender: TObject);
procedure MemoBodyChange(Sender: TObject);
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
uses
Registry;
procedure TFormMain.CheckBoxEnabledClick(Sender: TObject);
begin
Timer.Enabled := CheckBoxEnabled.Checked;
if Timer.Enabled then
TimerTimer(Sender);
end;
procedure TFormMain.ComboBoxSecurityChange(Sender: TObject);
begin
case ComboBoxSecurity.ItemIndex of
0:
begin
EditPort.ValueInt := 25;
end;
1:
begin
EditPort.ValueInt := 587;
end;
2:
begin
EditPort.ValueInt := 465;
end;
end;
end;
procedure TFormMain.EditHostChange(Sender: TObject);
begin
IdSMTP.Host := EditHost.Text;
end;
procedure TFormMain.EditIntervalChange(Sender: TObject);
begin
Timer.Interval := EditInterval.ValueInt * 60 * 1000;
end;
procedure TFormMain.EditPasswordChange(Sender: TObject);
begin
IdSMTP.Password := EditPassword.Text;
end;
procedure TFormMain.EditPortChangeValue(Sender: TObject);
begin
IdSMTP.Port := EditPort.ValueInt;
end;
procedure TFormMain.EditSenderChange(Sender: TObject);
begin
IdMessage.From.Address := EditSender.Text;
IdMessage.From.Name := EditSender.Text;
end;
procedure TFormMain.EditSubjectChange(Sender: TObject);
begin
IdMessage.Subject := EditSubject.Text;
end;
procedure TFormMain.EditUsernameChange(Sender: TObject);
begin
IdSMTP.Username := EditUsername.Text;
end;
procedure TFormMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caMinimize;
end;
procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if CheckBoxEnabled.Checked then
begin
Application.Minimize;
ShowWindow(Application.Handle, SW_HIDE);
end;
CanClose := not CheckBoxEnabled.Checked;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
with TRegistry.Create do
begin
try
Rootkey := HKEY_CURRENT_USER;
if OpenKey('Software\SimpleAutoEmail\AutoEmail', False) then
begin
ComboBoxSecurity.ItemIndex := ReadInteger('Security');
EditHost.Text := ReadString('Host');
EditUsername.Text := ReadString('Username');
EditPassword.Text := ReadString('Password');
EditPort.ValueInt := ReadInteger('Port');
EditRecipient.Text := ReadString('Recipient');
EditSubject.Text := ReadString('Subject');
EditSender.Text := ReadString('Sender');
MemoBody.Lines.Text := ReadString('Body');
EditInterval.ValueInt := ReadInteger('Interval');
CheckBoxEnabled.Checked := ReadBool('Enabled');
end;
finally
Free;
end;
end;
end;
procedure TFormMain.FormDestroy(Sender: TObject);
begin
with TRegistry.Create do
begin
try
Rootkey := HKEY_CURRENT_USER;
if OpenKey('Software\GTA\AutoEmail', True) then
begin
WriteString('Host', EditHost.Text);
WriteString('Username', EditUsername.Text);
WriteString('Password', EditPassword.Text);
WriteInteger('Port', EditPort.ValueInt);
WriteInteger('Security', ComboBoxSecurity.ItemIndex);
WriteString('Sender', EditSender.Text);
WriteString('Recipient', EditRecipient.Text);
WriteString('Subject', EditSubject.Text);
WriteString('Body', MemoBody.Lines.Text);
WriteInteger('Interval', EditInterval.ValueInt);
WriteBool('Enabled', CheckBoxEnabled.Checked);
end;
finally
Free;
end;
end;
end;
procedure TFormMain.MemoBodyChange(Sender: TObject);
begin
IdMessage.Body := MemoBody.Lines;
end;
procedure TFormMain.MenuItemQuitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFormMain.MenuItemShowClick(Sender: TObject);
begin
Show;
Application.Restore;
end;
procedure TFormMain.TimerTimer(Sender: TObject);
begin
IdMessage.Recipients.Add.Address := EditRecipient.Text;
try
IdSMTP.Connect;
IdSMTP.Authenticate;
except
on E:Exception do
begin
MessageDlg('Cannot authenticate: ' + E.Message, mtWarning, [mbOK], 0);
Exit;
end;
end;
IdSMTP.Send(IdMessage);
end;
end.
|
unit PlayerOptions;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TPlayerOptions }
TPlayerLogOption = (ploExtractor, ploDB);
TPlayerLogOptions = set of TPlayerLogOption;
TPlayerOptions = class(TPersistent)
private class var
FOptions: TPlayerOptions;
private
FLogOptions: TPlayerLogOptions;
FTempDir: String;
procedure SetTempDir(AValue: String);
public
class constructor ClassCreate;
class destructor ClassDestroy;
class property Options: TPlayerOptions read FOptions;
published
property TempDir: String read FTempDir write SetTempDir;
property LogOptions: TPlayerLogOptions
read FLogOptions write FLogOptions default [];
end;
function opts: TPlayerOptions;
implementation
function opts: TPlayerOptions;
begin
Result:=TPlayerOptions.Options;
end;
{ TPlayerOptions }
procedure TPlayerOptions.SetTempDir(AValue: String);
begin
if FTempDir = AValue then Exit;
FTempDir:=IncludeTrailingPathDelimiter(AValue);
ForceDirectories(FTempDir);
end;
class constructor TPlayerOptions.ClassCreate;
begin
inherited;
FOptions:=TPlayerOptions.Create;
end;
class destructor TPlayerOptions.ClassDestroy;
begin
FOptions.Free;
inherited;
end;
end.
|
{ Component(s):
tcyBaseLed
Description:
A base led component with Group feature
Led states : ON/OFF/DISABLE
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is Mauricio
* (https://sourceforge.net/projects/tcycomponents/).
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or the
* GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
* case the provisions of the GPL or the LGPL are applicable instead of those
* above. If you wish to allow use of your version of this file only under the
* terms of either the GPL or the LGPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and other
* provisions required by the LGPL or the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under the
* terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****}
unit indcyBaseLed;
{$mode objfpc}{$H+}
interface
uses LCLIntf, LCLType, LMessages, Messages, Classes, Types, Controls, Graphics;
type
TLedStatus = (lsOn, lsOff, lsDisabled);
TcyBaseLed = class(TGraphicControl)
private
FGroupIndex: Integer;
FAllowAllOff: Boolean;
FLedValue: Boolean;
FReadOnly: Boolean;
procedure SetAllowAllOff(Value: Boolean);
procedure SetGroupIndex(Value: Integer);
procedure UpdateExclusive;
protected
procedure Click; override;
procedure Loaded; override;
procedure SetEnabled(Value: Boolean); override;
procedure CMButtonPressed(var Message: TLMessage); message CM_BUTTONPRESSED; // Called in UpdateExclusive procedure ...
function TransparentColorAtPos({%H-}Point: TPoint): boolean; virtual;
procedure LedStatusChanged; virtual;
procedure SetInternalLedValue(Value: Boolean);
function GetLedStatus: TLedStatus; virtual;
procedure SetLedvalue(Value: Boolean); virtual;
procedure SetReadOnly(AValue: Boolean); virtual;
property AllowAllOff: Boolean read FAllowAllOff write SetAllowAllOff default false;
property GroupIndex: Integer read FGroupIndex write SetGroupIndex default 0;
property LedValue: Boolean read FLedvalue write SetLedvalue;
property ReadOnly: Boolean read FReadOnly write SetReadOnly default false;
public
property Canvas;
constructor Create(AOwner: TComponent); override;
property LedStatus: TLedStatus read GetLedStatus;
procedure Switch;
published
end;
implementation
constructor TcyBaseLed.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAllowAllOff := false;
FGroupIndex := 0;
FLedvalue:= false;
FReadOnly := false;
end;
procedure TcyBaseLed.LedStatusChanged;
begin
Invalidate;
end;
procedure TcyBaseLed.Loaded;
begin
Inherited;
ControlStyle := ControlStyle - [csDoubleClicks];
end;
procedure TcyBaseLed.SetReadOnly(AValue: Boolean);
begin
if AValue <> FReadOnly
then FReadOnly := AValue;
end;
procedure TcyBaseLed.SetEnabled(Value: Boolean);
begin
Inherited;
LedStatusChanged;
end;
function TcyBaseLed.TransparentColorAtPos(Point: TPoint): boolean;
begin
Result := false;
end;
procedure TcyBaseLed.Click;
var
aPt: TPoint = (x:0; y:0);
begin
if not FReadOnly
then begin
GetCursorPos(aPt);
aPt := Self.ScreenToClient(aPt);
if Not TransparentColorAtPos(aPt)
then LedValue := not FLedValue;
end;
Inherited;
end;
function TcyBaseLed.GetLedStatus: TLedStatus;
begin
if not Enabled
then
RESULT := lsDisabled
else
if FLedValue
then RESULT := lsOn
else RESULT := lsOff;
end;
// Procedure to force changing value :
procedure TcyBaseLed.SetInternalLedValue(Value: Boolean);
begin
if FLedValue <> Value
then begin
FLedValue := Value;
LedStatusChanged;
end;
end;
procedure TcyBaseLed.Switch;
begin
LedValue := not FLedValue;
end;
procedure TcyBaseLed.SetLedvalue(Value: Boolean);
begin
if Value <> FLedvalue
then begin
if (not Value) and (not FAllowAllOff) and (FGroupIndex <> 0)
then Exit; // Can't turn off all leds of the same group ...
FLedvalue := Value;
LedStatusChanged;
if Value
then UpdateExclusive; // Send message to turn off the other one ...
end;
end;
procedure TcyBaseLed.SetAllowAllOff(Value: Boolean);
begin
if FAllowAllOff <> Value
then begin
FAllowAllOff := Value;
UpdateExclusive; // Inform FAllowAllOff value to the others from the same group
end;
end;
procedure TcyBaseLed.SetGroupIndex(Value: Integer);
begin
if FGroupIndex <> Value
then begin
FGroupIndex := Value;
UpdateExclusive;
end;
end;
procedure TcyBaseLed.UpdateExclusive;
var
Msg: TMessage;
begin
if (FGroupIndex <> 0) and (Parent <> nil)
then begin
Msg.Msg := CM_BUTTONPRESSED;
Msg.WParam := FGroupIndex;
Msg.LParam := PtrInt(Self);
Msg.Result := 0;
Parent.Broadcast(Msg);
end;
end;
procedure TcyBaseLed.CMButtonPressed(var Message: TLMessage);
var Sender: TcyBaseLed;
begin
if (csLoading in ComponentState) then exit;
if Message.WParam = FGroupIndex // Same group?
then begin
Sender := TcyBaseLed(Message.LParam);
if Sender <> Self
then begin
if Sender.LedValue and FLedValue // Only one can be turn on on group mode ...
then begin;
FLedValue := false;
LedStatusChanged;
end;
FAllowAllOff := Sender.AllowAllOff;
end;
end;
end;
end.
|
unit SHL_IsoReader; // SemVersion: 0.1.0
interface // SpyroHackingLib is licensed under WTFPL
// TODO:
// - reading filelist
// - recognize more formats
uses
StrUtils, SysUtils, Classes, SHL_Types;
type
TImageFormat = (ifUnknown, ifIso, ifMdf, ifStr);
type
TIsoReader = class(TFileStream)
constructor Create(Filename: TextString; DenyWrite: Boolean = False);
constructor CreateWritable(Filename: TextString; DenyWrite: Boolean = False);
protected
function GetSize(): Int64; override;
public
function SetFormat(Header: Integer = 0; Footer: Integer = 0; Body: Integer =
2336; Offset: Integer = 0): Boolean; overload;
function SetFormat(Format: TImageFormat): Boolean; overload;
procedure SeekToSector(Sector: Integer);
function ReadSectors(SaveDataTo: Pointer; Count: Integer = 0): Integer;
function WriteSectors(ReadDataFrom: Pointer; Count: Integer = 0): Integer;
function GuessImageFormat(Text: PChar = nil): TImageFormat;
private
FCachedSize: Integer;
FSectorsCount: Integer;
FHeader: Integer;
FFooter: Integer;
FBody: Integer;
FOffset: Integer;
FTotal: Integer;
FSector: Integer;
public
property SectorsCount: Integer read FSectorsCount;
property Header: Integer read FHeader;
property Footer: Integer read FFooter;
property Body: Integer read FBody;
property Total: Integer read FTotal;
property Offset: Integer read FOffset;
property Sector: Integer read FSector write SeekToSector;
end;
implementation
function TIsoReader.GetSize(): Int64;
begin
Result := Int64(FCachedSize);
end;
constructor TIsoReader.Create(Filename: TextString; DenyWrite: Boolean = False);
begin
if DenyWrite then
inherited Create(Filename, fmOpenRead or fmShareDenyWrite)
else
inherited Create(Filename, fmOpenRead or fmShareDenyNone);
SetFormat();
end;
function TIsoReader.SetFormat(Header: Integer = 0; Footer: Integer = 0; Body:
Integer = 2336; Offset: Integer = 0): Boolean;
begin
FHeader := Header;
FFooter := Footer;
FBody := Body;
FTotal := FHeader + FBody + FFooter;
FCachedSize := Integer(inherited GetSize());
FSectorsCount := FCachedSize div FTotal;
Result := (FCachedSize mod FTotal) = 0;
end;
function TIsoReader.SetFormat(Format: TImageFormat): Boolean;
begin
Result := False;
case Format of
ifIso:
Result := SetFormat(16, 0);
ifMdf:
Result := SetFormat(16, 96);
ifStr:
Result := SetFormat(0, 0);
ifUnknown:
Result := SetFormat(0, 0);
end;
end;
procedure TIsoReader.SeekToSector(Sector: Integer);
begin
FSector := Sector;
Position := FOffset + FTotal * FSector + FHeader;
end;
function TIsoReader.ReadSectors(SaveDataTo: Pointer; Count: Integer = 0): Integer;
begin
if Count = 0 then
Result := Ord(inherited Read(SaveDataTo^, FBody) = FBody)
else
Result := inherited Read(SaveDataTo^, FTotal * Count) div FTotal;
Inc(FSector, Result);
end;
function TIsoReader.WriteSectors(ReadDataFrom: Pointer; Count: Integer = 0): Integer;
begin
if Count = 0 then
Result := Ord(inherited Write(ReadDataFrom^, FBody) = FBody)
else
Result := inherited Write(ReadDataFrom^, FTotal * Count) div FTotal;
Inc(FSector, Result);
end;
function TIsoReader.GuessImageFormat(Text: PChar = nil): TImageFormat;
var
Sector: array[0..615] of Integer;
OldPos: Integer;
begin
Result := ifUnknown;
FBody := 2336;
FHeader := 0;
FFooter := 0;
OldPos := Position;
ReadBuffer(Sector, 2464);
Position := OldPos;
while True do
begin
if (Sector[0] = Sector[1]) and (Sector[584] = Sector[585]) then
begin
if Text <> nil then
StrCopy(Text, 'STR');
Result := ifStr;
Break;
end;
FHeader := 16;
if (Sector[0] = Sector[588]) and (Sector[1] = Sector[589]) then
begin
if Text <> nil then
StrCopy(Text, 'ISO');
Result := ifIso;
Break;
end;
FFooter := 96;
if (Sector[0] = Sector[612]) and (Sector[1] = Sector[613]) then
begin
if Text <> nil then
StrCopy(Text, 'MDF');
Result := ifMdf;
Break;
end;
if Text <> nil then
StrCopy(Text, 'UNK');
Break;
end;
SetFormat(Result);
end;
constructor TIsoReader.CreateWritable(Filename: TextString; DenyWrite: Boolean = False);
begin
if FileExists(Filename) then
begin
if DenyWrite then
inherited Create(Filename, fmOpenReadWrite or fmShareDenyWrite)
else
inherited Create(Filename, fmOpenReadWrite or fmShareDenyNone);
end
else
inherited Create(Filename, fmCreate);
SetFormat();
end;
end.
|
unit fTemplateFieldEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ORCtrls, StdCtrls, ExtCtrls, Menus, ComCtrls, uTemplateFields, ORFn,
ToolWin, MenuBar, ORClasses, ORDtTm, fBase508Form, VA508AccessibilityManager;
type
TfrmTemplateFieldEditor = class(TfrmBase508Form)
pnlBottom: TPanel;
btnOK: TButton;
btnCancel: TButton;
pnlObjs: TPanel;
cbxObjs: TORComboBox;
lblObjs: TLabel;
splLeft: TSplitter;
pnlRight: TPanel;
pnlPreview: TPanel;
lblNotes: TLabel;
pnlObjInfo: TPanel;
lblName: TLabel;
lblS2: TLabel;
lblLM: TLabel;
edtName: TCaptionEdit;
splBottom: TSplitter;
lblS1: TLabel;
edtLMText: TCaptionEdit;
cbxType: TORComboBox;
lblType: TLabel;
reNotes: TRichEdit;
btnApply: TButton;
btnPreview: TButton;
mnuMain: TMainMenu;
mnuAction: TMenuItem;
mnuNew: TMenuItem;
mnuCopy: TMenuItem;
cbHide: TCheckBox;
pnlTop: TPanel;
MenuBar1: TMenuBar;
btnNew: TButton;
btnCopy: TButton;
mnuDelete: TMenuItem;
btnDelete: TButton;
mnuPreview: TMenuItem;
popText: TPopupMenu;
mnuBPUndo: TMenuItem;
N8: TMenuItem;
mnuBPCut: TMenuItem;
mnuBPCopy: TMenuItem;
mnuBPPaste: TMenuItem;
mnuBPSelectAll: TMenuItem;
N2: TMenuItem;
mnuBPCheckGrammar: TMenuItem;
mnuBPSpellCheck: TMenuItem;
lblTextLen: TLabel;
edtTextLen: TCaptionEdit;
udTextLen: TUpDown;
pnlSwap: TPanel;
edtDefault: TCaptionEdit;
pnlNum: TPanel;
edtURL: TCaptionEdit;
udDefNum: TUpDown;
edtDefNum: TCaptionEdit;
udMinVal: TUpDown;
edtMinVal: TCaptionEdit;
lblMin: TLabel;
udInc: TUpDown;
edtInc: TCaptionEdit;
lblInc: TLabel;
lblMaxVal: TLabel;
edtMaxVal: TCaptionEdit;
udMaxVal: TUpDown;
reItems: TRichEdit;
lblLength: TLabel;
edtLen: TCaptionEdit;
udLen: TUpDown;
cbxDefault: TORComboBox;
lblS3: TLabel;
gbIndent: TGroupBox;
lblIndent: TLabel;
edtIndent: TCaptionEdit;
udIndent: TUpDown;
udPad: TUpDown;
edtPad: TCaptionEdit;
lblPad: TLabel;
gbMisc: TGroupBox;
cbActive: TCheckBox;
cbRequired: TCheckBox;
cbSepLines: TCheckBox;
pnlDate: TPanel;
edtDateDef: TCaptionEdit;
cbxDateType: TORComboBox;
lblDateType: TLabel;
cbExclude: TCheckBox;
lblReq: TStaticText;
lblLine: TLabel;
lblCol: TLabel;
N14: TMenuItem;
mnuInsertTemplateField: TMenuItem;
lblCommCareLock: TLabel;
procedure cbxObjsNeedData(Sender: TObject; const StartFrom: String;
Direction, InsertAt: Integer);
procedure FormCreate(Sender: TObject);
procedure cbxObjsChange(Sender: TObject);
procedure edtNameChange(Sender: TObject);
procedure cbxTypeChange(Sender: TObject);
procedure edtLenChange(Sender: TObject);
procedure edtDefaultChange(Sender: TObject);
procedure cbxDefaultChange(Sender: TObject);
procedure edtLMTextChange(Sender: TObject);
procedure cbActiveClick(Sender: TObject);
procedure mnuNewClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure btnCancelClick(Sender: TObject);
procedure reItemsChange(Sender: TObject);
procedure cbHideClick(Sender: TObject);
procedure edtNameExit(Sender: TObject);
procedure mnuCopyClick(Sender: TObject);
procedure mnuDeleteClick(Sender: TObject);
procedure btnPreviewClick(Sender: TObject);
procedure mnuActionClick(Sender: TObject);
procedure cbRequiredClick(Sender: TObject);
procedure pnlObjsResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cbxObjsSynonymCheck(Sender: TObject; const Text: String;
var IsSynonym: Boolean);
procedure popTextPopup(Sender: TObject);
procedure mnuBPUndoClick(Sender: TObject);
procedure mnuBPCutClick(Sender: TObject);
procedure mnuBPCopyClick(Sender: TObject);
procedure mnuBPPasteClick(Sender: TObject);
procedure mnuBPSelectAllClick(Sender: TObject);
procedure mnuBPCheckGrammarClick(Sender: TObject);
procedure mnuBPSpellCheckClick(Sender: TObject);
procedure cbSepLinesClick(Sender: TObject);
procedure edtpopControlEnter(Sender: TObject);
procedure cbxObjsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtTextLenChange(Sender: TObject);
procedure edtDefNumChange(Sender: TObject);
procedure edtMinValChange(Sender: TObject);
procedure edtMaxValChange(Sender: TObject);
procedure edtIncChange(Sender: TObject);
procedure edtURLChange(Sender: TObject);
procedure edtPadChange(Sender: TObject);
procedure edtIndentChange(Sender: TObject);
procedure reNotesChange(Sender: TObject);
procedure cbxDateTypeChange(Sender: TObject);
procedure cbExcludeClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure reItemsResizeRequest(Sender: TObject; Rect: TRect);
procedure reItemsSelectionChange(Sender: TObject);
procedure mnuInsertTemplateFieldClick(Sender: TObject);
procedure ControlExit(Sender: TObject);
procedure reNotesKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
CopyFld, FFld: TTemplateField;
FUpdating: boolean;
FReloadChanges: boolean;
FChangesPending: boolean;
FDeleted: TORStringList;
FHideSynonyms: boolean;
FLastRect: TRect;
procedure UpdateControls;
procedure SyncItems(DoUpdate: boolean = TRUE);
function SaveChanges: boolean;
procedure ResetListEntry;
procedure VerifyName;
procedure EnableButtons;
procedure SetFld(const Value: TTemplateField);
procedure SetHideSynonyms(const Value: boolean);
function GetPopupControl: TCustomEdit;
function IsCommunityCare: boolean;
public
{ Public declarations }
end;
function EditDialogFields: boolean;
implementation
uses rTemplates, fTemplateDialog, Clipbrd, uSpell, uConst, System.UITypes,
fTemplateFields, VAUtils;
{$R *.DFM}
{ TfrmDlgObjEditor }
var
frmTemplateFields: TfrmTemplateFields = nil;
function EditDialogFields: boolean;
var
frmTemplateFieldEditor: TfrmTemplateFieldEditor;
begin
frmTemplateFieldEditor := TfrmTemplateFieldEditor.Create(Application);
try
frmTemplateFieldEditor.ShowModal;
Result := frmTemplateFieldEditor.FReloadChanges;
finally
frmTemplateFieldEditor.Free;
end;
end;
procedure TfrmTemplateFieldEditor.UpdateControls;
const
DefTxt = 'Default:';
var
ok, edt, txt, tmp: boolean;
Y, idx, Max: integer;
wpTxt: string;
procedure SetLbl(const Text: string);
var
lbl: TLabel;
begin
inc(idx);
case idx of
1: lbl := lblS1;
2: lbl := lblS2;
3: lbl := lblS3;
else
lbl := nil;
end;
if assigned(lbl) then
lbl.Caption := Text;
end;
procedure SetY(Control: TControl; const Text: string);
begin
if (Control.Visible) then
begin
Control.Top := Y;
inc(Y, Control.Height);
SetLbl(Text);
end;
end;
begin
if(not FUpdating) then
begin
FUpdating := TRUE;
try
Y := 0;
idx := 0;
ok := assigned(FFld);
if(ok) then
begin
edt := (FFld.FldType in EditLenTypes);
txt := (FFld.FldType in EditDfltTypes);
end
else
begin
edt := FALSE;
txt := FALSE;
end;
lblName.Enabled := ok;
edtName.Enabled := ok;
lblType.Enabled := ok;
cbxType.Enabled := ok;
lblLM.Enabled := ok;
edtLMText.Enabled := ok;
cbActive.Enabled := ok;
gbMisc.Enabled := ok;
lblNotes.Enabled := ok;
reNotes.Enabled := ok;
if(ok) then
begin
edtName.Text := FFld.FldName;
cbxType.ItemIndex := ord(FFld.FldType);
edtLMText.Text := FFld.LMText;
cbActive.Checked := FFld.Inactive;
reNotes.Lines.Text := FFld.Notes;
end
else
begin
edtName.Text := '';
cbxType.ItemIndex := -1;
edtLMText.Text := '';
cbActive.Checked := FALSE;
reNotes.Clear;
end;
tmp := ok and (not (FFld.FldType in NoRequired));
cbRequired.Enabled := tmp;
if tmp then
cbRequired.Checked := FFld.Required
else
cbRequired.Checked := FALSE;
pnlSwap.DisableAlign;
try
tmp := ok and (FFld.FldType in SepLinesTypes);
cbSepLines.Enabled := tmp;
if tmp then
cbSepLines.Checked := FFld.SepLines
else
cbSepLines.Checked := FALSE;
tmp := ok and (FFld.FldType in ExcludeText);
cbExclude.Enabled := tmp;
if tmp then
cbExclude.Checked := FFld.SepLines
else
cbExclude.Checked := FALSE;
lblLength.Enabled := edt;
if ok and (FFld.FldType = dftWP) then
begin
lblTextLen.Caption := 'Num Lines:';
udLen.Min := 5;
udLen.Max := 74;
udTextLen.Min := 2;
udTextLen.Max := MaxTFWPLines;
end
else
begin
udLen.Min := 1;
udLen.Max := 70;
udTextLen.Min := 0;
udTextLen.Max := 240;
lblTextLen.Caption := 'Text Len:';
end;
lblTextLen.Enabled := edt;
edtTextLen.Enabled := edt;
udTextLen.Enabled := edt;
edtLen.Enabled := edt;
udLen.Enabled := edt;
edtDefault.Visible := txt;
SetY(edtDefault, DefTxt);
Max := MaxTFEdtLen;
if(edt) then
begin
udLen.Associate := edtLen;
udLen.Position := FFld.MaxLen;
udTextLen.Associate := edtTextLen;
udTextLen.Position := FFld.TextLen;
if txt then
Max := FFld.MaxLen;
end
else
begin
udLen.Associate := nil;
edtLen.Text := '';
udTextLen.Associate := nil;
edtTextLen.Text := '';
end;
if txt then
begin
edtDefault.MaxLength := Max;
edtDefault.Text := copy(FFld.EditDefault, 1, Max);
end;
gbIndent.Enabled := ok;
lblIndent.Enabled := ok;
edtIndent.Enabled := ok;
udIndent.Enabled := ok;
if ok then
begin
udIndent.Associate := edtIndent;
udIndent.Position := FFld.Indent;
end
else
begin
udIndent.Associate := nil;
edtIndent.Text := '';
end;
tmp := ok and (not cbExclude.Checked);
lblPad.Enabled := tmp;
edtPad.Enabled := tmp;
udPad.Enabled := tmp;
if tmp then
begin
udPad.Associate := edtPad;
udPad.Position := FFld.Pad;
end
else
begin
udPad.Associate := nil;
edtPad.Text := '';
end;
tmp := ok and (FFld.FldType = dftNumber);
pnlNum.Visible := tmp;
SetY(pnlNum, DefTxt);
if tmp then
begin
udDefNum.Position := StrToIntDef(FFld.EditDefault, 0);
udMinVal.Position := FFld.MinVal;
udMaxVal.Position := FFld.MaxVal;
udInc.Position := FFld.Increment;
end;
tmp := ok and (FFld.FldType = dftDate);
pnlDate.Visible := tmp;
SetY(pnlDate, DefTxt);
if tmp then
begin
edtDateDef.Text := FFld.EditDefault;
cbxDateType.SelectByID(TemplateFieldDateCodes[FFld.DateType]);
end;
tmp := ok and (FFld.FldType in ItemDfltTypes);
cbxDefault.Visible := tmp;
SetY(cbxDefault, DefTxt);
tmp := ok and (FFld.FldType = dftHyperlink);
edtURL.Visible := tmp;
SetY(edtURL, 'Address:');
if tmp then
edtURL.Text := FFld.URL;
tmp := ok and (FFld.FldType in FldItemTypes);
reItems.Visible := tmp;
lblLine.Visible := tmp;
lblCol.Visible := tmp;
if tmp then
begin
if FFld.FldType = dftWP then
wpTxt := DefTxt
else
wpTxt := 'Items:';
end
else
wpTxt := '';
SetY(reItems, wpTxt);
if tmp then
reItems.Lines.Text := FFld.Items
else
reItems.Clear;
if ok then
begin
if FFld.CommunityCare then
lblCommCareLock.Visible := True
else
lblCommCareLock.Visible := False;
end
finally
pnlSwap.EnableAlign;
end;
SetLbl('');
SetLbl('');
SetLbl('');
SyncItems(FALSE);
FormResize(Self);
finally
FUpdating := FALSE;
end;
end;
end;
procedure TfrmTemplateFieldEditor.SyncItems(DoUpdate: boolean = TRUE);
var
i, idx, Siz, Max1, Max2: integer;
ChangeSizes: boolean;
begin
if DoUpdate and FUpdating then
exit;
Max1 := 0;
Max2 := 0;
ChangeSizes := FALSE;
FUpdating := TRUE;
try
cbxDefault.Items.Assign(reItems.Lines);
idx := -1;
if(assigned(FFld)) and reItems.Visible and cbxDefault.Visible then
begin
ChangeSizes := TRUE;
for i := 0 to reItems.Lines.Count-1 do
begin
Siz := length(StripEmbedded(reItems.Lines[i]));
if Max1 < Siz then
Max1 := Siz;
if(idx < 0) and (FFld.ItemDefault = reItems.Lines[i]) then
idx := i;
end;
Max2 := Max1;
if Max1 > MaxTFEdtLen then
Max1 := MaxTFEdtLen;
end;
cbxDefault.ItemIndex := idx;
finally
FUpdating := FALSE;
end;
if ChangeSizes and DoUpdate then
begin
udLen.Position := Max1;
if (not udTextLen.Enabled) or
((udTextLen.Position > 0) and (udTextLen.Position < Max2)) then
udTextLen.Position := Max2;
end;
end;
procedure TfrmTemplateFieldEditor.cbxObjsNeedData(Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer);
var
tmp: TORStringList;
i, idx: Integer;
begin
tmp := TORStringList.Create;
try
SubSetOfTemplateFields(StartFrom, Direction, tmp);
for i := 0 to FDeleted.Count - 1 do
begin
idx := tmp.IndexOfPiece(Piece(FDeleted[i], U, 1), U, 1);
if (idx >= 0) then
tmp.delete(idx);
end;
ConvertCodes2Text(tmp, FALSE);
cbxObjs.ForDataUse(tmp);
finally
FreeAndNil(tmp);
end;
end;
procedure TfrmTemplateFieldEditor.FormCreate(Sender: TObject);
var
i: integer;
Child: TControl;
Overage: integer;
begin
FDeleted := TORStringList.Create;
FHideSynonyms := TRUE;
cbxObjs.InitLongList('');
cbxObjs.ItemHeight := 15;
UpdateControls;
ResizeAnchoredFormToFont(self);
//ResizeAnchoredFormToFont does the pnlObjInfo panel wrong. So we fix it here.
gbMisc.Top := pnlObjInfo.ClientHeight - gbMisc.Height - 5;
gbIndent.Top := gbMisc.Top;
edtLMText.Top := gbMisc.Top - edtLMText.Height - 2;
lblLM.Top := edtLMText.Top + 5;
pnlSwap.Height := lblLM.Top - pnlSwap.Top;
Overage := edtName.Left + edtName.Width - pnlObjInfo.ClientWidth - 4;
for i := 0 to pnlObjInfo.ControlCount-1 do begin
Child := pnlObjInfo.Controls[i];
if (akRight in Child.Anchors) then begin
if (akLeft in Child.Anchors) then
Child.Width := Child.Width - Overage
else
Child.Left := Child.Left - Overage;
end;
end;
end;
procedure TfrmTemplateFieldEditor.cbxObjsChange(Sender: TObject);
begin
if(cbxObjs.ItemIEN <> 0) then
SetFld(GetTemplateField(cbxObjs.ItemID, TRUE))
else
SetFld(nil);
UpdateControls;
IsCommunityCare;
end;
procedure TfrmTemplateFieldEditor.edtNameChange(Sender: TObject);
var
ok: boolean;
begin
if(not FUpdating) and (assigned(FFld)) then
begin
if (not FFld.NameChanged) and (not FFld.NewField) then
begin
ok := InfoBox('*** WARNING ***' + CRLF + CRLF +
'This template field has been saved, and may have been used in one or more' + CRLF +
'boilerplates. Boilerplates can be found in templates, titles, reasons for request' + CRLF +
'and reminder dialogs. Renaming this template field will cause any boilerplates' + CRLF +
'that use it to no longer function correctly.' + CRLF + CRLF +
'Are you sure you want to rename the ' + FFld.FldName + ' template field?',
'Warning', MB_YESNO or MB_ICONWARNING) = IDYES;
if ok then
InfoBox('Template field will be renamed when OK or Apply is pressed.', 'Information', MB_OK or MB_ICONINFORMATION)
else
begin
FUpdating := TRUE;
try
edtName.Text := FFld.FldName;
finally
FUpdating := FALSE;
end;
end;
end
else
ok := TRUE;
if ok then
begin
FFld.FldName := edtName.Text;
edtName.Text := FFld.FldName;
FChangesPending := TRUE;
ResetListEntry;
end;
end;
end;
procedure TfrmTemplateFieldEditor.cbxTypeChange(Sender: TObject);
begin
if(not FUpdating) and (assigned(FFld)) then
begin
if(cbxType.ItemIndex < 0) then
begin
FUpdating := TRUE;
try
cbxType.ItemIndex := 0;
finally
FUpdating := FALSE;
end;
end;
FFld.FldType := TTemplateFieldType(cbxType.ItemIndex);
end;
EnableButtons;
UpdateControls;
end;
procedure TfrmTemplateFieldEditor.edtLenChange(Sender: TObject);
var
v: integer;
ok: boolean;
begin
EnsureText(edtLen, udLen);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType in (EditLenTypes))) then
begin
EnsureText(edtLen, udLen);
FFld.MaxLen := udLen.Position;
udLen.Position := FFld.MaxLen;
if edtDefault.Visible then
begin
edtDefault.MaxLength := FFld.MaxLen;
edtDefault.Text := copy(edtDefault.Text,1,FFld.MaxLen);
end;
case FFLd.FldType of
dftEditBox: ok := TRUE;
dftComboBox: ok := (udTextLen.Position > 0);
else ok := FALSE;
end;
if ok then
begin
v := udLen.Position;
if udTextLen.Position < v then
udTextLen.Position := v;
end;
end;
end;
procedure TfrmTemplateFieldEditor.edtDefaultChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType in EditDfltType2)) then
begin
FFld.EditDefault := TEdit(Sender).Text;
TEdit(Sender).Text := FFld.EditDefault;
end;
end;
procedure TfrmTemplateFieldEditor.cbxDefaultChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType in ItemDfltTypes)) then
begin
FFld.ItemDefault := cbxDefault.Text;
SyncItems;
end;
end;
procedure TfrmTemplateFieldEditor.edtLMTextChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.LMText := edtLMText.Text;
edtLMText.Text := FFld.LMText;
end;
end;
procedure TfrmTemplateFieldEditor.cbActiveClick(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.Inactive := cbActive.Checked;
cbActive.Checked := FFld.Inactive;
FChangesPending := TRUE;
//ResetListEntry;
end;
end;
procedure TfrmTemplateFieldEditor.mnuNewClick(Sender: TObject);
begin
SetFld(TTemplateField.Create(nil));
if(assigned(FFld)) then
begin
FChangesPending := TRUE;
if cbxObjs.ShortCount = 0 then
begin
cbxObjs.Items.Insert(0,LLS_LINE);
cbxObjs.Items.Insert(1,'');
end;
if(assigned(CopyFld)) then
FFld.Assign(CopyFld);
cbxObjs.Items.Insert(0,FFld.ID + U + FFld.FldName);
cbxObjs.SelectByID(FFld.ID);
cbxObjsChange(nil);
if(assigned(FFld)) then
edtName.SetFocus;
end
else
UpdateControls;
end;
procedure TfrmTemplateFieldEditor.btnOKClick(Sender: TObject);
begin
SaveChanges;
end;
procedure TfrmTemplateFieldEditor.btnApplyClick(Sender: TObject);
var
tmp: string;
begin
SaveChanges;
cbxObjs.Clear;
if assigned(FFld) then
tmp := FFld.FldName
else
tmp := '';
cbxObjs.InitLongList(tmp);
cbxObjs.ItemIndex := 0;
cbxObjsChange(cbxObjs);
end;
procedure TfrmTemplateFieldEditor.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
var
ans: word;
begin
if(AnyTemplateFieldsModified) then
begin
ans := InfoBox('Save Changes?', 'Confirmation', MB_YESNOCANCEL or MB_ICONQUESTION);
if(ans = IDCANCEL) then
CanClose := FALSE
else
if(ans = IDYES) then
CanClose := SaveChanges;
end;
end;
procedure TfrmTemplateFieldEditor.btnCancelClick(Sender: TObject);
var
i: integer;
begin
for i := 0 to FDeleted.Count-1 do
UnlockTemplateField(Piece(FDeleted[i],U,1));
FDeleted.Clear;
ClearModifiedTemplateFields;
end;
function TfrmTemplateFieldEditor.SaveChanges: boolean;
var
ans: word;
Errors: string;
i: integer;
begin
for i := 0 to FDeleted.Count-1 do
DeleteTemplateField(Piece(FDeleted[i],U,1));
FDeleted.Clear;
Result := TRUE;
Errors := SaveTemplateFieldErrors;
if(Errors <> '') then
begin
ans := InfoBox(Errors + CRLF + CRLF + 'Cancel changes to these Template Fields?',
'Confirmation', MB_YESNO or MB_ICONQUESTION);
if(ans = IDYES) then
ClearModifiedTemplateFields
else
Result := FALSE;
end;
if(FChangesPending) then
FReloadChanges := TRUE;
end;
procedure TfrmTemplateFieldEditor.reItemsChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType in FldItemTypes)) then
begin
FFld.Items := reItems.Lines.Text;
SyncItems;
end;
end;
procedure TfrmTemplateFieldEditor.cbHideClick(Sender: TObject);
begin
SetHideSynonyms(cbHide.Checked);
end;
procedure TfrmTemplateFieldEditor.edtNameExit(Sender: TObject);
begin
if (ActiveControl <> btnCancel) and (ActiveControl <> btnDelete) then
VerifyName;
end;
procedure TfrmTemplateFieldEditor.VerifyName;
var
bad: boolean;
begin
if assigned(FFld) then
begin
if FDeleted.IndexOfPiece(FFld.FldName, U, 2) >= 0 then
begin
ShowMsg('Template field can not be named the same as a deleted' + CRLF +
'field until OK or Apply has been pressed.');
bad := TRUE;
end
else
bad := TemplateFieldNameProblem(FFld);
if bad then
edtName.SetFocus;
end;
end;
procedure TfrmTemplateFieldEditor.mnuCopyClick(Sender: TObject);
begin
if assigned(FFld) then
begin
CopyFld := FFld;
try
mnuNewClick(nil);
finally
CopyFld := nil;
end;
end;
end;
procedure TfrmTemplateFieldEditor.SetFld(const Value: TTemplateField);
begin
FFld := Value;
EnableButtons;
end;
procedure TfrmTemplateFieldEditor.mnuDeleteClick(Sender: TObject);
var
idx: integer;
ok: boolean;
Answer: word;
txt: string;
btns: TMsgDlgButtons;
begin
if assigned(FFld) then
begin
ok := (FFld.NewField);
if not ok then
begin
btns := [mbYes, mbNo];
if FFld.Inactive then
txt := ''
else
begin
txt := ' Rather than deleting, you may want' + CRLF +
'to inactivate this template field instead. You may inactivate this template by' + CRLF +
'pressing the Ignore button now.';
include(btns, mbIgnore);
end;
Answer := MessageDlg('*** WARNING ***' + CRLF + CRLF +
'This template field has been saved, and may have been used in one or more' + CRLF +
'boilerplates. Boilerplates can be found in templates, titles, reasons for request' + CRLF +
'and reminder dialogs. Deleting this template field will cause any boilerplates' + CRLF +
'that use it to no longer function correctly.' + txt + CRLF + CRLF +
'Are you sure you want to delete the ' + FFld.FldName + ' template field?',
mtWarning, btns, 0);
ok := (Answer = mrYes);
if(Answer = mrIgnore) then
cbActive.Checked := TRUE;
end;
if ok then
begin
if(FFld.NewField or FFld.CanModify) then
begin
if FFld.NewField then
begin
idx := cbxObjs.ItemIndex;
cbxObjs.ItemIndex := -1;
cbxObjs.Items.Delete(idx);
if cbxObjs.Items[0] = LLS_LINE then
begin
cbxObjs.Items.Delete(1);
cbxObjs.Items.Delete(0);
end;
end
else
begin
FDeleted.Add(FFld.ID + U + FFld.FldName);
cbxObjs.ItemIndex := -1;
end;
end;
FFld.Free;
SetFld(nil);
UpdateControls;
cbxObjs.InitLongList('');
FChangesPending := TRUE;
end;
end;
end;
procedure TfrmTemplateFieldEditor.ResetListEntry;
var
txt: string;
begin
if(assigned(FFld) and FFld.NewField and (cbxObjs.ItemIndex >= 0)) then
begin
txt := FFld.ID + U + FFld.FldName;
//if(FFld.Inactive) then
//txt := txt + ' <Inactive>';
cbxObjs.Items[cbxObjs.ItemIndex] := txt;
cbxObjs.ItemIndex := cbxObjs.ItemIndex;
end;
end;
procedure TfrmTemplateFieldEditor.btnPreviewClick(Sender: TObject);
var
TmpSL: TStringList;
begin
if(assigned(FFld)) then
begin
TmpSL := TStringList.Create;
try
TmpSL.Add(TemplateFieldBeginSignature + FFld.FldName + TemplateFieldEndSignature);
CheckBoilerplate4Fields(TmpSL, 'Preview Template Field: ' + FFld.FldName, TRUE);
finally
TmpSL.Free;
end;
end;
end;
function TfrmTemplateFieldEditor.IsCommunityCare: boolean;
procedure ApplyCommunityCareLock(AllowEdit: Boolean; aCtrl: TWinControl);
var
I:integer;
begin
for i := 0 to aCtrl.ControlCount - 1 do
begin
if aCtrl.Controls[i] is TWinControl then
begin
if TWinControl(aCtrl.Controls[i]).ControlCount > 0 then
ApplyCommunityCareLock(AllowEdit, TWinControl(aCtrl.Controls[i]));
TWinControl(aCtrl.Controls[i]).Enabled := AllowEdit;
end;
end;
end;
var
HasAccess: Boolean;
begin
if assigned(FFld) then
HasAccess := FFld.CommunityCare
else
HasAccess := False;
Result := not HasAccess;
ApplyCommunityCareLock(not HasAccess, pnlRight);
btnOK.Enabled := not HasAccess;
btnApply.Enabled := not HasAccess;
end;
procedure TfrmTemplateFieldEditor.EnableButtons;
begin
btnCopy.Enabled := assigned(FFld) and not FFld.CommunityCare;
mnuCopy.Enabled := btnCopy.Enabled;
btnDelete.Enabled := btnCopy.Enabled; // (assigned(FFld) and FFld.NewField);
mnuDelete.Enabled := btnDelete.Enabled;
btnPreview.Enabled := assigned(FFld) and (FFld.FldType <> dftUnknown);
mnuPreview.Enabled := btnPreview.Enabled;
end;
procedure TfrmTemplateFieldEditor.mnuActionClick(Sender: TObject);
begin
EnableButtons;
end;
procedure TfrmTemplateFieldEditor.cbRequiredClick(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.Required := cbRequired.Checked;
cbRequired.Checked := FFld.Required;
end;
end;
procedure TfrmTemplateFieldEditor.pnlObjsResize(Sender: TObject);
begin
btnPreview.Left := pnlRight.Left;
end;
procedure TfrmTemplateFieldEditor.FormDestroy(Sender: TObject);
begin
FDeleted.Free;
if(assigned(frmTemplateFields)) then begin
frmTemplateFields.FRee;
frmTemplateFields := nil;
end; {if}
end;
procedure TfrmTemplateFieldEditor.SetHideSynonyms(const Value: boolean);
begin
FHideSynonyms := Value;
cbxObjs.HideSynonyms := FALSE; // Refresh Display
cbxObjs.HideSynonyms := TRUE;
end;
procedure TfrmTemplateFieldEditor.cbxObjsSynonymCheck(Sender: TObject;
const Text: String; var IsSynonym: Boolean);
begin
if not FHideSynonyms then
IsSynonym := FALSE;
if(FDeleted.Count > 0) and (FDeleted.IndexOfPiece(Text,U,2) >= 0) then
IsSynonym := TRUE;
end;
procedure TfrmTemplateFieldEditor.popTextPopup(Sender: TObject);
var
HasText, CanEdit, isre: boolean;
ce: TCustomEdit;
ShowTempField: boolean;
begin
ce := GetPopupControl;
if assigned(ce) then
begin
isre := (ce is TRichEdit);
CanEdit := (not TORExposedCustomEdit(ce).ReadOnly);
mnuBPUndo.Enabled := (CanEdit and (ce.Perform(EM_CANUNDO, 0, 0) <> 0));
if isre then
HasText := (TRichEdit(ce).Lines.Count > 0)
else
HasText := (Text <> '');
mnuBPSelectAll.Enabled := HasText;
mnuBPCopy.Enabled := HasText and (ce.SelLength > 0);
mnuBPPaste.Enabled := (CanEdit and Clipboard.HasFormat(CF_TEXT));
mnuBPCut.Enabled := (CanEdit and HasText and (ce.SelLength > 0));
ShowTempField := FALSE;
if CanEdit then
if (not assigned(frmTemplateFields)) or
(assigned(frmTemplateFields) and not frmTemplateFields.Visible) then
if (ce = reItems) or
(ce = edtDefault) then
ShowTempField := TRUE;
mnuInsertTemplateField.Enabled := ShowTempField;
end
else
begin
isre := FALSE;
HasText := FALSE;
CanEdit := FALSE;
mnuBPPaste.Enabled := FALSE;
mnuBPCopy.Enabled := FALSE;
mnuBPCut.Enabled := FALSE;
mnuBPSelectAll.Enabled := FALSE;
mnuBPUndo.Enabled := FALSE;
mnuInsertTemplateField.Enabled := FALSE;
end;
mnuBPSpellCheck.Visible := isre;
mnuBPCheckGrammar.Visible := isre;
if isre and HasText and CanEdit then
begin
mnuBPSpellCheck.Enabled := SpellCheckAvailable;
mnuBPCheckGrammar.Enabled := SpellCheckAvailable;
end
else
begin
mnuBPSpellCheck.Enabled := FALSE;
mnuBPCheckGrammar.Enabled := FALSE;
end;
end;
function TfrmTemplateFieldEditor.GetPopupControl: TCustomEdit;
begin
if assigned(popText.PopupComponent) and (popText.PopupComponent is TCustomEdit) then
Result := TCustomEdit(popText.PopupComponent)
else
Result := nil;
end;
procedure TfrmTemplateFieldEditor.mnuBPUndoClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if assigned(ce) then
ce.Perform(EM_UNDO, 0, 0);
end;
procedure TfrmTemplateFieldEditor.mnuBPCutClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if assigned(ce) then
ce.CutToClipboard;
end;
procedure TfrmTemplateFieldEditor.mnuBPCopyClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if assigned(ce) then
ce.CopyToClipboard;
end;
procedure TfrmTemplateFieldEditor.mnuBPPasteClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if assigned(ce) then
ce.SelText := Clipboard.AsText;
end;
procedure TfrmTemplateFieldEditor.mnuBPSelectAllClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if assigned(ce) then
ce.SelectAll;
end;
procedure TfrmTemplateFieldEditor.mnuBPCheckGrammarClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if(assigned(ce) and (ce is TRichEdit)) then
GrammarCheckForControl(TRichEdit(ce));
end;
procedure TfrmTemplateFieldEditor.mnuBPSpellCheckClick(Sender: TObject);
var
ce: TCustomEdit;
begin
ce := GetPopupControl;
if(assigned(ce) and (ce is TRichEdit)) then
SpellCheckForControl(TRichEdit(ce));
end;
procedure TfrmTemplateFieldEditor.cbSepLinesClick(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.SepLines := cbSepLines.Checked;
cbSepLines.Checked := FFld.SepLines;
end;
end;
procedure TfrmTemplateFieldEditor.edtpopControlEnter(Sender: TObject);
begin
popText.PopupComponent := TComponent(Sender);
if assigned(frmTemplateFields) then
begin
if ((Sender = reItems) or (Sender = edtDefault)) then
begin
frmTemplateFields.btnInsert.Enabled := TRUE;
if Sender = reItems then
frmTemplateFields.re := reItems
else
frmTemplateFields.re := edtDefault;
end
else
frmTemplateFields.btnInsert.Enabled := FALSE;
end;
end;
procedure TfrmTemplateFieldEditor.cbxObjsKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if(Key = VK_DELETE) and btnDelete.Enabled then
mnuDeleteClick(btnDelete);
end;
procedure TfrmTemplateFieldEditor.edtTextLenChange(Sender: TObject);
var
v: integer;
begin
EnsureText(edtTextLen, udTextLen);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType in EditLenTypes)) then
begin
FFld.TextLen := udTextLen.Position;
udTextLen.Position := FFld.TextLen;
if FFld.FldType = dftEditBox then
begin
v := udTextLen.Position;
if udLen.Position > v then
udLen.Position := v;
end;
end;
end;
procedure TfrmTemplateFieldEditor.edtDefNumChange(Sender: TObject);
var
v: integer;
begin
EnsureText(edtDefNum, udDefNum);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftNumber)) then
begin
FFld.EditDefault := IntToStr(udDefNum.Position);
udDefNum.Position := StrToIntDef(FFld.EditDefault, 0);
v := udDefNum.Position;
if udMinVal.Position > v then
udMinVal.Position := v;
if udMaxVal.Position < v then
udMaxVal.Position := v;
end;
end;
procedure TfrmTemplateFieldEditor.edtMinValChange(Sender: TObject);
var
v: integer;
begin
EnsureText(edtMinVal, udMinVal);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftNumber)) then
begin
FFld.MinVal := udMinVal.Position;
udMinVal.Position := FFld.MinVal;
v := udMinVal.Position;
if udDefNum.Position < v then
udDefNum.Position := v;
if udMaxVal.Position < v then
udMaxVal.Position := v;
end;
end;
procedure TfrmTemplateFieldEditor.edtMaxValChange(Sender: TObject);
var
v: integer;
begin
EnsureText(edtMaxVal, udMaxVal);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftNumber)) then
begin
FFld.MaxVal := udMaxVal.Position;
udMaxVal.Position := FFld.MaxVal;
v := udMaxVal.Position;
if udDefNum.Position > v then
udDefNum.Position := v;
if udMinVal.Position > v then
udMinVal.Position := v;
end;
end;
procedure TfrmTemplateFieldEditor.edtIncChange(Sender: TObject);
begin
EnsureText(edtInc, udInc);
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftNumber)) then
begin
FFld.Increment := udInc.Position;
udInc.Position := FFld.Increment;
end;
end;
procedure TfrmTemplateFieldEditor.edtURLChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftHyperlink)) then
begin
FFld.URL := edtURL.Text;
edtURL.Text := FFld.URL;
end;
end;
procedure TfrmTemplateFieldEditor.edtPadChange(Sender: TObject);
begin
EnsureText(edtPad, udPad);
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.Pad := udPad.Position;
udPad.Position := FFld.Pad;
end;
end;
procedure TfrmTemplateFieldEditor.edtIndentChange(Sender: TObject);
begin
EnsureText(edtIndent, udIndent);
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.Indent := udIndent.Position;
udIndent.Position := FFld.Indent;
end;
end;
procedure TfrmTemplateFieldEditor.reNotesChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and FFld.CanModify) then
FFld.Notes := reNotes.Lines.Text;
end;
procedure TfrmTemplateFieldEditor.cbxDateTypeChange(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld)) and (FFld.FldType = dftDate)) then
begin
if cbxDateType.ItemIndex >= 0 then
FFld.DateType := TTmplFldDateType(cbxDateType.ItemIndex + 1)
else
FFld.DateType := dtDate;
cbxDateType.SelectByID(TemplateFieldDateCodes[FFld.DateType]);
end;
end;
procedure TfrmTemplateFieldEditor.cbExcludeClick(Sender: TObject);
begin
if((not FUpdating) and (assigned(FFld))) then
begin
FFld.SepLines := cbExclude.Checked;
cbExclude.Checked := FFld.SepLines;
UpdateControls;
end;
end;
procedure TfrmTemplateFieldEditor.FormResize(Sender: TObject);
begin
LimitEditWidth(reItems, 240);
LimitEditWidth(reNotes, MAX_ENTRY_WIDTH);
end;
procedure TfrmTemplateFieldEditor.reItemsResizeRequest(Sender: TObject;
Rect: TRect);
var
R: TRect;
begin
R := TRichEdit(Sender).ClientRect;
if (FLastRect.Right <> R.Right) or
(FLastRect.Bottom <> R.Bottom) or
(FLastRect.Left <> R.Left) or
(FLastRect.Top <> R.Top) then
begin
FLastRect := R;
FormResize(Self);
end;
end;
procedure TfrmTemplateFieldEditor.reItemsSelectionChange(Sender: TObject);
var
p: TPoint;
begin
if lblLine.Visible then
begin
p := reItems.CaretPos;
lblLine.Caption := 'Line: ' + inttostr(p.y + 1);
lblCol.Caption := 'Col: ' + inttostr(p.x + 1);
end;
end;
procedure TfrmTemplateFieldEditor.mnuInsertTemplateFieldClick(Sender: TObject);
var
iCon: TCustomEdit;
ShowButton: boolean;
begin
iCon := GetPopupControl;
if iCon <> nil then
begin
if iCon.Name <> ActiveControl.Name then
begin
ActiveControl := iCon;
iCon.SelStart := iCon.SelLength;
end;
if (not assigned(frmTemplateFields)) then
begin
frmTemplateFields := TfrmTemplateFields.Create(Self);
frmTemplateFields.Font := Font;
end;
ShowButton := False;
if iCon = reItems then
begin
frmTemplateFields.re := reItems;
ShowButton := TRUE;
end
else if iCon = edtDefault then
begin
frmTemplateFields.re := edtDefault;
ShowButton := TRUE;
end;
frmTemplateFields.btnInsert.Enabled := ShowButton;
frmTemplateFields.Show;
end
end;
procedure TfrmTemplateFieldEditor.ControlExit(Sender: TObject);
begin
if assigned(frmTemplateFields) then
frmTemplateFields.btnInsert.Enabled := FALSE;
end;
procedure TfrmTemplateFieldEditor.reNotesKeyUp(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key = VK_TAB) then
begin
if ssShift in Shift then
begin
FindNextControl(Sender as TWinControl, False, True, False).SetFocus; //previous control
Key := 0;
end
else if ssCtrl in Shift then
begin
FindNextControl(Sender as TWinControl, True, True, False).SetFocus; //next control
Key := 0;
end;
end;
if (key = VK_ESCAPE) then begin
FindNextControl(Sender as TWinControl, False, True, False).SetFocus; //previous control
key := 0;
end;
end;
end.
|
unit OrderQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, DragHelper, System.Generics.Collections,
DSWrap, BaseEventsQuery;
type
TOrderW = class(TDSWrap)
protected
FOrd: TFieldWrap;
public
property Ord: TFieldWrap read FOrd;
end;
TQueryOrder = class(TQueryBaseEvents)
private
FRecOrderList: TList<TRecOrder>;
function GetOrderW: TOrderW;
{ Private declarations }
protected
procedure DoOnUpdateOrder(ARecOrder: TRecOrder);
procedure UpdateOrder;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure MoveDSRecord(AStartDrag: TStartDrag; ADropDrag: TDropDrag);
property OrderW: TOrderW read GetOrderW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses System.Math, System.Generics.Defaults;
constructor TQueryOrder.Create(AOwner: TComponent);
begin
inherited;
FRecOrderList := TList<TRecOrder>.Create;
end;
destructor TQueryOrder.Destroy;
begin
FreeAndNil(FRecOrderList);
inherited;
end;
procedure TQueryOrder.DoOnUpdateOrder(ARecOrder: TRecOrder);
begin
OrderW.Ord.F.Value := ARecOrder.Order;
end;
function TQueryOrder.GetOrderW: TOrderW;
begin
Assert(FDSWrap <> nil);
Result := FDSWrap as TOrderW;
Assert(Result.Ord <> nil);
end;
procedure TQueryOrder.MoveDSRecord(AStartDrag: TStartDrag;
ADropDrag: TDropDrag);
var
AClone: TFDMemTable;
AClone2: TFDMemTable;
AKeyField: TField;
ANewOrderValue: Integer;
ANewRecNo: Integer;
AOrderField: TField;
AOrderField2: TField;
I: Integer;
IsDown: Boolean;
IsUp: Boolean;
k: Integer;
OK: Boolean;
Sign: Integer;
begin
for I := 0 to FRecOrderList.Count - 1 do
FRecOrderList[I].Free;
FRecOrderList.Clear;
// Готовимся обновить порядок параметров
AClone := TFDMemTable.Create(Self);
AClone2 := TFDMemTable.Create(Self);
try
// Важно!!! Клоны должны быть отсортированы так же как строки на экране
AClone.CloneCursor(FDQuery);
AClone.IndexFieldNames := OrderW.Ord.FieldName;
AClone.First;
AClone2.CloneCursor(FDQuery);
AClone2.IndexFieldNames := OrderW.Ord.FieldName;
AClone2.First;
// Если был перенос вверх
IsUp := (ADropDrag.OrderValue < AStartDrag.MinOrderValue);
// Если был перенос вниз
IsDown := not IsUp;
AOrderField := AClone.FieldByName(OrderW.Ord.FieldName);
AOrderField2 := AClone2.FieldByName(OrderW.Ord.FieldName);
AKeyField := AClone.FieldByName(Wrap.PKFieldName);
while not AClone.Eof do
begin
Sign := 0;
// Если перетаскиваем вверх
if IsUp and (AOrderField.AsInteger >= ADropDrag.OrderValue) and
(AOrderField.AsInteger < AStartDrag.MinOrderValue) then
Sign := 1;
// Если перетаскиваем вниз
if IsDown and (AOrderField.AsInteger <= ADropDrag.OrderValue) and
(AOrderField.AsInteger > AStartDrag.MaxOrderValue) then
Sign := -1;
// Если текущую запись нужно сместить
if Sign <> 0 then
begin
OK := AClone2.LocateEx(Wrap.PKFieldName, AKeyField.Value, []);
Assert(OK);
// Находим смещение
ANewRecNo := AClone2.RecNo + Sign * Length(AStartDrag.Keys);
Assert((ANewRecNo >= 1) and (ANewRecNo <= AClone2.RecordCount));
AClone2.RecNo := ANewRecNo;
// Пока уходим в отрицательную сторону
FRecOrderList.Add(TRecOrder.Create(AKeyField.AsInteger,
-AOrderField2.AsInteger));
// Запоминаем, что нужно изменить
// FRecOrderList.Add(TRecOrder.Create(AKeyField.AsInteger, AOrderField.AsInteger + Sign *
// Length(AStartDrag.Keys)));
end;
AClone.Next;
end;
// ANewOrderValue := ADropDrag.OrderValue;
// if IsDown then
// ANewOrderValue := ADropDrag.OrderValue - Length(AStartDrag.Keys) + 1;
OK := AClone2.LocateEx(Wrap.PKFieldName, ADropDrag.Key, []);
Assert(OK);
if IsUp then
TArray.Sort<Integer>(AStartDrag.Keys)
else
TArray.Sort<Integer>(AStartDrag.Keys, TComparer<Integer>.Construct(
function(const Left, Right: Integer): Integer
begin
Result := Right - Left;
end));
for I := Low(AStartDrag.Keys) to High(AStartDrag.Keys) do
begin
// Запоминаем, что нужно изменить
FRecOrderList.Add(TRecOrder.Create(AStartDrag.Keys[I],
AOrderField2.AsInteger));
ANewRecNo := IfThen(IsUp, AClone2.RecNo + 1, AClone2.RecNo - 1);
Assert((ANewRecNo >= 1) and (ANewRecNo <= AClone2.RecordCount));
AClone2.RecNo := ANewRecNo;
end;
finally
FreeAndNil(AClone);
FreeAndNil(AClone2)
end;
// Меняем отрицательные значения на положительные
k := FRecOrderList.Count - 1;
for I := 0 to k do
begin
if FRecOrderList[I].Order < 0 then
FRecOrderList.Add(TRecOrder.Create(FRecOrderList[I].Key,
-FRecOrderList[I].Order));
end;
// Выполняем все изменения
UpdateOrder;
end;
procedure TQueryOrder.UpdateOrder;
var
APKValue: Variant;
I: Integer;
begin
if FRecOrderList.Count = 0 then
begin
Exit;
end;
FDQuery.DisableControls;
try
APKValue := Wrap.PK.Value;
try
// Теперь поменяем порядок
for I := 0 to FRecOrderList.Count - 1 do
begin
Wrap.LocateByPK(FRecOrderList[I].Key, True);
FDQuery.Edit;
DoOnUpdateOrder(FRecOrderList[I]);
FDQuery.Post;
end;
for I := 0 to FRecOrderList.Count - 1 do
FRecOrderList[I].Free;
FRecOrderList.Clear;
finally
FDQuery.Locate(Wrap.PKFieldName, APKValue, []);
end;
finally
FDQuery.EnableControls;
end;
end;
end.
|
unit LuaTestmain;
interface
{$O-}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ActiveX, ExtCtrls;
type
{$METHODINFO ON}
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Memo2: TMemo;
ButtonLua: TButton;
Label1: TLabel;
Panel1: TPanel;
Button2: TButton;
OpenDialog1: TOpenDialog;
Button3: TButton;
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ButtonLuaClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function TestAAA(p1, p2, p3, p4 :Integer) :Boolean;
end;
{$METHODINFO OFF}
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Lua, LuaUtils, LuaLib, lauxlib, Lua_Assert, ScriptableObject, ObjAuto, typInfo,
Script_System, Script_Classes, Lua_System, Script_DB, Script_DBTables, ObjComAuto;
const
HandleStr ='HANDLE';
type
{$METHODINFO ON}
TMyTest = class(TObjectDispatch)
public
constructor Create(AInstanceObj :TObject; AOwned :Boolean);
function ScriptCreate(Obj :Integer):Integer;
function TestA(Param1 :Boolean; Param2 :Pointer(*TComponent*); var ByRefParam :Integer; pippo :String) :TAnchors; stdcall;
procedure TestB;
end;
{$METHODINFO OFF}
constructor TMyTest.Create(AInstanceObj :TObject; AOwned :Boolean);
begin
inherited;
end;
function TMyTest.ScriptCreate(Obj :Integer):Integer;
begin
Form1.Caption :='AZZZZZZZZZZZZZZZZ';
end;
function TMyTest.TestA(Param1 :Boolean; Param2 :Pointer(*TComponent*); var ByRefParam :Integer; pippo :String) :TAnchors;
begin
Form1.Caption :=pippo;
Inc(ByRefParam);
end;
procedure TMyTest.TestB;
begin
Form1.Caption :='TestB';
end;
function TForm1.TestAAA(p1, p2, p3, p4 :Integer) :Boolean;
begin
SetBounds(p1, p2, p3, p4);
Result :=True;
end;
function listvars(L :Plua_State; level: Integer) :Integer;
Var
ar :lua_Debug;
i :Integer;
name :PChar;
begin
if (lua_getstack(L, level, @ar) = 0) then
begin
//* failure: no such level in the stack */
exit;
end;
i := 1;
name := lua_getlocal(L, @ar, i);
while (name <> nil) do
begin
lua_pop(L, 1);
Inc(i);
name := lua_getlocal(L, @ar, i);
end;
lua_getinfo(L, 'f', @ar);
(* i := 1;
name := lua_getpuvalue(L, -1, @ar);
while ((name <> nil) do
begin
lua_pop(L, 1);
Inc(i);
name := lua_getpuvalue(L, -1, @ar);
end; *)
end;
function GetTObject(L: Plua_State; Index: Integer): TObject;
begin
Result := TObject(LuaGetTableLightUserData(L, Index, HandleStr));
end;
function LuaTestNames(L: Plua_State): Integer; cdecl;
var
NParams :Integer;
begin
NParams := lua_gettop(L);
// if (NParams=0)
// then begin
Form1.Memo2.Lines.Add(GetTObject(L, 1).ClassName);
Form1.memo2.Lines.Add('CALLED '+LuaGetCurrentFuncName(L)+' ='+IntToStr(NParams));
LuaPushInteger(L, 1000);
Result :=1;
(* end
else LuaError(L, ERR_Script+
'LuaOpenDatabase must have NO Params');
*)
end;
function LuaGetProp(L: PLua_State): Integer; cdecl;
procedure Strings(Index: Integer);
var
S: string;
indice :Integer;
begin
indice :=luaL_checkInt(L, Index);
S := Form1.Memo1.Lines[indice];
LuaPushString(L, 'Line '+IntToStr(indice)+' ='+S);
end;
var
Name : string;
ty, NParams : Integer;
begin
Result := 1;
try
NParams := lua_gettop(L);
ty :=lua_type(L, 1);
ty := lua_type(L, 2);
if (ty = LUA_TNUMBER) then
begin
Strings(2);
Exit;
end;
Name := LuaToString(L, 2);
//Se esiste questo metodo
LuaRawSetTableNil(L, 1, Name);
LuaRawSetTableFunction(L, 1, Name, LuaTestNames);
lua_pushcfunction(L, LuaTestNames);
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
function LuaSetProp(L: PLua_State): Integer; cdecl;
procedure Strings(NewVal :Variant; Index: Integer);
var
S: string;
indice :Integer;
begin
indice :=luaL_checkInt(L, Index);
Form1.Memo1.Lines[indice] :=NewVal;
// LuaPushString(L, 'Line '+IntToStr(indice)+' ='+S);
end;
var
Name: string;
NewVal :Variant;
ty, NParams :Integer;
begin
Result := 0;
try
NParams := lua_gettop(L);
ty :=lua_type(L, 1);
ty :=lua_type(L, 2);
ty :=lua_type(L, 3);
if (ty <> LUA_TFUNCTION)
then begin
NewVal :=LuaToVariant(L, 3);
ty := lua_type(L, 2);
if (ty = LUA_TNUMBER) then
begin
Strings(NewVal, 2);
Exit;
end;
Name := LuaToString(L, 2);
Form1.Label1.Caption :=Name;
//Name := luaL_checkstring(L, 2);
//LuaPushString(L, 'Get prop '+Name);
end;
except
on E: Exception do luaL_error(L, PChar(E.Message));
end;
end;
function LuaCreate(L: Plua_State): Integer; cdecl;
var
NParams :Integer;
ar :lua_Debug;
err :Integer;
paramIndex :Integer;
ty :Integer;
begin
NParams := lua_gettop(L);
paramIndex :=1;
(* lua_pushnil(L);
while (lua_next(L, 1) <> 0) do
begin
ty :=lua_type(L, -paramIndex);
Dec(paramIndex);
lua_pop(L, 1);
end;
*)
lua_newtable(L);
LuaSetTableLightUserData(L, -1, HandleStr, Form1.Button1);
//LuaSetTableFunction(L, 1, 'vvv', vvvv);
LuaSetTablePropertyFuncs(L, -1, LuaGetProp, LuaSetProp);
// LuaSetMetaFunction(L, 1, '__index', );
// LuaSetMetaFunction(L, 1, '__newindex', );
// LuaSetMetaFunction(L, 1, '__call', LuaTestNames);
Result :=1;
end;
procedure RunLuaScript(ScriptFile :String);
Var
L :Plua_state;
begin
try
L := lua_open;
luaopen_base(L);
luaopen_string(L);
Script_System.RegisterObject(Form1, 'Form1');
Script_System.RegisterClass(TLabel);
Script_System.RegisterClass(TMyTest);
Lua_System.RegisterFunctions(L);
//LuaRegister(L, 'NameAAA', LuaTestNames);
//LuaRegister(L, 'NameBBBB', LuaTestNames);
Lua_Assert.RegisterFunctions(L);
LuaLoadBuffer(L, Form1.Memo1.Text, 'code');
LuaPcall(L, 0, 0, 0);
finally
if (L<>Nil)
then lua_close(L);
end;
end;
(*
function SetToString(TypeInfo: PTypeInfo; Value: Longint; Brackets: Boolean): string;
var
S: TIntegerSet;
I: Integer;
begin
Result := '';
Integer(S) := Value;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
function StringToSet(EnumInfo: PTypeInfo; const Value: string): Integer;
var
P: PChar;
EnumName: string;
EnumValue: Longint;
// grab the next enum name
function NextWord(var P: PChar): string;
var
i: Integer;
begin
i := 0;
// scan til whitespace
while not (P[i] in [',', ' ', #0,']']) do
Inc(i);
SetString(Result, P, i);
// skip whitespace
while P[i] in [',', ' ',']'] do
Inc(i);
Inc(P, i);
end;
begin
Result := 0;
if Value = '' then Exit;
P := PChar(Value);
// skip leading bracket and whitespace
while P^ in ['[',' '] do
Inc(P);
EnumName := NextWord(P);
while EnumName <> '' do
begin
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
raise EPropertyConvertError.CreateFmt('Invalid Property Element %s', [EnumName]);
Include(TIntegerSet(Result), EnumValue);
EnumName := NextWord(P);
end;
end;
*)
function ObjectInvoke(Instance: TObject; MethodHeader: PMethodInfoHeader;
const ParamIndexes: array of Integer;
const Params: array of Variant): Variant;
const
MaxParams = 10;
procedure Swap(var A, B: PParamInfo);
var
T: PParamInfo;
begin
T := A;
A := B;
B := T;
end;
var
MethodName: string;
procedure ParameterMismatch(I: Integer);
begin
raise Exception.CreateFmt('sTypeMisMatch', [I, MethodName]);
end;
var
MethodInfo: Pointer;
ReturnInfo: PReturnInfo;
MethodAddr: Pointer;
InfoEnd: Pointer;
Count: Integer;
I, K, P: Integer;
Param: PParamInfo;
Regs: array[paEAX..paECX] of Cardinal;
RetVal: Variant;
ParamType: TVarType;
VarType: TVarType;
ParamVarData: PVarData;
PushData: Pointer;
ParamBytes: Integer;
Size: Integer;
Frame: PChar;
ResultParam: Pointer;
ResultPointer: Pointer;
ParamInfos: array[0..MaxParams- 1] of PParamInfo;
ParamData: array[0..MaxParams - 1] of Pointer;
Pointers: array[0..MaxParams - 1] of Pointer;
Temps: array[0..MaxParams - 1] of Variant;
begin
// MethodInfo now points to the method we found.
MethodInfo := MethodHeader;
MethodAddr := MethodHeader^.Addr;
MethodName := PMethodInfoHeader(MethodInfo)^.Name;
Inc(Integer(MethodInfo), SizeOf(TMethodInfoHeader) - SizeOf(ShortString) + 1 +
Length(MethodName));
ReturnInfo := MethodInfo;
Inc(Integer(MethodInfo), SizeOf(TReturnInfo));
InfoEnd := Pointer(Integer(MethodHeader) + MethodHeader^.Len);
Count := 0;
while Integer(MethodInfo) < Integer(InfoEnd) do
begin
if Count >= MaxParams then
raise Exception.CreateFmt('sMethodOver', [MethodName, MaxParams]);
ParamInfos[Count] := MethodInfo;
Inc(Count);
Inc(Integer(MethodInfo), SizeOf(TParamInfo) - SizeOf(ShortString) + 1 +
Length(PParamInfo(MethodInfo)^.Name));
end;
if High(Params) >= Count then
raise Exception.CreateFmt('sTooManyParams', [MethodName]);
(*
// Fill the ParamData array, converting the type as necessary, taking
// into account any ParamIndexes supplied
P := 0;
FillChar(ParamData, SizeOf(ParamData), 0);
for I := 0 to High(Params) do
begin
// Figure out what parameter index this parameter refers to.
// If it is a named parameter it will have an entry in the ParamIndexs
// array. If not, P points to the current parameter to use for unnamed
// parameters. K is the formal parameter number.
// This calculation assumes Self is first and any result parameters are last
if I <= High(ParamIndexes) then
begin
K := ParamIndexes[I];
if K >= Count then
raise Exception.CreateFmt('sInvalidDispID', [I, MethodName]);
end
else
K := High(Params) - P + 1; // Add one to account for Self
Param := ParamInfos[K];
ParamType := GetVariantType(Param^.ParamType^);
ParamVarData := @Params[I];
VarType := ParamVarData^.VType;
if Param^.Flags * [pfOut, pfVar] <> [] then
begin
// For pfVar, the variant must be a byref and equal to the type.
if (VarType <> ParamType or varByRef) and (ParamType <> varVariant) then
ParameterMismatch(I);
end
else
// Convert the parameter to the right type
case ConvertKindOf(VarType and varTypeMask, ParamType) of
ckConvert:
try
Temps[I] := VarAsType(Params[I], ParamType);
// The data bytes for sizes < 4 are dirty, that is they are not
// guarenteed to have 0's in the high bytes. We need them to be zero'ed
if ParamType <= CMaxArrayVarType then
case CVarTypeToElementInfo[ParamType].Size of
1: TVarData(Temps[I]).VLongWord := TVarData(Temps[I]).VByte;
2: TVarData(Temps[I]).VLongWord := TVarData(Temps[I]).VWord;
end;
ParamVarData := @Temps[I];
except
ParameterMismatch(I);
end;
ckError: ParameterMismatch(I);
end;
if ParamType = varVariant then
begin
Pointers[K] := ParamVarData;
ParamData[K] := @Pointers[K];
end
else if varByRef and VarType <> 0 then
ParamData[K] := @ParamVarData^.VPointer
else
ParamData[K] := @ParamVarData^.VInteger;
// Update P which is the pointer to the current non-named parameter.
// This assumes that unnamed parameter fill in the holes left by
// named parameters.
while (P <= High(Params)) and (ParamData[High(Params) - P + 1] <> nil) do
Inc(P)
end;
// Set up the call frame RET EBP
ParamBytes := ReturnInfo^.ParamSize - (4 + 4);
asm
SUB ESP,ParamBytes
MOV Frame,ESP
end;
Dec(Integer(Frame), 4 + 4); // Access numbers include RET and EBP
// Push the parameters on the stack (or put them into the correct register)
ResultParam := nil;
for I := 0 to Count - 1 do
begin
Param := ParamInfos[I];
PushData := ParamData[I];
if PushData = nil then
if (Param^.ParamType^.Kind = tkClass) and SameText(Param^.Name, 'SELF') then
// Self is special. It doesn't appear in the ParamData array since it
// is not represented in the Params array.
PushData := @Instance
else if pfResult in Param^.Flags then
begin
ResultParam := Param;
VarClear(Result);
TVarData(Result).VType := GetVariantType(Param^.ParamType^);
if TVarData(Result).VType = varVariant then
ResultPointer := @Result
else
ResultPointer := @TVarData(Result).VInteger;
PushData := @ResultPointer;
end
else
raise Exception.CreateFmt(sParamRequired, [I, MethodName]);
if Param^.Access < Word(Ord(paStack)) then
Regs[Param^.Access] := PCardinal(PushData)^
else
begin
if [pfVar, pfOut, pfResult] * Param^.Flags <> [] then
PCardinal(@Frame[Param^.Access])^ := PCardinal(PushData)^
else
begin
Size := GetTypeSize(Param^.ParamType^);
case Size of
1, 2, 4:
PCardinal(@Frame[Param^.Access])^ := PCardinal(PushData)^;
8:
begin
PCardinal(@Frame[Param^.Access])^ := PCardinal(PushData)^;
PCardinal(@Frame[Param^.Access + 4])^ :=
PCardinal(Integer(PushData) + 4)^;
end;
else
Move(PushData^, Frame[Param^.Access and not 3], Size);
end;
end;
end;
end;
// Do the call
asm
MOV EAX,DWORD PTR Regs[0]
MOV EDX,DWORD PTR Regs[4]
MOV ECX,DWORD PTR Regs[8]
CALL MethodAddr
MOV DWORD PTR Regs[0],EAX
MOV DWORD PTR Regs[4],EDX
end;
if ReturnInfo^.CallingConvention = ccCdecl then
asm
ADD ESP,ParamBytes
end;
if (ResultParam = nil) and (ReturnInfo^.ReturnType <> nil) then
begin
// The result came back in registers. Otherwise a result pointer was used
// and the return variant is already initialized (or it was a procedure)
TVarData(RetVal).VType := GetVariantType(ReturnInfo^.ReturnType^);
if ReturnInfo^.ReturnType^.Kind = tkFloat then
GetFloatReturn(TVarData(RetVal).VDouble, GetTypeData(ReturnInfo^.ReturnType^)^.FloatType)
else
begin
// For regular Boolean types, we must convert it to a boolean to
// wipe the high order bytes; otherwise the caller may see a false
// as true.
if (TVarData(RetVal).VType = varBoolean) and
(ReturnInfo^.ReturnType^ = System.TypeInfo(Boolean)) then
TVarData(RetVal).VInteger := Integer(Boolean(Regs[paEAX]))
else
TVarData(RetVal).VInteger := Integer(Regs[paEAX]);
PCardinal(Integer(@TVarData(RetVal).VInteger) + 4)^ := Regs[paEDX];
end;
Result := RetVal;
TVarData(RetVal).VType := varEmpty;
end;
*)
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Scripter : TScriptableObject;
ValArray : array of Variant;
I : integer;
V : variant;
PV :PVariant;
Nparams :Integer;
Test :TMyTest;
mInfo :PMethodInfoHeader;
MethodName :String;
Props :PPropList;
n :Integer;
pInfo :PPropInfo;
tInfo :PTypeInfo;
retValue :Variant;
MethodInfo: PMethodInfoHeader;
ReturnInfo: PReturnInfo;
ParamInfos: TParamInfos;
curParam :PParamInfo;
S :TIntegerSet;
begin
Test :=TMyTest.Create(Self, false);
Scripter :=TScriptableObject.Create(Self, false);
MethodName :='TestAAA';
Scripter.GetMethodInfos(MethodName, MethodInfo, ReturnInfo, ParamInfos);
//ObjectInvoke(Test, GetMethodInfo(Test, 'TestA'), [0, 1, 2, 3], [true, Integer(Self), NParams, 'abcd']);
for I :=0 to High(ParamInfos) do
begin
curParam :=ParamInfos[i];
Memo2.Lines.Add(curParam^.Name+' : '+curParam^.ParamType^.Name+'; '+
IntToHex(curParam^.Access, 8));
end;
Scripter.Free;
Test.Free;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
Scripter : TScriptableObject;
ValArray : array of Variant;
I : integer;
V : variant;
PV :PVariant;
Nparams :Integer;
Test :TScriptComponent;
mInfo :PMethodInfoHeader;
MethodName :String;
Props :PPropList;
n :Integer;
pInfo :PPropInfo;
tInfo :PTypeInfo;
retValue :Variant;
MethodInfo: PMethodInfoHeader;
ReturnInfo: PReturnInfo;
ParamInfos: TParamInfos;
curParam :PParamInfo;
S :TIntegerSet;
begin
Test :=TScriptComponent.Create(Self, false);
MethodName :='TestAAA';
Test.GetMethodInfos(MethodName, MethodInfo, ReturnInfo, ParamInfos);
//ObjectInvoke(Test, GetMethodInfo(Test, 'TestA'), [0, 1, 2, 3], [true, Integer(Self), NParams, 'abcd']);
for I :=0 to High(ParamInfos) do
begin
curParam :=ParamInfos[i];
Memo2.Lines.Add(curParam^.Name+' : '+curParam^.ParamType^.Name+'; '+
IntToHex(curParam^.Access, 8));
end;
Test.Free;
end;
procedure TForm1.ButtonLuaClick(Sender: TObject);
begin
RunLuaScript('');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.InitialDir=''
then OpenDialog1.InitialDir :=ExtractFilePath(ParamStr(0))+'scripts';
if OpenDialog1.Execute
then Memo1.Lines.LoadFromFile(OpenDialog1.FileName);
end;
end.
|
unit xExerciseControl;
interface
uses xExerciseInfo, System.SysUtils, System.Classes, xFunction, xExerciseAction,
xSortControl, xQuestionInfo;
type
/// <summary>
/// 控制类
/// </summary>
TExerciseControl = class
private
FExerciseList: TStringList;
FExerciseAction : TExerciseAction;
FCurrentPath: string;
function GetExerciseInfo(nIndex: Integer): TExerciseInfo;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 当前目录
/// </summary>
property CurrentPath : string read FCurrentPath write FCurrentPath;
/// <summary>
/// 列表
/// </summary>
property ExerciseList : TStringList read FExerciseList write FExerciseList;
property ExerciseInfo[nIndex:Integer] : TExerciseInfo read GetExerciseInfo;
/// <summary>
/// 添加
/// </summary>
procedure AddExercise(AExerciseInfo : TExerciseInfo);
/// <summary>
/// 删除
/// </summary>
procedure DelExercise(nExerciseID : Integer); overload;
/// <summary>
/// 删除
/// </summary>
/// <param name="bIsDelPath">如果是目录,是否删除目录</param>
procedure DelExercise(AExercise : TExerciseInfo; bIsDelPath: Boolean); overload;
/// <summary>
/// 重命名
/// </summary>
procedure ReName(AExerciseInfo : TExerciseInfo; sNewName : string);
/// <summary>
/// 加载
/// </summary>
procedure LoadExercise(sPath : string = '');
/// <summary>
/// 上一层目录
/// </summary>
procedure LoadPreviousPath;
/// <summary>
/// 当前目录先是否存在名
/// </summary>
function IsExist(sEName : string) : Boolean;
/// <summary>
/// 清空
/// </summary>
procedure ClearExercise;
end;
var
ExerciseControl : TExerciseControl;
implementation
{ TExerciseControl }
procedure TExerciseControl.AddExercise(AExerciseInfo: TExerciseInfo);
begin
if Assigned(AExerciseInfo) then
begin
AExerciseInfo.ID := FExerciseAction.GetMaxSN + 1;
FExerciseList.AddObject('', AExerciseInfo);
FExerciseAction.AddExercise(AExerciseInfo);
end;
end;
procedure TExerciseControl.ClearExercise;
var
i : Integer;
begin
for i := FExerciseList.Count - 1 downto 0 do
begin
FExerciseAction.DelExercise(TExerciseInfo(FExerciseList.Objects[i]).ID);
TExerciseInfo(FExerciseList.Objects[i]).Free;
FExerciseList.Delete(i);
end;
end;
constructor TExerciseControl.Create;
begin
FExerciseList:= TStringList.Create;
FExerciseAction := TExerciseAction.Create;
LoadExercise;
end;
procedure TExerciseControl.DelExercise(nExerciseID: Integer);
var
i : Integer;
begin
for i := FExerciseList.Count - 1 downto 0 do
begin
if TExerciseInfo(FExerciseList.Objects[i]).id = nExerciseID then
begin
FExerciseAction.DelExercise(nExerciseID);
TExerciseInfo(FExerciseList.Objects[i]).Free;
FExerciseList.Delete(i);
Break;
end;
end;
end;
procedure TExerciseControl.DelExercise(AExercise: TExerciseInfo;
bIsDelPath: Boolean);
var
i : Integer;
begin
for i := FExerciseList.Count - 1 downto 0 do
begin
if TExerciseInfo(FExerciseList.Objects[i]).id = AExercise.Id then
begin
FExerciseAction.DelExercise(AExercise, bIsDelPath);
TExerciseInfo(FExerciseList.Objects[i]).Free;
FExerciseList.Delete(i);
Break;
end;
end;
end;
destructor TExerciseControl.Destroy;
begin
ClearStringList(FExerciseList);
FExerciseList.Free;
FExerciseAction.Free;
inherited;
end;
procedure TExerciseControl.ReName(AExerciseInfo: TExerciseInfo; sNewName : string);
var
i : Integer;
slList : TStringList;
begin
slList := TStringList.Create;
FExerciseAction.LoadExerciseAll(slList);
// 目录
if AExerciseInfo.Ptype = 0 then
begin
for i := 0 to slList.Count - 1 do
begin
with TExerciseInfo(slList.Objects[i]) do
begin
if Pos(AExerciseInfo.Path + '\' + AExerciseInfo.Ename, Path) = 1 then
begin
Path := StringReplace(Path,AExerciseInfo.Path + '\' + AExerciseInfo.Ename, AExerciseInfo.Path + '\' + sNewName, []) ;
FExerciseAction.EditExercise(TExerciseInfo(slList.Objects[i]));
end;
end;
end;
AExerciseInfo.Ename := sNewName;
FExerciseAction.EditExercise(AExerciseInfo);
end
else // 文件
begin
FExerciseAction.EditExercise(AExerciseInfo);
end;
ClearStringList(slList);
slList.Free;
end;
function TExerciseControl.GetExerciseInfo(nIndex: Integer): TExerciseInfo;
begin
if (nIndex >= 0) and (nIndex < FExerciseList.Count) then
begin
Result := TExerciseInfo(FExerciseList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
function TExerciseControl.IsExist(sEName: string): Boolean;
var
i : Integer;
AInfo : TExerciseInfo;
begin
Result := False;
if sEName = '' then
begin
Result := True;
end
else
begin
for i := 0 to FExerciseList.Count -1 do
begin
AInfo := TExerciseInfo(FExerciseList.Objects[i]);
if AInfo.Ename = sEName then
begin
Result := True;
Exit;
end;
end;
end;
end;
procedure TExerciseControl.LoadExercise(sPath : string);
var
AQuestionInfo : TQuestionInfo;
nID : Integer;
i : Integer;
AInfo : TExerciseInfo;
begin
FCurrentPath := sPath;
FExerciseAction.LoadExercise(sPath, FExerciseList);
for i := FExerciseList.Count - 1 downto 0 do
begin
AInfo := TExerciseInfo(FExerciseList.Objects[i]);
if AInfo.Ptype = 1 then
begin
TryStrToInt(AInfo.Remark, nID);
AQuestionInfo := SortControl.GetQInfo(nID);
// 如果题库中不存在则不加载练习题,并删到数据库中的考题
if not Assigned(AQuestionInfo) then
begin
FExerciseAction.DelExercise(AInfo.Id);
AInfo.Free;
FExerciseList.Delete(i);
end
else
begin
AInfo.Ename := AQuestionInfo.QName;
AInfo.Code1 := AQuestionInfo.QCode;
AInfo.Code2 := AQuestionInfo.QRemark2;
AInfo.Remark := IntToStr(AQuestionInfo.QID);
end;
end;
end;
end;
procedure TExerciseControl.LoadPreviousPath;
var
nIndex : Integer;
begin
nIndex := FCurrentPath.LastIndexOf('\');
LoadExercise(Copy(FCurrentPath, 1, nIndex));
end;
end.
|
unit UnContaPagarListaRegistrosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, JvExControls, JvButton,
JvTransparentButton, ExtCtrls,
{ Fluente }
Util, DataUtil, UnModelo, UnContasPagarListaRegistrosModelo, Componentes,
UnAplicacao;
type
TContaPagarListaRegistrosView = class(TForm, ITela)
pnlTitulo: TPanel;
btnIncluir: TJvTransparentButton;
btnMenu: TJvTransparentButton;
pnlFiltro: TPanel;
EdtContaPagar: TEdit;
gProdutos: TDBGrid;
procedure EdtContaPagarChange(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
private
FControlador: IResposta;
FContasPagarListaRegistrosModelo: TContasPagarListaRegistrosModelo;
public
function Controlador(const Controlador: IResposta): ITela;
function Descarregar: ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
end;
implementation
{$R *.dfm}
{ TContaPagarListaRegistrosView }
function TContaPagarListaRegistrosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TContaPagarListaRegistrosView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FContasPagarListaRegistrosModelo := nil;
Result := Self;
end;
function TContaPagarListaRegistrosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TContaPagarListaRegistrosView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FContasPagarListaRegistrosModelo :=
(Modelo as TContasPagarListaRegistrosModelo);
Result := Self;
end;
function TContaPagarListaRegistrosView.Preparar: ITela;
begin
Result := Self;
end;
procedure TContaPagarListaRegistrosView.EdtContaPagarChange(
Sender: TObject);
begin
if Self.EdtContaPagar.Text = '' then
Self.FContasPagarListaRegistrosModelo.Carregar
else
Self.FContasPagarListaRegistrosModelo.CarregarPor(
Criterio.Campo('FORN_NOME').como(Self.EdtContaPagar.Text).obter());
end;
procedure TContaPagarListaRegistrosView.btnIncluirClick(Sender: TObject);
var
_chamada: TChamada;
begin
_chamada := TChamada.Create
.Chamador(Self);
Self.FControlador.Responder(_chamada);
end;
end.
|
unit xUDPServerBase;
interface
uses xCommBase, System.Types, xTypes, System.Classes, xFunction,
system.SysUtils, IdBaseComponent, IdComponent, IdUDPServer, IdUDPBase,
IdUDPClient, IdSocketHandle, IdGlobal, IdContext;
type
/// <summary>
/// UDP 通讯基类 不监听直接可以发送,要接收必须监听
/// </summary>
TUDPServerBase = class(TCommBase)
private
FUDPServer: TIdUDPServer;
FListenPort: Word;
FOnIPSendRev: TIPSendRevPack;
procedure UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes;
ABinding: TIdSocketHandle);
function SendIPData(sIP: string; nPort :Integer; APacks: TArray<Byte>) : Boolean;
protected
/// <summary>
///真实发送 串口或以太网发送
/// </summary>
function RealSend(APacks: TArray<Byte>; sParam1: string = ''; sParam2 : string=''): Boolean; override;
/// <summary>
/// 真实连接
/// </summary>
function RealConnect : Boolean; override;
/// <summary>
/// 真实断开连接
/// </summary>
procedure RealDisconnect; override;
/// <summary>
/// 接收数据
/// </summary>
procedure RevPacksData(sIP: string; nPort :Integer;aPacks: TArray<Byte>); overload;virtual;
procedure RevStrData(sIP: string; nPort :Integer; sStr: string); overload;virtual;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 发送数据
/// </summary>
function SendPacksDataUDP(sIP: string; nPort :Integer; APacks: TArray<Byte>): Boolean; overload; virtual;
function SendPacksDataUDP(sIP: string; nPort :Integer; sStr: string): Boolean; overload; virtual;
/// <summary>
/// 监听端口
/// </summary>
property ListenPort : Word read FListenPort write FListenPort;
/// <summary>
/// 带IP地址和端口的发送和接收事件
/// </summary>
property OnIPSendRev : TIPSendRevPack read FOnIPSendRev write FOnIPSendRev;
end;
implementation
{ TUDPServerBase }
constructor TUDPServerBase.Create;
begin
inherited;
FUDPServer:= TIdUDPServer.Create;
FUDPServer.OnUDPRead := UDPRead;
FUDPServer.BroadcastEnabled := True;
// FUDPServer.BufferSize := MaxInt;
// FIP := '';
FListenPort := 11000;
end;
destructor TUDPServerBase.Destroy;
begin
FUDPServer.Free;
inherited;
end;
function TUDPServerBase.RealConnect: Boolean;
var
s : string;
begin
FUDPServer.DefaultPort := FListenPort;
// FIP := '255.255.255.255';
// FPort := FUDPServer.DefaultPort;
FUDPServer.Active := True;
Result := FUDPServer.Active;
if Result then
s := '成功'
else
s := '失败';
Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 启动侦听端口'+inttostr(FListenPort)+s);
end;
procedure TUDPServerBase.RealDisconnect;
begin
inherited;
FUDPServer.Active := False;
Log(FormatDateTime('hh:mm:ss:zzz', Now) + ' 关闭侦听端口'+inttostr(FListenPort));
end;
function TUDPServerBase.RealSend(APacks: TArray<Byte>; sParam1,sParam2 : string): Boolean;
var
sIP : string;
nPort : Integer;
begin
sIP := sParam1;
TryStrToInt(sParam2, nPort);
Result := SendIPData(sIP, nPort, APacks);
end;
procedure TUDPServerBase.RevPacksData(sIP: string; nPort: Integer;
aPacks: TArray<Byte>);
begin
if Assigned(FOnIPSendRev) then
FOnIPSendRev(sIP, nPort, APacks, false);
RevPacksData(aPacks);
end;
procedure TUDPServerBase.RevStrData(sIP: string; nPort: Integer; sStr: string);
begin
RevStrData( sStr);
end;
function TUDPServerBase.SendPacksDataUDP(sIP: string; nPort: Integer;
APacks: TArray<Byte>): Boolean;
begin
Result := SendPacksDataBase(APacks, sIP, IntToStr(nPort));
end;
function TUDPServerBase.SendIPData(sIP: string; nPort: Integer;
APacks: TArray<Byte>): Boolean;
var
i : Integer;
ABuffer: TIdBytes;
begin
try
SetLength(ABuffer, Length(APacks));
for i := 0 to Length(APacks) - 1 do
ABuffer[i] := APacks[i];
if sIP = '' then
sIP := '255.255.255.255';
if nPort <= 0 then
nPort := 11000;
FUDPServer.SendBuffer(sIP, nPort, ABuffer);
if Assigned(FOnIPSendRev) then
FOnIPSendRev(sIP,nPort, APacks, True);
Result := True;
finally
end;
end;
function TUDPServerBase.SendPacksDataUDP(sIP: string; nPort: Integer;
sStr: string): Boolean;
begin
Result := SendPacksDataUDP(sIP, nPort, StrToPacks(sStr));
end;
procedure TUDPServerBase.UDPRead(AThread: TIdUDPListenerThread;
const AData: TIdBytes; ABinding: TIdSocketHandle);
var
s : string;
i : Integer;
sIP : string;
nPort : Integer;
begin
s := '';
for i := 0 to Length(AData) - 1 do
s := s + Char(AData[i]);
if s <> '' then
begin
sIP := ABinding.PeerIP;
nPort := ABinding.Port;
RevStrData(sIP, nPort, s);
RevPacksData(sIP, nPort,StrToPacks( s))
end;
end;
end.
|
unit ncaFrmSenhaWiz;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, ncErros, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxTextEdit, cxControls, cxContainer, cxEdit, cxLabel, StdCtrls,
cxLookAndFeelPainters, cxButtons, Menus, pngimage, ExtCtrls, cxGraphics,
cxLookAndFeels, LMDPNGImage, LMDSimplePanel, LMDControl, LMDCustomControl,
LMDCustomPanel, LMDCustomBevelPanel, LMDCustomParentPanel, LMDCustomPanelFill,
LMDPanelFill;
type
TFrmSenhaWiz = class(TForm)
edNova: TcxTextEdit;
lbNovaSenha: TcxLabel;
edConfirma: TcxTextEdit;
lbConfirmarSenha: TcxLabel;
cxLabel4: TcxLabel;
btnAlterar: TcxButton;
btnCancelar: TcxButton;
Timer1: TTimer;
LMDPanelFill1: TLMDPanelFill;
Image3: TImage;
cxLabel1: TcxLabel;
LMDSimplePanel1: TLMDSimplePanel;
LMDSimplePanel2: TLMDSimplePanel;
LMDSimplePanel11: TLMDSimplePanel;
procedure btnCancelarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure btnAlterarClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FSenha : String;
public
function Editar(var aSenha: String): Boolean;
{ Public declarations }
end;
var
FrmSenhaWiz: TFrmSenhaWiz;
implementation
uses ncaFrmPri, ncaDM;
// START resource string wizard section
resourcestring
SAsSenhasNãoEstãoIguais = 'As senhas não estão iguais.';
// END resource string wizard section
{$R *.dfm}
{ TFrmAlteraSenha }
function TFrmSenhaWiz.Editar(var aSenha: String): Boolean;
begin
aSenha := '';
ShowModal;
Result := (ModalResult=mrOk);
if Result then
aSenha := FSenha;
end;
procedure TFrmSenhaWiz.btnAlterarClick(Sender: TObject);
begin
if not Sametext(edNova.Text, edConfirma.Text) then begin
edNova.SetFocus;
Raise Exception.Create(SAsSenhasNãoEstãoIguais);
end;
FSenha := edNova.Text;
ModalResult := mrOk;
end;
procedure TFrmSenhaWiz.btnCancelarClick(Sender: TObject);
begin
FSenha := '';
ModalResult := mrOk;
end;
procedure TFrmSenhaWiz.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmSenhaWiz.FormShow(Sender: TObject);
begin
Timer1.Enabled := SameText(ParamStr(1), 'afterinst'); // do not localize
edNova.SetFocus;
end;
procedure TFrmSenhaWiz.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
try
ForceForegroundWindow(Handle);
finally
Timer1.Interval := 5000;
Timer1.Enabled := True;
end;
end;
procedure TFrmSenhaWiz.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = Key_Enter) then
Perform(WM_NEXTDLGCTL,0,0);
end;
end.
|
{
Definition of error codes.
LICENSE:
Copyright 2016-2021 Jan Horacek
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.
}
unit Errors;
interface
const
RCS_GENERAL_EXCEPTION = 1000;
RCS_FILE_CANNOT_ACCESS = 1010;
RCS_FILE_DEVICE_OPENED = 1011;
RCS_MODULE_INVALID_ADDR = 1100;
RCS_PORT_INVALID_NUMBER = 1103;
RCS_PORT_INVALID_VALUE = 1106;
RCS_INPUT_NOT_YET_SCANNED = 1108;
RCS_ALREADY_OPENNED = 2001;
RCS_CANNOT_OPEN_PORT = 2002;
RCS_FIRMWARE_TOO_LOW = 2003;
RCS_DEVICE_DISCONNECTED = 2004;
RCS_SCANNING_NOT_FINISHED = 2010;
RCS_NOT_OPENED = 2011;
RCS_ALREADY_STARTED = 2012;
RCS_OPENING_NOT_FINISHED = 2021;
RCS_NO_MODULES = 2025;
RCS_NOT_STARTED = 2031;
RCS_MODULE_FAILED = 3141;
RCS_MODULE_RESTORED = 3142;
RCS_UNSUPPORTED_API_VERSION = 4000;
implementation
end.
|
{ Component(s):
TindLed ---> old cindy name tcyled
Description:
A simple led with Group feature
depending on the state: ON/OFF/DISABLE
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Initial Developer of the Original Code is Mauricio
* (https://sourceforge.net/projects/tcycomponents/).
*
* No contributors for now ...
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or the
* GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which
* case the provisions of the GPL or the LGPL are applicable instead of those
* above. If you wish to allow use of your version of this file only under the
* terms of either the GPL or the LGPL, and not to allow others to use your
* version of this file under the terms of the MPL, indicate your decision by
* deleting the provisions above and replace them with the notice and other
* provisions required by the LGPL or the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under the
* terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK *****
Modified by Jurassic Pork 2013 for package Industrial of Lazarus}
unit IndLed;
{$mode objfpc}{$H+}
interface
uses Classes, Types, Controls, Graphics, indcyBaseLed, indcyTypes, indcyClasses, indcyGraphics;
type
TShapeType = (stRectangle, stRoundRect, stEllipse);
TcyCustomLed = class(TcyBaseLed)
private
FLedColorOn: TColor;
FLedColorOff: TColor;
FLedColorDisabled: TColor;
FShapeRoundRectX: Integer;
FShapeRoundRectY: Integer;
FShapeLedColorOn: TColor;
FShapeLedColorOff: TColor;
FShapeLedColorDisabled: TColor;
FBevels: TcyBevels;
FShapeType: TShapeType;
FShapePenWidth: Word;
FTransparent: boolean;
procedure SetShapeLedColorOn(Value: TColor);
procedure SetShapePenWidth(Value: Word);
procedure SetShapeType(Value: TShapeType);
procedure SetShapeRoundRectX(Value: Integer);
procedure SetShapeRoundRectY(Value: Integer);
procedure SetBevels(const Value: TcyBevels);
procedure SetLedColorDisabled(Value: TColor);
procedure SetLedColorOff(Value: TColor);
procedure SetLedColorOn(Value: TColor);
procedure SetTransparent(const Value: boolean);
procedure SetShapeLedColorDisabled(const Value: TColor);
procedure SetShapeLedColorOff(const Value: TColor);
protected
procedure Paint; override;
function TransparentColorAtPos(Point: TPoint): boolean; override;
property Transparent: boolean read FTransparent write SetTransparent default false;
property LedColorOn: TColor read FLedColorOn write SetLedColorOn;
property LedColorOff: TColor read FLedColorOff write SetLedColorOff;
property LedColorDisabled: TColor read FLedColorDisabled write SetLedColorDisabled;
property ShapeLedColorOn: TColor read FShapeLedColorOn write SetShapeLedColorOn;
property ShapeLedColorOff: TColor read FShapeLedColorOff write SetShapeLedColorOff;
property ShapeLedColorDisabled: TColor read FShapeLedColorDisabled write SetShapeLedColorDisabled;
property ShapePenWidth: Word read FShapePenWidth write SetShapePenWidth default 1;
property ShapeType: TShapeType read FShapeType write SetShapeType default stRectangle;
property ShapeRoundRectX: Integer read FShapeRoundRectX write SetShapeRoundRectX default 10;
property ShapeRoundRectY: Integer read FShapeRoundRectY write SetShapeRoundRectY default 10;
property Bevels: TcyBevels read FBevels write SetBevels;
property Height default 25;
property Width default 25;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
TindLed = class(TcyCustomLed)
private
protected
public
published
property Align;
property Anchors;
property BorderSpacing;
property Color;
property Constraints;
property Enabled;
property Visible;
property OnClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property ShowHint;
// Herited from TcyBaseLed :
property AllowAllOff;
property GroupIndex;
property LedValue;
property ReadOnly;
// Herited from TcyCustomLed :
property Bevels;
property LedColorOn;
property LedColorOff;
property LedColorDisabled;
property ShapeLedColorOn;
property ShapeLedColorOff;
property ShapeLedColorDisabled;
property ShapePenWidth;
property ShapeType;
property ShapeRoundRectX;
property ShapeRoundRectY;
property Transparent;
end;
implementation
constructor TcyCustomLed.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBevels := TcyBevels.Create(self, TcyBevel);
// Determine at design time if
// the form is loading or if we have just added the component at design time :
if csDesigning in ComponentState
then
if Owner <> nil
then
if not (csLoading in Owner.ComponentState) // we have just added the component at design time
then begin
with FBevels.Add do // Frame
begin
HighlightColor := clBlack;
ShadowColor := clBlack;
end;
with FBevels.Add do // Inner 3D frame
Width := 3;
with FBevels.Add do // Contrast Frame
Style := bcLowered;
with FBevels.Add do // Border between Bevels and Shape
begin
HighlightColor := clBlack;
ShadowColor := clBlack;
Width := 1;
end;
end;
FTransparent := false;
FShapeType := stRectangle;
FShapePenWidth:= 1;
FShapeRoundRectX := 10;
FShapeRoundRectY := 10;
FShapeLedColorOn := clGreen;
FShapeLedColorOff := $00004000; // Dark green
FShapeLedColorDisabled := $00003468; // Dark maroon
FLedColorOn:= clLime;
FLedColorOff:= clGreen;
FLedColorDisabled:= $000059B3; // Maroon
Height := 25;
Width := 25;
end;
destructor TcyCustomLed.Destroy;
begin
FBevels.Free;
FBevels := Nil;
inherited Destroy;
end;
procedure TcyCustomLed.Paint;
var
Rect: TRect;
begin
Rect := ClientRect;
// Draw background :
if not FTransparent
then begin
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect);
end;
Bevels.DrawBevels(Canvas, Rect, false);
case ledStatus of
lsOn: Canvas.Brush.Color := FLedColorOn;
lsOff: Canvas.Brush.Color := FLedColorOff;
lsDisabled: Canvas.Brush.Color := FLedColorDisabled;
end;
if FShapePenWidth > 0
then begin
Rect := classes.Rect(Rect.Left + FShapePenWidth div 2,
Rect.Top + FShapePenWidth div 2,
Rect.Right - (FShapePenWidth-1) div 2,
Rect.Bottom - (FShapePenWidth-1) div 2);
case ledStatus of
lsOn: Canvas.Pen.Color := FShapeLedColorOn;
lsOff: Canvas.Pen.Color := FShapeLedColorOff;
lsDisabled: Canvas.Pen.Color := FShapeLedColorDisabled;
end;
Canvas.Pen.Width := FShapePenWidth;
end
else begin
Canvas.Pen.Color := Canvas.Brush.Color;
Canvas.Pen.Width := 1;
end;
case FShapeType of
stRectangle: canvas.Rectangle(Rect);
stRoundRect: canvas.RoundRect(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom, ShapeRoundRectX, ShapeRoundRectY);
stEllipse : canvas.Ellipse(Rect);
end;
end;
function TcyCustomLed.TransparentColorAtPos(Point: TPoint): boolean;
begin
RESULT := false;
if FTransparent and (Bevels.Count = 0) and (FShapeType = stEllipse)
then RESULT := not PointInEllipse(Point, ClientRect);
end;
procedure TcyCustomLed.SetTransparent(const Value: boolean);
begin
if value <> FTransparent
then begin
FTransparent := Value;
Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeLedColorOn(Value: TColor);
begin
if value <> FShapeLedColorOn
then begin
FShapeLedColorOn := Value;
if GetLedStatus = lsOn
then Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeLedColorOff(const Value: TColor);
begin
if value <> FShapeLedColorOff
then begin
FShapeLedColorOff := Value;
if GetLedStatus = lsOff
then Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeLedColorDisabled(const Value: TColor);
begin
if value <> FShapeLedColorDisabled
then begin
FShapeLedColorDisabled := Value;
if GetLedStatus = lsDisabled
then Invalidate;
end;
end;
procedure TcyCustomLed.SetShapePenWidth(Value: Word);
begin
if value <> FShapePenWidth
then begin
FShapePenWidth := Value;
Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeRoundRectX(Value: Integer);
begin
if Value <> FShapeRoundRectX
then begin
FShapeRoundRectX := value;
if FShapeType = stRoundRect
then Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeRoundRectY(Value: Integer);
begin
if Value <> FShapeRoundRectY
then begin
FShapeRoundRectY := value;
if FShapeType = stRoundRect
then Invalidate;
end;
end;
procedure TcyCustomLed.SetShapeType(Value: TShapeType);
begin
if value <> FShapeType
then begin
FShapeType := Value;
Invalidate;
end;
end;
procedure TcyCustomLed.SetLedColorOn(Value: TColor);
begin
if value <> FLedColorOn
then begin
FLedColorOn := Value;
if GetLedStatus = lsOn
then Invalidate;
end;
end;
procedure TcyCustomLed.SetLedColorOff(Value: TColor);
begin
if value <> FLedColorOff
then begin
FLedColorOff := Value;
if GetLedStatus = lsOff
then Invalidate;
end;
end;
procedure TcyCustomLed.SetLedColorDisabled(Value: TColor);
begin
if value <> FLedColorDisabled
then begin
FLedColorDisabled := Value;
if GetLedStatus = lsDisabled
then Invalidate;
end;
end;
procedure TcyCustomLed.SetBevels(const Value: TcyBevels);
begin
FBevels := Value;
end;
end.
|
unit ProductsBaseQuery0;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseEventsQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls,
NotifyEvents, DescriptionsQueryWrap, DSWrap,
DocFieldInfo;
type
TBaseProductsW = class(TDescriptionW)
private
FAmount: TFieldWrap;
FDatasheet: TFieldWrap;
FDiagram: TFieldWrap;
FDrawing: TFieldWrap;
FID: TFieldWrap;
FImage: TFieldWrap;
FIsGroup: TFieldWrap;
FPriceD: TFieldWrap;
FPriceD1: TFieldWrap;
FPriceD2: TFieldWrap;
FPriceE: TFieldWrap;
FPriceE1: TFieldWrap;
FPriceE2: TFieldWrap;
FPriceR: TFieldWrap;
FPriceR1: TFieldWrap;
FPriceR2: TFieldWrap;
procedure DoAfterOpen(Sender: TObject);
protected
procedure InitFields; virtual;
procedure OnDatasheetGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
public
constructor Create(AOwner: TComponent); override;
procedure AfterConstruction; override;
procedure SetDisplayFormat(const AFields: Array of TField);
property Amount: TFieldWrap read FAmount;
property Datasheet: TFieldWrap read FDatasheet;
property Diagram: TFieldWrap read FDiagram;
property Drawing: TFieldWrap read FDrawing;
property ID: TFieldWrap read FID;
property Image: TFieldWrap read FImage;
property IsGroup: TFieldWrap read FIsGroup;
property PriceD: TFieldWrap read FPriceD;
property PriceD1: TFieldWrap read FPriceD1;
property PriceD2: TFieldWrap read FPriceD2;
property PriceE: TFieldWrap read FPriceE;
property PriceE1: TFieldWrap read FPriceE1;
property PriceE2: TFieldWrap read FPriceE2;
property PriceR: TFieldWrap read FPriceR;
property PriceR1: TFieldWrap read FPriceR1;
property PriceR2: TFieldWrap read FPriceR2;
end;
TQryProductsBase0 = class(TQueryBaseEvents)
private
class var
FDollarCource: Double;
FEuroCource: Double;
FOnDollarCourceChange: TNotifyEventsEx;
FOnEuroCourceChange: TNotifyEventsEx;
var
FBPW: TBaseProductsW;
class procedure SetDollarCource(const Value: Double); static;
class procedure SetEuroCource(const Value: Double); static;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
procedure LoadDocFile(const AFileName: String;
ADocFieldInfo: TDocFieldInfo);
property BPW: TBaseProductsW read FBPW;
class property DollarCource: Double read FDollarCource write SetDollarCource;
class property EuroCource: Double read FEuroCource write SetEuroCource;
class property OnDollarCourceChange: TNotifyEventsEx read FOnDollarCourceChange;
class property OnEuroCourceChange: TNotifyEventsEx read FOnEuroCourceChange;
{ Public declarations }
end;
implementation
uses
StrHelper, System.IOUtils;
{$R *.dfm}
constructor TQryProductsBase0.Create(AOwner: TComponent);
begin
inherited;
FBPW := Wrap as TBaseProductsW;
if FOnDollarCourceChange = nil then
begin
FOnDollarCourceChange := TNotifyEventsEx.Create(Self);
FOnEuroCourceChange := TNotifyEventsEx.Create(Self);
end;
end;
function TQryProductsBase0.CreateDSWrap: TDSWrap;
begin
Result := TBaseProductsW.Create(FDQuery);
end;
procedure TQryProductsBase0.LoadDocFile(const AFileName: String;
ADocFieldInfo: TDocFieldInfo);
var
OK: Boolean;
S: String;
begin
if AFileName.IsEmpty then
Exit;
// В БД храним путь до файла относительно папки с документацией
S := GetRelativeFileName(AFileName, ADocFieldInfo.Folder);
OK := BPW.TryEdit;
FDQuery.FieldByName(ADocFieldInfo.FieldName).AsString := S;
if OK then
BPW.TryPost;
end;
class procedure TQryProductsBase0.SetDollarCource(const Value: Double);
begin
if FDollarCource = Value then
Exit;
FDollarCource := Value;
// Извещаем представления
FOnDollarCourceChange.CallEventHandlers(nil);
end;
class procedure TQryProductsBase0.SetEuroCource(const Value: Double);
begin
if FEuroCource = Value then
Exit;
FEuroCource := Value;
// Извещаем представления
FOnEuroCourceChange.CallEventHandlers(nil);
end;
constructor TBaseProductsW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FIsGroup := TFieldWrap.Create(Self, 'IsGroup');
FDatasheet := TFieldWrap.Create(Self, 'Datasheet');
FDiagram := TFieldWrap.Create(Self, 'Diagram');
FImage := TFieldWrap.Create(Self, 'Image');
FDrawing := TFieldWrap.Create(Self, 'Drawing');
FAmount := TFieldWrap.Create(Self, 'Amount');
FPriceD := TFieldWrap.Create(Self, 'PriceD');
FPriceD1 := TFieldWrap.Create(Self, 'PriceD1');
FPriceD2 := TFieldWrap.Create(Self, 'PriceD2');
FPriceE := TFieldWrap.Create(Self, 'PriceE');
FPriceE1 := TFieldWrap.Create(Self, 'PriceE1');
FPriceE2 := TFieldWrap.Create(Self, 'PriceE2');
FPriceR := TFieldWrap.Create(Self, 'PriceR');
FPriceR1 := TFieldWrap.Create(Self, 'PriceR1');
FPriceR2 := TFieldWrap.Create(Self, 'PriceR2');
TNotifyEventWrap.Create(AfterOpen, DoAfterOpen, EventList);
end;
procedure TBaseProductsW.AfterConstruction;
begin
inherited;
if DataSet.Active then
InitFields;
end;
procedure TBaseProductsW.DoAfterOpen(Sender: TObject);
begin
SetFieldsRequired(False);
SetFieldsReadOnly(False);
InitFields;
end;
procedure TBaseProductsW.InitFields;
begin
Datasheet.F.OnGetText := OnDatasheetGetText;
Diagram.F.OnGetText := OnDatasheetGetText;
Drawing.F.OnGetText := OnDatasheetGetText;
Image.F.OnGetText := OnDatasheetGetText;
SetDisplayFormat([PriceR.F, PriceD.F, PriceE.F, PriceD1.F, PriceR1.F,
PriceE1.F, PriceD2.F, PriceR2.F, PriceE2.F]);
end;
procedure TBaseProductsW.OnDatasheetGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
begin
if not Sender.AsString.IsEmpty then
Text := TPath.GetFileNameWithoutExtension(Sender.AsString);
end;
procedure TBaseProductsW.SetDisplayFormat(const AFields: Array of TField);
var
I: Integer;
begin
Assert(Length(AFields) > 0);
for I := Low(AFields) to High(AFields) do
begin
// Если поле не TNumericField - значит запрос вернул 0 записей и не удалось определить тип поля
if (AFields[I] is TNumericField) then
(AFields[I] as TNumericField).DisplayFormat := '###,##0.00';
end;
end;
end.
|
unit UFMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.Grids, UIMainController, GIFImg;
type
TFMain = class(TForm)
pnlHeader: TPanel;
imgHeader: TImage;
pnlCloseButton: TPanel;
imgClose: TImage;
lblTitle: TLabel;
pnlLastLogsData: TPanel;
pnlStatusConnections: TPanel;
pnlLastExec: TPanel;
pnlBtnFilter: TPanel;
pnlBtnConfig: TPanel;
imgBtnConfig: TImage;
lblBtnConfig: TLabel;
pnlBtnUser: TPanel;
imgBtnUser: TImage;
lblBtnUser: TLabel;
imgBtnFilter: TImage;
lblBtnFilter: TLabel;
lblLastLogDataTitle: TLabel;
lblStatusConnectionTitles: TLabel;
lblLastExecTitle: TLabel;
strgrdLastLogData: TStringGrid;
lblMessageDataLog: TLabel;
imgStatusLastExec: TImage;
lblMessageLastExecTitle: TLabel;
lblDateTimeLastExecTitle: TLabel;
lblMessageLastExecPart1: TLabel;
lblDateTimeLastExec: TLabel;
lblMessageLastExecPart2: TLabel;
lblMongoStatus: TLabel;
imgMongoStatus: TImage;
lblMongoDbTitle: TLabel;
lblMySqlStatus: TLabel;
imgMySqlStatus: TImage;
lblMySqlTitle: TLabel;
pnlDivider: TPanel;
procedure imgCloseClick(Sender: TObject);
procedure imgCloseMouseEnter(Sender: TObject);
procedure imgCloseMouseLeave(Sender: TObject);
procedure pnlBtnUserMouseEnter(Sender: TObject);
procedure pnlBtnUserMouseLeave(Sender: TObject);
procedure imgBtnUserMouseEnter(Sender: TObject);
procedure imgBtnUserMouseLeave(Sender: TObject);
procedure lblBtnUserMouseEnter(Sender: TObject);
procedure lblBtnUserMouseLeave(Sender: TObject);
procedure pnlBtnConfigMouseEnter(Sender: TObject);
procedure pnlBtnConfigMouseLeave(Sender: TObject);
procedure imgBtnConfigMouseEnter(Sender: TObject);
procedure imgBtnConfigMouseLeave(Sender: TObject);
procedure lblBtnConfigMouseEnter(Sender: TObject);
procedure lblBtnConfigMouseLeave(Sender: TObject);
procedure pnlBtnFilterMouseEnter(Sender: TObject);
procedure pnlBtnFilterMouseLeave(Sender: TObject);
procedure imgBtnFilterMouseEnter(Sender: TObject);
procedure imgBtnFilterMouseLeave(Sender: TObject);
procedure lblBtnFilterMouseEnter(Sender: TObject);
procedure lblBtnFilterMouseLeave(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure strgrdLastLogDataDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure FormShow(Sender: TObject);
procedure strgrdLastLogDataSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure strgrdLastLogDataDblClick(Sender: TObject);
procedure pnlBtnUserClick(Sender: TObject);
private
{ Private declarations }
FController: IMainController;
FRowCellSelected : Integer;
procedure AdjustPnlBtnUser(Hover : Boolean);
procedure PnlBtnUserExecute;
procedure AdjustPnlBtnFilter(Hover : Boolean);
procedure PnlBtnFilterExecute;
procedure AdjustPnlBtnConfig(Hover : Boolean);
procedure PnlBtnConfigExecute;
public
{ Public declarations }
procedure LoadController(controller: IMainController);
procedure NotShowLoadingDataLogs;
procedure ShowMessageDataLogs(Msg: string);
procedure ShowMessageLastExec(Msg: string);
end;
var
FMain: TFMain;
implementation
{$R *.dfm}
procedure TFMain.AdjustPnlBtnConfig(Hover: Boolean);
begin
if (Hover) then
begin
imgBtnConfig.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Config72pxDark',RT_RCDATA));
lblBtnConfig.Font.Color := $003C0A28;
end
else
begin
imgBtnConfig.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Config72px',RT_RCDATA));
lblBtnConfig.Font.Color := $005A1E41;
end;
end;
procedure TFMain.AdjustPnlBtnFilter(Hover: Boolean);
begin
if (Hover) then
begin
imgBtnFilter.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Filter72pxDark',RT_RCDATA));
lblBtnFilter.Font.Color := $0014A0DC;
end
else
begin
imgBtnFilter.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Filter72px',RT_RCDATA));
lblBtnFilter.Font.Color := $0000B2FF;
end;
end;
procedure TFMain.AdjustPnlBtnUser(Hover: Boolean);
begin
if (Hover) then
begin
imgBtnUser.Picture.LoadFromStream(TResourceStream.Create(HInstance,'User72pxDark',RT_RCDATA));
lblBtnUser.Font.Color := $003C0A28;
end
else
begin
imgBtnUser.Picture.LoadFromStream(TResourceStream.Create(HInstance,'User72px',RT_RCDATA));
lblBtnUser.Font.Color := $005A1E41;
end;
end;
procedure TFMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FController.Close;
end;
procedure TFMain.FormShow(Sender: TObject);
begin
if Assigned(FController) then
FController.LoadDataView;
end;
procedure TFMain.imgBtnConfigMouseEnter(Sender: TObject);
begin
AdjustPnlBtnConfig(true);
end;
procedure TFMain.imgBtnConfigMouseLeave(Sender: TObject);
begin
AdjustPnlBtnConfig(false);
end;
procedure TFMain.imgBtnFilterMouseEnter(Sender: TObject);
begin
AdjustPnlBtnFilter(true);
end;
procedure TFMain.imgBtnFilterMouseLeave(Sender: TObject);
begin
AdjustPnlBtnUser(false);
end;
procedure TFMain.imgBtnUserMouseEnter(Sender: TObject);
begin
AdjustPnlBtnUser(true);
end;
procedure TFMain.imgBtnUserMouseLeave(Sender: TObject);
begin
AdjustPnlBtnUser(false);
end;
procedure TFMain.imgCloseClick(Sender: TObject);
begin
Self.Close;
end;
procedure TFMain.imgCloseMouseEnter(Sender: TObject);
begin
imgClose.Picture.LoadFromStream(TResourceStream
.Create(HInstance,'Close48pxDark',RT_RCDATA));
end;
procedure TFMain.imgCloseMouseLeave(Sender: TObject);
begin
imgClose.Picture.LoadFromStream(TResourceStream
.Create(HInstance,'Close48px',RT_RCDATA));
end;
procedure TFMain.lblBtnConfigMouseEnter(Sender: TObject);
begin
AdjustPnlBtnConfig(true);
end;
procedure TFMain.lblBtnConfigMouseLeave(Sender: TObject);
begin
AdjustPnlBtnConfig(false);
end;
procedure TFMain.lblBtnFilterMouseEnter(Sender: TObject);
begin
AdjustPnlBtnFilter(true);
end;
procedure TFMain.lblBtnFilterMouseLeave(Sender: TObject);
begin
AdjustPnlBtnFilter(false);
end;
procedure TFMain.lblBtnUserMouseEnter(Sender: TObject);
begin
AdjustPnlBtnUser(true);
end;
procedure TFMain.lblBtnUserMouseLeave(Sender: TObject);
begin
AdjustPnlBtnUser(false);
end;
procedure TFMain.LoadController(controller: IMainController);
begin
FController := controller;
end;
procedure TFMain.NotShowLoadingDataLogs;
var
I: Integer;
begin
for I := ComponentCount - 1 downto 0 do
begin
If Components[i].Name = 'pnlLastLogsDataImg' then
(Components[i] as TImage).Free;
end;
strgrdLastLogData.Visible := True;
end;
procedure TFMain.PnlBtnConfigExecute;
begin
end;
procedure TFMain.pnlBtnConfigMouseEnter(Sender: TObject);
begin
AdjustPnlBtnConfig(true);
end;
procedure TFMain.pnlBtnConfigMouseLeave(Sender: TObject);
begin
AdjustPnlBtnConfig(false);
end;
procedure TFMain.PnlBtnFilterExecute;
begin
end;
procedure TFMain.pnlBtnFilterMouseEnter(Sender: TObject);
begin
AdjustPnlBtnFilter(true);
end;
procedure TFMain.pnlBtnFilterMouseLeave(Sender: TObject);
begin
AdjustPnlBtnFilter(false);
end;
procedure TFMain.pnlBtnUserClick(Sender: TObject);
begin
FController.ShowUser;
end;
procedure TFMain.PnlBtnUserExecute;
begin
end;
procedure TFMain.pnlBtnUserMouseEnter(Sender: TObject);
begin
AdjustPnlBtnUser(true);
end;
procedure TFMain.pnlBtnUserMouseLeave(Sender: TObject);
begin
AdjustPnlBtnUser(false);
end;
procedure TFMain.ShowMessageDataLogs(Msg: string);
var
lblMessage : TLabel;
X, Y, ImgX, ImgY, I: Integer;
LoaginGif : TGIFImage;
begin
strgrdLastLogData.Visible := False;
lblMessageDataLog.Caption := Msg;
lblMessageDataLog.Visible := True;
end;
procedure TFMain.ShowMessageLastExec(Msg: string);
begin
imgStatusLastExec.Visible := False;
lblMessageLastExecTitle.Visible := False;
lblMessageLastExecPart1.Visible := False;
lblDateTimeLastExecTitle.Visible := False;
lblDateTimeLastExec.Visible := False;
lblMessageLastExecPart2.Left := 8;
lblMessageLastExecPart2.Width := 497;
lblMessageLastExecPart2.Caption := Msg;
lblMessageLastExecPart2.Alignment := taCenter;
end;
procedure TFMain.strgrdLastLogDataDblClick(Sender: TObject);
begin
if FRowCellSelected > 0 then
FController.ShowLogDetails(StrToInt(strgrdLastLogData.Cells[3,FRowCellSelected]),strgrdLastLogData.Cells[1,FRowCellSelected],strgrdLastLogData.Cells[2,FRowCellSelected], strgrdLastLogData.Cells[4,FRowCellSelected]);
end;
procedure TFMain.strgrdLastLogDataDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
Image: TPngImage;
s: string;
aCanvas: TCanvas;
begin
if (ACol <> 0) or (ARow = 0) then
Exit;
s := (Sender as TStringGrid).Cells[3, ARow];
// Draw ImageX.Picture.Bitmap in all Rows in Col 1
aCanvas := (Sender as TStringGrid).Canvas; // To avoid with statement
// Clear current cell rect
aCanvas.FillRect(Rect);
// Draw the image in the cell
Image := TPngImage.Create;
if (s = '1') then
Image.LoadFromStream(TResourceStream.Create(HInstance,'Success24px',RT_RCDATA))
else
Image.LoadFromStream(TResourceStream.Create(HInstance,'Error24px',RT_RCDATA));
aCanvas.Draw(Rect.Left, Rect.Top, Image);
end;
procedure TFMain.strgrdLastLogDataSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
FRowCellSelected := ARow;
end;
end.
|
unit StdRequest;
interface
uses xmldom, XMLDoc, XMLIntf, Variants;
type
{ Forward Decls }
IXMLGMIORequestType = interface;
IXMLAuthType = interface;
IXMLDataType = interface;
IXMLSourcesType = interface;
IXMLSourceType = interface;
IXMLStateType = interface;
{ IXMLGMIORequestType }
IXMLGMIORequestType = interface(IXMLNode)
['{086C2F9B-BA0D-48EA-9853-0595CC0716E3}']
{ Property Accessors }
function Get_Auth: IXMLAuthType;
function Get_Structure: Integer;
function Get_Data: IXMLDataType;
function Get_State: IXMLStateType;
function Get_Comment: UnicodeString;
procedure Set_Comment(Value: UnicodeString);
procedure Set_Structure(Value: Integer);
{ Methods & Properties }
property Comment: UnicodeString read Get_Comment write Set_Comment;
property Auth: IXMLAuthType read Get_Auth;
property Structure: Integer read Get_Structure write Set_Structure;
property Data: IXMLDataType read Get_Data;
property State: IXMLStateType read Get_State;
end;
{ IXMLStateType }
IXMLStateType = interface(IXMLNode)
['{9DD441AD-60C6-41B0-B32F-125537230BB3}']
{ Property Accessors }
function Get_RemoteServerReady: integer;
procedure Set_RemoteServerReady(Value: integer);
{ Methods & Properties }
property RemoteServerReady: integer read Get_RemoteServerReady write Set_RemoteServerReady;
end;
{ IXMLAuthType }
IXMLAuthType = interface(IXMLNode)
['{F40CB462-EE38-47FE-800D-65302BD0A52B}']
{ Property Accessors }
function Get_Login: UnicodeString;
function Get_Password: UnicodeString;
function Get_RemoteName: UnicodeString;
function Get_RequestID: UnicodeString;
procedure Set_RequestID(Value: UnicodeString);
procedure Set_RemoteName(Value: UnicodeString);
procedure Set_Login(Value: UnicodeString);
procedure Set_Password(Value: UnicodeString);
{ Methods & Properties }
property Login: UnicodeString read Get_Login write Set_Login;
property Password: UnicodeString read Get_Password write Set_Password;
property RemoteName: UnicodeString read Get_RemoteName write Set_RemoteName;
property RequestID: UnicodeString read Get_RequestID write Set_RequestID;
end;
{ IXMLDataType }
IXMLDataType = interface(IXMLNode)
['{248C3598-ED18-4D08-B4C3-63FB66922C72}']
{ Property Accessors }
function Get_Sources: IXMLSourcesType;
function Get_SQL: UnicodeString;
function Get_OPC: Integer;
procedure Set_SQL(Value: UnicodeString);
procedure Set_OPC(Value: Integer);
{ Methods & Properties }
property Sources: IXMLSourcesType read Get_Sources;
property SQL: UnicodeString read Get_SQL write Set_SQL;
property OPC: Integer read Get_OPC write Set_OPC;
end;
{ IXMLSourcesType }
IXMLSourcesType = interface(IXMLNodeCollection)
['{621FD3F6-CCB5-4717-8DB0-6EEC42CDA866}']
{ Property Accessors }
function Get_Source(Index: Integer): IXMLSourceType;
{ Methods & Properties }
function Add: IXMLSourceType;
function Insert(const Index: Integer): IXMLSourceType;
property Source[Index: Integer]: IXMLSourceType read Get_Source; default;
end;
{ IXMLSourceType }
IXMLSourceType = interface(IXMLNode)
['{AEAAFC24-F86F-4D32-A214-545D9B04C4AE}']
{ Property Accessors }
function Get_Id: Integer;
function Get_ValSrcType: Integer;
function Get_ValType: Integer;
function Get_AggrType: Integer;
function Get_UTime1: Cardinal;
function Get_UTime2: Cardinal;
function Get_AggrIntervalLen: Integer;
function Get_DiagramType: Integer;
procedure Set_DiagramType(Value: Integer);
procedure Set_AggrIntervalLen(Value: Integer);
procedure Set_Id(Value: Integer);
procedure Set_ValSrcType(Value: Integer);
procedure Set_ValType(Value: Integer);
procedure Set_AggrType(Value: Integer);
procedure Set_UTime1(Value: Cardinal);
procedure Set_UTime2(Value: Cardinal);
{ Methods & Properties }
property Id: Integer read Get_Id write Set_Id;
property ValSrcType: Integer read Get_ValSrcType write Set_ValSrcType;
property ValType: Integer read Get_ValType write Set_ValType;
property DiagramType: Integer read Get_DiagramType write Set_DiagramType;
property AggrType: Integer read Get_AggrType write Set_AggrType;
property AggrIntervalLen: Integer read Get_AggrIntervalLen write Set_AggrIntervalLen;
property UTime1: Cardinal read Get_UTime1 write Set_UTime1;
property UTime2: Cardinal read Get_UTime2 write Set_UTime2;
end;
{ Forward Decls }
TXMLGMIORequestType = class;
TXMLAuthType = class;
TXMLDataType = class;
TXMLSourcesType = class;
TXMLSourceType = class;
{ TXMLGMIORequestType }
TXMLGMIORequestType = class(TXMLNode, IXMLGMIORequestType)
protected
{ IXMLGMIORequestType }
function Get_Auth: IXMLAuthType;
function Get_Structure: Integer;
function Get_Data: IXMLDataType;
function Get_State: IXMLStateType;
function Get_Comment: UnicodeString;
procedure Set_Comment(Value: UnicodeString);
procedure Set_Structure(Value: Integer);
public
procedure AfterConstruction; override;
end;
{ IXMLStateType }
TXMLStateType = class(TXMLNode, IXMLStateType)
protected
{ IXMLStateType }
function Get_RemoteServerReady: integer;
procedure Set_RemoteServerReady(Value: integer);
end;
{ TXMLAuthType }
TXMLAuthType = class(TXMLNode, IXMLAuthType)
protected
{ IXMLAuthType }
function Get_Login: UnicodeString;
function Get_Password: UnicodeString;
function Get_RemoteName: UnicodeString;
function Get_RequestID: UnicodeString;
procedure Set_RequestID(Value: UnicodeString);
procedure Set_RemoteName(Value: UnicodeString);
procedure Set_Login(Value: UnicodeString);
procedure Set_Password(Value: UnicodeString);
end;
{ TXMLDataType }
TXMLDataType = class(TXMLNode, IXMLDataType)
protected
{ IXMLDataType }
function Get_Sources: IXMLSourcesType;
function Get_SQL: UnicodeString;
function Get_OPC: Integer;
procedure Set_SQL(Value: UnicodeString);
procedure Set_OPC(Value: Integer);
public
procedure AfterConstruction; override;
end;
{ TXMLSourcesType }
TXMLSourcesType = class(TXMLNodeCollection, IXMLSourcesType)
protected
{ IXMLSourcesType }
function Get_Source(Index: Integer): IXMLSourceType;
function Add: IXMLSourceType;
function Insert(const Index: Integer): IXMLSourceType;
public
procedure AfterConstruction; override;
end;
{ TXMLSourceType }
TXMLSourceType = class(TXMLNode, IXMLSourceType)
protected
{ IXMLSourceType }
function Get_Id: Integer;
function Get_ValSrcType: Integer;
function Get_ValType: Integer;
function Get_AggrType: Integer;
function Get_UTime1: Cardinal;
function Get_UTime2: Cardinal;
function Get_AggrIntervalLen: Integer;
function Get_DiagramType: Integer;
procedure Set_DiagramType(Value: Integer);
procedure Set_AggrIntervalLen(Value: Integer);
procedure Set_Id(Value: Integer);
procedure Set_ValSrcType(Value: Integer);
procedure Set_ValType(Value: Integer);
procedure Set_AggrType(Value: Integer);
procedure Set_UTime1(Value: Cardinal);
procedure Set_UTime2(Value: Cardinal);
end;
{ Global Functions }
function GetGMIORequest(Doc: IXMLDocument): IXMLGMIORequestType;
function LoadGMIORequest(const FileName: string): IXMLGMIORequestType;
function NewGMIORequest: IXMLGMIORequestType;
function LoadXMLData_GMIORequest(const xml: string): IXMLGMIORequestType;
const
TargetNamespace = '';
implementation
{ Global Functions }
uses GMGlobals;
function GetGMIORequest(Doc: IXMLDocument): IXMLGMIORequestType;
begin
Result := Doc.GetDocBinding('GMIORequest', TXMLGMIORequestType, TargetNamespace) as IXMLGMIORequestType;
end;
function LoadGMIORequest(const FileName: string): IXMLGMIORequestType;
begin
Result := LoadXMLDocument(FileName).GetDocBinding('GMIORequest', TXMLGMIORequestType, TargetNamespace) as IXMLGMIORequestType;
end;
function NewGMIORequest: IXMLGMIORequestType;
begin
Result := NewXMLDocument.GetDocBinding('GMIORequest', TXMLGMIORequestType, TargetNamespace) as IXMLGMIORequestType;
Result.Auth.RequestID := GenerateGUID();
end;
function LoadXMLData_GMIORequest(const xml: string): IXMLGMIORequestType;
begin
Result := LoadXMLData(xml).GetDocBinding('GMIORequest', TXMLGMIORequestType, TargetNamespace) as IXMLGMIORequestType;
end;
{ TXMLGMIORequestType }
procedure TXMLGMIORequestType.AfterConstruction;
begin
RegisterChildNode('Auth', TXMLAuthType);
RegisterChildNode('Data', TXMLDataType);
RegisterChildNode('State', TXMLStateType);
inherited;
end;
function TXMLGMIORequestType.Get_Auth: IXMLAuthType;
begin
Result := ChildNodes['Auth'] as IXMLAuthType;
end;
function TXMLGMIORequestType.Get_Comment: UnicodeString;
begin
Result := AttributeNodes['Comment'].Text;
end;
function TXMLGMIORequestType.Get_State: IXMLStateType;
begin
Result := ChildNodes['State'] as IXMLStateType;
end;
function TXMLGMIORequestType.Get_Structure: Integer;
begin
Result := ChildNodes['Structure'].NodeValue;
end;
procedure TXMLGMIORequestType.Set_Comment(Value: UnicodeString);
begin
AttributeNodes['Comment'].Text := Value;
end;
procedure TXMLGMIORequestType.Set_Structure(Value: Integer);
begin
ChildNodes['Structure'].NodeValue := Value;
end;
function TXMLGMIORequestType.Get_Data: IXMLDataType;
begin
Result := ChildNodes['Data'] as IXMLDataType;
end;
{ TXMLAuthType }
function TXMLAuthType.Get_Login: UnicodeString;
begin
Result := AttributeNodes['Login'].Text;
end;
procedure TXMLAuthType.Set_Login(Value: UnicodeString);
begin
SetAttribute('Login', Value);
end;
function TXMLAuthType.Get_Password: UnicodeString;
begin
Result := AttributeNodes['Password'].Text;
end;
function TXMLAuthType.Get_RemoteName: UnicodeString;
begin
Result := AttributeNodes['RemoteName'].Text;
end;
function TXMLAuthType.Get_RequestID: UnicodeString;
begin
Result := AttributeNodes['RequestID'].Text;
end;
procedure TXMLAuthType.Set_Password(Value: UnicodeString);
begin
SetAttribute('Password', Value);
end;
procedure TXMLAuthType.Set_RemoteName(Value: UnicodeString);
begin
SetAttribute('RemoteName', Value);
end;
procedure TXMLAuthType.Set_RequestID(Value: UnicodeString);
begin
SetAttribute('RequestID', Value);
end;
{ TXMLDataType }
procedure TXMLDataType.AfterConstruction;
begin
RegisterChildNode('Sources', TXMLSourcesType);
inherited;
end;
function TXMLDataType.Get_Sources: IXMLSourcesType;
begin
Result := ChildNodes['Sources'] as IXMLSourcesType;
end;
function TXMLDataType.Get_SQL: UnicodeString;
begin
Result := ChildNodes['SQL'].Text;
end;
procedure TXMLDataType.Set_SQL(Value: UnicodeString);
begin
ChildNodes['SQL'].NodeValue := Value;
end;
function TXMLDataType.Get_OPC: Integer;
begin
Result := ChildNodes['OPC'].NodeValue;
end;
procedure TXMLDataType.Set_OPC(Value: Integer);
begin
ChildNodes['OPC'].NodeValue := Value;
end;
{ TXMLSourcesType }
procedure TXMLSourcesType.AfterConstruction;
begin
RegisterChildNode('Source', TXMLSourceType);
ItemTag := 'Source';
ItemInterface := IXMLSourceType;
inherited;
end;
function TXMLSourcesType.Get_Source(Index: Integer): IXMLSourceType;
begin
Result := List[Index] as IXMLSourceType;
end;
function TXMLSourcesType.Add: IXMLSourceType;
begin
Result := AddItem(-1) as IXMLSourceType;
end;
function TXMLSourcesType.Insert(const Index: Integer): IXMLSourceType;
begin
Result := AddItem(Index) as IXMLSourceType;
end;
{ TXMLSourceType }
function TXMLSourceType.Get_Id: Integer;
begin
Result := AttributeNodes['Id'].NodeValue;
end;
procedure TXMLSourceType.Set_Id(Value: Integer);
begin
SetAttribute('Id', Value);
end;
function TXMLSourceType.Get_ValSrcType: Integer;
begin
Result := AttributeNodes['ValSrcType'].NodeValue;
end;
procedure TXMLSourceType.Set_ValSrcType(Value: Integer);
begin
SetAttribute('ValSrcType', Value);
end;
function TXMLSourceType.Get_ValType: Integer;
begin
Result := AttributeNodes['ValType'].NodeValue;
end;
procedure TXMLSourceType.Set_ValType(Value: Integer);
begin
SetAttribute('ValType', Value);
end;
function TXMLSourceType.Get_AggrIntervalLen: Integer;
begin
Result := AttributeNodes['AggrIntrvlLen'].NodeValue;
end;
function TXMLSourceType.Get_AggrType: Integer;
begin
Result := AttributeNodes['AggrType'].NodeValue;
end;
function TXMLSourceType.Get_DiagramType: Integer;
begin
Result := AttributeNodes['DiagramType'].NodeValue;
end;
procedure TXMLSourceType.Set_AggrIntervalLen(Value: Integer);
begin
SetAttribute('AggrIntrvlLen', Value);
end;
procedure TXMLSourceType.Set_AggrType(Value: Integer);
begin
SetAttribute('AggrType', Value);
end;
procedure TXMLSourceType.Set_DiagramType(Value: Integer);
begin
SetAttribute('DiagramType', Value);
end;
function TXMLSourceType.Get_UTime1: Cardinal;
begin
Result := AttributeNodes['UTime1'].NodeValue;
end;
procedure TXMLSourceType.Set_UTime1(Value: Cardinal);
begin
SetAttribute('UTime1', Value);
end;
function TXMLSourceType.Get_UTime2: Cardinal;
begin
Result := AttributeNodes['UTime2'].NodeValue;
end;
procedure TXMLSourceType.Set_UTime2(Value: Cardinal);
begin
SetAttribute('UTime2', Value);
end;
{ TXMLStateType }
function TXMLStateType.Get_RemoteServerReady: integer;
begin
Result := ChildNodes['RemoteServerReady'].NodeValue;
end;
procedure TXMLStateType.Set_RemoteServerReady(Value: integer);
begin
ChildNodes['RemoteServerReady'].NodeValue := Value;
end;
initialization
NullStrictConvert := false;
end.
|
unit Devices.Altistart22;
interface
uses GMConst, Devices.Modbus.ReqCreatorBase;
type
TAltistart22ReqCreator = class(TModbusRTUDevReqCreator)
public
procedure AddRequests(); override;
end;
const
// Линейное напряжение
ADDR_ALTISTART22_ALL = 257;
COUNT_ALTISTART22_ALL = 23;
ADDR_ALTISTART22_LCR1 = ADDR_ALTISTART22_ALL;
ADDR_ALTISTART22_LCR2 = ADDR_ALTISTART22_ALL + 1;
ADDR_ALTISTART22_LCR3 = ADDR_ALTISTART22_ALL + 2;
ADDR_ALTISTART22_LFT = 279;
ADDR_ALTISTART22_U = 260;
implementation
{ TAltistart22ReqCreator }
procedure TAltistart22ReqCreator.AddRequests;
begin
// Всем колхозом
AddModbusRequestToSendBuf(ADDR_ALTISTART22_ALL, COUNT_ALTISTART22_ALL, rqtAltistart22_All);
end;
end.
|
unit Bank_i;
{This file was generated on 11 Aug 2000 20:11:55 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : Bank_i }
{derived from IDL module : Bank }
interface
uses
CORBA;
type
errStruct = interface;
Account = interface;
errStruct = interface
['{51C5AB89-24C5-143C-323E-5CFEBEF27D21}']
function _get_myInt : SmallInt;
procedure _set_myInt (const myInt : SmallInt);
function _get_myStr : AnsiString;
procedure _set_myStr (const myStr : AnsiString);
property myInt : SmallInt read _get_myInt write _set_myInt;
property myStr : AnsiString read _get_myStr write _set_myStr;
end;
Account = interface
['{838D242D-0A78-C1F6-EDEA-1E5B70BB4C8E}']
function balance : Single;
procedure deposit (const value : Single);
procedure withdrawl (const value : Single);
procedure DoException ;
end;
implementation
initialization
end. |
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.10
* @Brief:
*}
unit org.utilities;
interface
type
TLogLevel = (llFatal, llError, llWarning, llNormal, llDebug);
TLogNotify = procedure (Sender: TObject; LogLevel: TLogLevel; LogContent: string) of object;
const
LOG_LEVLE_DESC: array [TLogLevel] of string = (
'ÖÂÃü',
'´íÎó',
'¾¯¸æ',
'ÆÕͨ',
'µ÷ÊÔ'
);
implementation
end.
|
unit UnExportacaoFiscal;
interface
Uses Classes, db, SQLExpr, comctrls, SysUtils, UnDados;
Type TRBFuncoesExportacaoFiscal = class
private
Aux,
Estados,
Tabela,
Produtos : TSQLQuery;
procedure LocalizaPessoasExportacao(VpaTabela : TDataSet; VpaCodFilial : Integer; VpaDataInicial,VpaDataFinal: TDateTime);
procedure LocalizaNotasExportacao(VpaTabela : TDataSet;VpaCodFilial : Integer; VpaDataInicial,VpaDataFinal: TDateTime; VpaUF : String);
procedure LocalizaProdutosExportacao(VpaTabela : TDataSet;VpaCodFilial : Integer; VpaDataInicial,VpaDataFinal: TDateTime; VpaUF : String);
procedure SintegraGeraArquivo(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure SintegraGeraArquivoporEstado(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure SintegraAdicionaRegistro10e11(VpaCodFilia : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaArquivo : TStringList);
procedure SintegraAdicionaRegistro50(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure LINCEExportarPessoas(VpaTabela: TDataSet; VpaDiretorio: string;VpaBarraStatus : TStatusBar);
procedure LINCEExportarNotas(VpaTabela: TDataSet; VpaDiretorio: string;VpaBarraStatus : TStatusBar);
procedure WKLiscalDosExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure WKLiscalDosExportarNotas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar);
procedure WkLiscalDosAdicionaParcelasNota(VpaArquivo : TStringList;VpaCodFilial, VpaSeqNota : Integer);
function WkLiscalDosMontaNatureza(VpaCodNatureza, VpaTipoPagamento : String;VpaPerAliquota : Double) : String;
function WkLiscalRCodigoAliquota(VpaPerAliquota :Double) : String;
procedure WKRadarExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure SCISupremaExportaPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure SCISupremaExportaNotasVpa(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure MTFiscalExportaPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure MTFiscalExportarNotas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdicionaRegistro10e11(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaArquivo : TStringList);
procedure ValidaPRAdiconaRegistro50(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdiconaRegistro51(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdiconaRegistro53(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdiconaRegistro54(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdiconaRegistro50e51e53e54(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar;Var VpaQtdRegistro50, VpaQtdRegistro51, VpaQtdRegistro53, VpaQtdRegistro54 : Integer);
procedure ValidaPRAdicionaRegistro74(VpaTabela : TDataSet; VpaDatInventario : TDateTime; Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdicionaRegistro75(VpaTabela : TDataSet; VpaDatInicial, VpaDatFinal : TDateTime; Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdicionaRegistro74e75(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar;Var VpaQtdRegistro74, VpaQtdRegistro75 : Integer);
procedure ValidaPRAdiconaRegistro60Me60Ae60R(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
procedure ValidaPRAdicionaRegistro90porTipo(VpaQtdRegistro,VpaTipoRegistro : Integer;VpaCNPJ,VpaInscricaoEstadual : String;VpaArquivo : TStringList);
procedure ValidaPRAdicionaRegistro90(VpaCNPJ, VpaInscricaoEstadual : String;VpaQtdRegistro50, VpaQtdRegistro51,VpaQtdRegistro53,VpaQtdRegistro54,VpaQtdRegistro74,VpaQtdRegistro75 : Integer;VpaArquivo: TStringList);
procedure ValidaPRExportaNotas(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure DominioExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure DominioExportaNotas(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
procedure DominioCabecalhoNotas(VpaDatInicio, VpaDatFim : TDatetime;VpaArquivo : TStringList);
procedure DominioExportaNotasRegistro2(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaBarraStatus : TStatusBar;VpaCritica :TStringList;VpaArquivo : TStringList);
procedure TextoStatusBar(VpaStatusBar : TStatusBar;VpaTexto : String);
procedure ValidaVariaveisExportacaoFiscal(VpaCritica : TStringList);
function RAliquotaNota(VpaCodfilial, VpaSeqNota : Integer) : Double;
function RCodigoFiscalMunicipio(VpaDesCidade, VpaDesUF : string) : String;
function RInscricaoEstadualFilial(VpaCodFilial : Integer) :String;
public
constructor cria(VpaBaseDados : TSQLConnection );
destructor destroy;override;
procedure ExportarNotasPessoas(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
end;
implementation
Uses FunString, UnClientes, Constantes, FunSql, FunData, FunArquivos, funValida, UnNotaFiscal, unSistema;
{******************************************************************************}
constructor TRBFuncoesExportacaoFiscal.cria(VpaBaseDados : TSQLConnection );
begin
inherited create;
Aux := TSQLQuery.Create(nil);
Aux.SQLCOnnection := VpaBaseDados;
Tabela := TSQLQuery.Create(nil);
Tabela.SQLCOnnection := VpaBaseDados;
Estados := TSQLQuery.Create(nil);
Estados.SQLCOnnection := VpaBaseDados;
Produtos := TSQLQuery.Create(nil);
Produtos.SQLCOnnection := VpaBaseDados;
end;
{******************************************************************************}
destructor TRBFuncoesExportacaoFiscal.destroy;
begin
Aux.free;
Tabela.free;
Estados.free;
inherited destroy;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.LocalizaPessoasExportacao(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDataInicial,VpaDataFinal: TDateTime);
begin
FechaTabela(VpaTabela);
LimpaSQLTabela(VpaTabela);
AdicionaSQLTabela(VpaTabela,' select CLI.I_COD_CLI, CLI.C_NOM_CLI, CLI.C_TIP_PES, ' +
SQLTextoIsNull('CLI.C_CGC_CLI','CLI.C_CPF_CLI')+' CNPJ_CPF, CLI.C_END_CLI, CLI.C_BAI_CLI, ' +
' CLI.C_EST_CLI, CLI.C_CID_CLI, C_CEP_CLI, C_FO1_CLI,CLI.C_FON_FAX,CLI.C_NOM_FAN, CLI.C_INS_CLI, CLI.C_TIP_CAD, ' +
' CLI.C_COM_END, CLI.I_NUM_END, CLI.C_IND_AGR '+
' from CADCLIENTES CLI ' +
' where exists (Select * from CADNOTAFISCAIS CAD '+
' Where CAD.I_COD_CLI = CLI.I_COD_CLI ' +
' and CAD.I_NRO_NOT IS NOT NULL '+
' and '+SQLTextoIsNull('CAD.C_FLA_ECF','''N''')+' = ''N'' ' +
' and CAD.I_EMP_FIL = '+ IntToStr(VpaCodFilial)+
SQLTextoDataEntreAAAAMMDD('CAD.D_DAT_EMI', VpaDataInicial, VpaDataFinal, True)+
' )');
AbreTabela(VpaTabela);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.LocalizaNotasExportacao(VpaTabela : TDataSet;VpaCodFilial : Integer; VpaDataInicial,VpaDataFinal: TDateTime; VpaUF : String);
begin
FechaTabela(VpaTabela);
LimpaSQLTabela(VpaTabela);
AdicionaSQLTabela(VpaTabela,
' select '+SqlTextoIsNull('CLI.C_CGC_CLI','CLI.C_CPF_CLI')+' CNPJ_CPF, CLI.I_COD_CLI, CLI.C_EST_CLI, C_INS_CLI, FIL.C_EST_FIL, ' +
' FIL.C_CGC_FIL, CAD.I_NRO_NOT, CAD.C_SER_NOT, CAD.D_DAT_EMI, CAD.N_TOT_NOT, CAD.N_BAS_CAL, ' +
' CAD.N_VLR_ICM, CAD.N_TOT_IPI, CAD.N_VLR_ISQ, CAD.L_OB1_NOT, CAD.C_COD_NAT, CAD.I_SEQ_NOT,'+
' CAD.I_TIP_FRE, CAD.N_VLR_FRE, CAD.I_EMP_FIL, CAD.N_VLR_SEG, N_OUT_DES, CAD.C_NOT_CAN, '+
' CAD.I_COD_PAG, CAD.N_TOT_PRO, CAD.N_TOT_SER, CAD.N_PER_ISQ, CAD.N_VLR_ISQ, CAD.C_CHA_NFE, '+
' CLI.C_TIP_PES, CLI.C_CID_CLI '+
' from CADNOTAFISCAIS CAD, CADCLIENTES CLI, CADFILIAIS FIL' +
' where CAD.I_COD_CLI = CLI.I_COD_CLI ' +
' and CAD.I_EMP_FIL = FIL.I_EMP_FIL ' +
' and CAD.I_NRO_NOT IS NOT NULL '+
' and CAD.C_SER_NOT = '''+Varia.SerieNota+''''+
' and '+SqlTextoisNull('CAD.C_FLA_ECF','''N''')+' = ''N'' ' +
' and CAD.I_EMP_FIL = '+IntToStr(VpaCodfilial)+
// ' and CAD.I_NRO_NOT = 6561 ' +
SQLTextoDataEntreAAAAMMDD('CAD.D_DAT_EMI', VpaDataInicial, VpaDataFinal, True));
if VpaUF <> '' then
AdicionaSQLTabela(VpaTabela,' AND CLI.C_EST_CLI = '''+VpaUF+'''');
AdicionaSQLTabela(VpaTabela,'order by cad.I_SEQ_NOT');
AbreTabela(VpaTabela);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.LocalizaProdutosExportacao(VpaTabela : TDataSet;VpaCodFilial : Integer; VpaDataInicial,VpaDataFinal: TDateTime; VpaUF : String);
begin
LimpaSQlTabela(VpaTabela);
AdicionaSQLTabela(VpaTabela,'select PRO.C_COD_PRO, QTD.N_QTD_PRO, QTD.N_VLR_CUS, PRO.C_NOM_PRO, C_COD_UNI, '+
' PRO.N_PER_IPI, PRO.N_RED_ICM '+
' from CADPRODUTOS PRO, MOVQDADEPRODUTO QTD '+
' Where PRO.I_SEQ_PRO = QTD.I_SEQ_PRO '+
' AND QTD.I_EMP_FIL = '+IntToStr(VpaCodFilial)+
' AND EXISTS ( SELECT CAD.I_SEQ_NOT FROM CADNOTAFISCAIS CAD, MOVNOTASFISCAIS MOV, CADCLIENTES CLI '+
' Where CAD.I_EMP_FIL = '+IntTosTr(VpaCodFilial)+
SQLTextoDataEntreAAAAMMDD('CAD.D_DAT_EMI',VpaDataInicial,VpaDataFinal,true)+
' AND CAD.I_EMP_FIL = MOV.I_EMP_FIL '+
' AND CAD.I_SEQ_NOT = MOV.I_SEQ_NOT ' +
' AND CAD.I_COD_CLI = CLI.I_COD_CLI ');
if VpaUF <> '' then
AdicionaSQLTabela(VpaTabela,' AND CLI.C_EST_CLI = '''+VpaUF+'''');
AdicionaSQLTabela(VpaTabela,' AND MOV.I_SEQ_PRO = PRO.I_SEQ_PRO)');
AdicionaSQLTabela(VpaTabela,' order by PRO.C_COD_PRO');
VpaTabela.Open;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SintegraGeraArquivo(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfArquivo : TStringList;
begin
VpfArquivo := TStringList.create;
TextoStatusBar(VpaBarraStatus,'4 Adicionando registro 10');
SintegraAdicionaRegistro10e11(VpaCodFilial,VpaDataInicial,VpaDataFinal, VpfArquivo);
SintegraAdicionaRegistro50(VpaCodFilial,VpaDataInicial,VpaDataFinal,'',VpfArquivo,VpaCritica,VpaBarraStatus);
VpfArquivo.SaveToFile(VpaDiretorio+InttoStr(Ano(VpaDataInicial))+AdicionaCharE('0',InttoStr(Mes(VpaDataInicial)),2)+'.txt');
VpfArquivo.free;
SintegraGeraArquivoporEstado(VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SintegraGeraArquivoporEstado(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfArquivo : TStringList;
begin
AdicionaSQLAbreTabela(Estados,'Select DISTINCT(C_EST_CLI) ESTADO '+
' from CADNOTAFISCAIS CAD, CADCLIENTES CLI '+
' where CAD.I_COD_CLI = CLI.I_COD_CLI ' +
' and CAD.I_NRO_NOT IS NOT NULL '+
' and CAD.C_SER_NOT = '''+Varia.SerieNota+''''+
' and '+SqlTextoIsnull('CAD.C_FLA_ECF','''N''')+' = ''N'' ' +
' and CAD.I_EMP_FIL = '+IntToStr(VpaCodfilial)+
SQLTextoDataEntreAAAAMMDD('CAD.D_DAT_EMI', VpaDataInicial, VpaDataFinal, True)+
' and CLI.C_EST_CLI <> '''+Varia.UFFilial+'''');
While not Estados.Eof do
begin
VpfArquivo := TStringList.create;
TextoStatusBar(VpaBarraStatus,'4 Adicionando registro 10');
SintegraAdicionaRegistro10e11(VpaCodFilial,VpaDataInicial,VpaDataFinal, VpfArquivo);
SintegraAdicionaRegistro50(VpaCodFilial,VpaDataInicial,VpaDataFinal,Estados.FieldByName('ESTADO').AsString, VpfArquivo,VpaCritica,VpaBarraStatus);
VpfArquivo.SaveToFile(VpaDiretorio+Estados.FieldByName('ESTADO').AsString+ InttoStr(Ano(VpaDataInicial))+AdicionaCharE('0',InttoStr(Mes(VpaDataInicial)),2)+'.txt');
VpfArquivo.free;
Estados.next;
end;
Estados.close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SintegraAdicionaRegistro10e11(VpaCodFilia : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaArquivo : TStringList);
var
VpfLinha : String;
begin
AdicionaSQLAbreTabela(Tabela,'Select * from CADFILIAIS '+
' Where I_EMP_FIL = '+IntToStr(VpaCodfilia));
VpfLinha := '10'+
//CGC
DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('C_CGC_FIL').AsString,'.'),'/'),'-')+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',DeletaChars(DeletaChars(Tabela.FieldByName('C_INS_FIL').AsString,'.'),'-'),14)+
//NOME DO CONTRIBUINTE
AdicionaCharD(' ',COPY(Tabela.FieldByName('C_NOM_FIL').AsString,1,35),35)+
//MUNICIPIO
AdicionaCharD(' ',COPY(Tabela.FieldByName('C_CID_FIL').AsString,1,30),30)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',Tabela.FieldByName('C_EST_FIL').AsString,2)+
//FAX
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(COPY(Tabela.FieldByName('C_FON_FIL').AsString,5,15),')'),' '),'-'),10)+
//DATA INICIAL
FormatDateTime('YYYYMMDD',VpaDatInicial)+
//DATA FINAL
FormatDateTime('YYYYMMDD',VpaDatFinal)+
//CODIGO DO CONVENIO
'3'+
//CODIGO DA IDENTIFICACAO DAS NATUREZAS INFORMADAS
'3'+
//CODIGO DA FINALIDADE DO ARQUIVO MAGNETICO
'1';
VpaArquivo.Add(VpfLinha);
//registro 11
VpfLinha := '11'+
//Logradouro
AdicionaCharD(' ',copy(Tabela.FieldByName('C_END_FIL').AsString,1,34),34)+
//NUMERO
AdicionaCharE('0',Tabela.FieldByName('I_NUM_FIL').AsString,5)+
//COMPLEMENTO
AdicionaCharD(' ','',22)+
//BAIRRO
AdicionaCharD(' ',Tabela.FieldByName('C_BAI_FIL').AsString,15)+
//CEP
AdicionaCharE('0',Tabela.FieldByName('I_CEP_FIL').AsString,8)+
//NOME DE CONTATO
AdicionaCharD(' ',Tabela.FieldByName('C_DIR_FIL').AsString,28)+
//TELEFONE CONTATO
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(COPY(Tabela.FieldByName('C_FAX_FIL').AsString,5,15),')'),' '),'-'),12);
VpaArquivo.Add(VpfLinha);
Tabela.Close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SintegraAdicionaRegistro50(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
Var
VpfLinha : String;
VpfQtdRegistros50, VpfQtdRegistros51 : Integer;
VpfInscricaoEstadual, VpfInscricaoEstadualFilial : String;
begin
VpfInscricaoEstadualFilial := RInscricaoEstadualFilial(VpaCodFilial);
VpfQtdRegistros50 := 0;
VpfQtdRegistros51 := 0;
TextoStatusBar(VpaBarraStatus,'4 Localizando as notas fiscais');
LocalizaNotasExportacao(Tabela,VpaCodFilial,VpaDatInicial,VpaDatFinal,VpaUF);
While not Tabela.Eof do
begin
inc(VpfQtdRegistros50);
TextoStatusBar(VpaBarraStatus,'4 Validando a inscrição estadual');
VpfInscricaoEstadual := DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('C_INS_CLI').AsString,'.'),'-'),'/');
if (VpfInscricaoEstadual = '') or (Tabela.FieldByName('C_TIP_PES').AsString = 'F') then
VpfInscricaoEstadual := 'ISENTO';
if (Tabela.FieldByName('C_TIP_PES').AsString = 'F') then
begin
if not VerificaCPF(Tabela.FieldByName('CNPJ_CPF').AsString) then
VpaCritica.Add('Cadastro do Cliente "'+Tabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! CPF inválida');
end
else
begin
if not VerificarIncricaoEstadual(VpfInscricaoEstadual,Tabela.FieldByName('C_EST_CLI').AsString,false,true) then
VpaCritica.Add('Cadastro do Cliente "'+Tabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual inválida');
if VpfInscricaoEstadual = VpfInscricaoEstadualFilial then
VpaCritica.Add('Cadastro do Cliente "'+Tabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual é a mesma da "'+varia.NomeFilial+'"');
end;
TextoStatusBar(VpaBarraStatus,'4 Inserindo registro 50 da nota fiscal "'+Tabela.FieldByName('I_NRO_NOT').AsString+'"');
//codigo do registro
VpfLinha := '50'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',VpfInscricaoEstadual,14)+
//DATA DE EMISSAO
FormatDateTime('YYYYMMDD',Tabela.FieldByName('D_DAT_EMI').AsDateTime)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',Tabela.FieldByName('C_EST_CLI').AsString,2)+
//MODELO
'01'+
//SERIE DA NOTA
AdicionaCharD(' ',Tabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',Tabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(Tabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//EMITENTE DA NOTA FISCAL
'P'+
//VALOR TOTAL
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Tabela.FieldByName('N_TOT_NOT').AsFloat),','),13)+
//BASE DE CALCULO DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Tabela.FieldByName('N_BAS_CAL').AsFloat),','),13)+
//VALOR DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Tabela.FieldByName('N_VLR_ICM').AsFloat),','),13)+
// ISENTA OU NÃO TRIBUTADA
AdicionaCharE('0','0',13)+
// OUTRAS
AdicionaCharE('0','0',13)+
//ALIQUOTA
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',RAliquotaNota(Tabela.FieldByName('I_EMP_FIL').AsInteger,Tabela.FieldByName('I_SEQ_NOT').AsInteger)),','),4)+
//SITUACAO DA NOTA FISCAL
AdicionaCharE('N',Tabela.FieldByName('C_NOT_CAN').AsString,1);
VpaArquivo.Add(VpfLinha);
Tabela.Next;
end;
Tabela.First;
While not Tabela.Eof do
begin
inc(VpfQtdRegistros51);
if (varia.CNPJFilial = CNPJ_Kairos) then
begin
TextoStatusBar(VpaBarraStatus,'3 Inserindo registro 51 da nota fiscal "'+Tabela.FieldByName('I_NRO_NOT').AsString+'"');
//codigo do registro
VpfLinha := '51'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',VpfInscricaoEstadual,14)+
//DATA DE EMISSAO
FormatDateTime('YYYYMMDD',Tabela.FieldByName('D_DAT_EMI').AsDateTime)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',Tabela.FieldByName('C_EST_CLI').AsString,2)+
//SERIE DA NOTA
AdicionaCharD(' ',Tabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',Tabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(Tabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//VALOR TOTAL
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Tabela.FieldByName('N_TOT_NOT').AsFloat),','),13)+
//VALOR DO IPI
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Tabela.FieldByName('N_TOT_IPI').AsFloat),','),13)+
// ISENTA OU NÃO TRIBUTADA
AdicionaCharE('0','0',13)+
// OUTRAS
AdicionaCharE('0','0',13)+
//BRANCOS 20
AdicionaCharE(' ','',20)+
//SITUACAO DA NOTA FISCAL
AdicionaCharE('N',Tabela.FieldByName('C_NOT_CAN').AsString,1);
VpaArquivo.Add(VpfLinha);
end;
Tabela.Next;
end;
TextoStatusBar(VpaBarraStatus,'4 Inserindo registro tipo 90');
AdicionaSQLAbreTabela(Tabela,'Select * from CADFILIAIS '+
' Where I_EMP_FIL = '+IntToStr(VpaCodfilial));
//registro do tipo 90
VpfLinha := '90' +
//CGC
DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('C_CGC_FIL').AsString,'.'),'/'),'-')+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',DeletaChars(DeletaChars(Tabela.FieldByName('C_INS_FIL').AsString,'.'),'-'),14)+
//TIPO DO REGISTRO A SER TOTALIZADO
'50'+
//TOTAL DE REGISTROS
AdicionaCharE('0',IntToStr(VpfQtdRegistros50),8)+
'51'+
//TOTAL DE REGISTROS
AdicionaCharE('0',IntToStr(VpfQtdRegistros51),8)+
//TOTAL GERAL DOS REGISTROS
'99'+AdicionaCharE('0',IntToStr(VpfQtdRegistros50+VpfQtdRegistros51+3),8);
VpfLinha := AdicionaCharD(' ',VPFLINHA,125)+ '1';
VpaArquivo.add(VpfLinha);
Tabela.Close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.LinceExportarPessoas(VpaTabela: TDataSet; VpaDiretorio: string;VpaBarraStatus : TStatusBar);
var
VpfTexto: TextFile;
VpfAuxStr: Ansistring;
begin
AssignFile(VpfTExto,VpaDiretorio + 'PESSOAS.txt');
Rewrite(VpfTexto);
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'2 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfAuxStr :=
//Field1=Codigo,Char,06,00,00
AdicionaCharD(' ',VpaTabela.fieldbyname('I_COD_CLI').AsString, 6) +
//Field2=Fantas,Char,20,00,06
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_NOM_CLI').AsString,20), 20) +
//Field3=Pessoa,Char,01,00,26
AdicionaCharD(' ',VpaTabela.fieldbyname('C_TIP_PES').AsString, 1) +
//Field4=CGCCPF,Char,18,00,27
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) +
//Field5=RazSoc,Char,50,00,45
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_NOM_CLI').AsString,50), 50) +
//Field6=Endere,Char,50,00,95
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_END_CLI').AsString,50), 50) +
//Field7=Bairro,Char,30,00,145
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_BAI_CLI').AsString,30), 30) +
//Field8=Estado,Char,02,00,175
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) +
//Field9=CodMun,Char,06,00,177
AdicionaCharD(' ',RCodigoFiscalMunicipio(VpaTabela.FieldByName('C_CID_CLI').AsString,VpaTabela.FieldByName('C_EST_CLI').AsString), 7) +
//Field10=NomMun,Char,30,00,183
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_CID_CLI').AsString,30), 30) +
//Field11=CepMun,Char,08,00,213
AdicionaCharD(' ',VpaTabela.fieldbyname('C_CEP_CLI').AsString, 8) +
//Field12=Telefo,Char,15,00,221
AdicionaCharD(' ',DeletaChars(VpaTabela.fieldbyname('C_FO1_CLI').AsString,'*'), 15) +
//Field13=Agrope,Char,01,00,236
AdicionaCharD('N',VpaTabela.fieldbyname('C_IND_AGR').AsString,1) +
//Field14=Inscri,Char,25,00,237
AdicionaCharD(' ',DeletaChars(VpaTabela.fieldbyname('C_INS_CLI').AsString,'-'), 25) +
//Field15=CtbFor,Char,10,00,262
AdicionaCharD(' ','', 10) +
//Field16=CtbCli,Char,10,00,272
AdicionaCharD(' ','', 10);
Writeln(VpfTExto,VpfAuxStr);
VpaTabela.Next;
end;
CloseFile(VpfTexto);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.LINCEExportarNotas(VpaTabela : TDataSet; VpaDiretorio: string;VpaBarraStatus : TStatusBar);
var
VpfTexto: TStringList;
VpfAuxStr, VpfNatureza,VpfContribuinte,VpfDesObservacao : string;
VpfValTotal, VpfValBase, VpfValAliquota,VpfValICMS, VpfValIPI, VpfValIsentas: Double;
VpfIndNotaCancelada : Boolean;
begin
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'2 Exportado dados da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
if VpaTabela.FieldByName('C_COD_NAT').AsString <> '' then
VpfNatureza := VpaTabela.FieldByName('C_COD_NAT').AsString
else
begin
if VpaTabela.FieldByName('C_EST_CLI').AsString <> 'SC' then
VpfNatureza := '6101'
else
VpfNatureza := '';
end;
IF VpaTabela.FieldByName('C_TIP_PES').AsString = 'F' then
VpfContribuinte := 'N'
else
VpfContribuinte := 'S';
VpfIndNotaCancelada := (VpaTabela.FieldByName('C_NOT_CAN').AsString = 'S');
if VpfIndNotaCancelada then
begin
VpfValTotal := 0;
VpfValBase := 0;
VpfValAliquota :=0;
VpfValIcms := 0;
VpfValIPI := 0;
VpfDesObservacao := 'NOTA FISCAL CANCELADA';
VpfValIsentas := 0
end
else
begin
VpfValTotal := VpaTabela.fieldbyname('N_TOT_NOT').AsFloat;
VpfValBase := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
VpfValIcms := VpaTabela.fieldbyname('N_VLR_ICM').AsFloat;
VpfValIpi := VpaTabela.fieldbyname('N_TOT_IPI').AsFloat;
VpfValAliquota := 12;
VpfValIsentas := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
VpfDesObservacao := DeletaChars(DeletaChars(CopiaEsquerda(VpaTabela.FieldByName('L_OB1_NOT').AsString,57),#13),'"');
end;
VpfAuxStr :=
//Field1=Fornec,Char,18,00,00
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) +
//Field2=EstDes,Char,02,00,18
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) +
//Field3=Operac,Char,06,00,20
AdicionaCharD(' ',VpfNatureza, 4) + '02'+
//Field4=EstOri,Char,02,00,26
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_FIL').AsString, 2) +
//Field5=MunOri,Char,06,00,28
AdicionaCharD(' ','', 6) +
//Field6=DocIni,Char,06,00,34
AdicionaCharD(' ',VpaTabela.fieldbyname('I_NRO_NOT').AsString, 6) +
//Field7=DocFin,Char,06,00,40
AdicionaCharD(' ',VpaTabela.fieldbyname('I_NRO_NOT').AsString, 6) +
//Field8=Especi,Char,04,00,46
AdicionaCharD(' ','NFE', 4) +
//Field9=DSerie,Char,03,00,50
AdicionaCharD(' ',VpaTabela.fieldbyname('C_SER_NOT').AsString, 3) +
//Field10=DatEmi,Char,10,00,53
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) +
//Field11=Contri,Char,01,00,63
AdicionaCharD('S',VpfContribuinte, 1) +
//Field12=VlCont,Float,20,02,64
AdicionaCharE(' ',FormatFloat('0.00',vpfValTotal), 20) +
//Field13=IcmAli,Float,20,02,84
AdicionaCharE(' ',FormatFloat('00.00',vpfValAliquota), 20) +
//Field14=IcmBsr,Char,01,00,104
AdicionaCharE('N','N', 1) +
//Field15=IcmRed,Float,20,02,105
AdicionaCharE(' ','0,00', 20) +
//Field16=IcmBsc,Float,20,02,125
AdicionaCharE(' ',FormatFloat('0.00',VpfValBase), 20) +
//Field17=IcmVlr,Float,20,02,145
AdicionaCharE(' ',FormatFloat('0.00',VpfValICMS), 20) +
//Field18=IcmIse,Float,20,02,165
AdicionaCharE(' ',FormatFloat('0.00',VpfValTotal), 20) +
//Field19=IcmOut,Float,20,02,185
AdicionaCharE(' ','0,00', 20) +
//Field20=AcrFin,Float,20,02,205
AdicionaCharE(' ','0,00', 20) +
//Field21=CplAli,Float,20,02,225
AdicionaCharE(' ','0,00', 20) +
//Field22=CplBsc,Float,20,02,245
AdicionaCharE(' ','0,00', 20) +
//Field23=CplVlr,Float,20,02,265
AdicionaCharE(' ','0,00', 20) +
//Field24=IpiBsc,Float,20,02,285
AdicionaCharE(' ','0,00', 20) +
//Field25=IpiVlr,Float,20,02,305
AdicionaCharE(' ',FormatFloat('0.00',VpfValIPI), 20) +
//Field26=IpiIse,Float,20,02,325
AdicionaCharE(' ','0,00', 20) +
//Field27=IpiOut,Float,20,02,345
AdicionaCharE(' ','0,00', 20) +
//Field28=IssAli,Float,20,02,365
AdicionaCharE(' ','0,00', 20) +
//Field29=IssBsc,Float,20,02,385
AdicionaCharE(' ','0,00', 20) +
//Field30=IssVlr,Float,20,02,405
AdicionaCharE(' ',FormatFloat('0.00',VpaTabela.fieldbyname('N_VLR_ISQ').AsFloat), 20) +
//Field31=Observ,Char,40,00,425
AdicionaCharE(' ',CopiaDireita(DeletaChars(VpfDesObservacao,#13), 40), 40) +
//Field32=TabCon,Char,04,00,465
AdicionaCharD(' ','', 4) +
//Field33=Esp,Char,04,00,469
AdicionaCharD(' ','xxxx', 4) +
//Field34=C75Cod,Char,02,00,473
AdicionaCharD(' ','01', 2);
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'SAIDA.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.WKLiscalDosExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfTexto: TStringList;
VpfAuxStr: string;
VpfCodFiscalMunicipio : String;
begin
//Exporta os clientes para o sistema LISCAL versão 447 for DOS da WK sistemas
//Dúvidas referente ao layout foram tiradas com o Arno da ERB no dia 17/08/2005 as 16:30
//Os campos textos tem que vir entre " aspas duplas e os numericos com zero a esquerda, com o separador de campo vírgula
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
if VpfCodFiscalMunicipio = '' then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! O município cadastrado "'+VpaTabela.FieldByName('C_CID_CLI').AsString+ '" não existe para o Fisco');
TextoStatusBar(VpaBarraStatus,'1 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfAuxStr :=
//01=Tipo de Operacao (A-Alteracao, E-Exclusão, I-Inclusão) X(01) **Sempre será I de inclusão, o Liscal se encarrega de verificar se o cliente já existe pelo CNPJ e caso existir altera os dados
'"I","'+
//02 -Codigo reduzido do fornecedor / cliente 9(8).
AdicionaCharE('0',VpaTabela.fieldbyname('I_COD_CLI').AsString, 8) +'","'+
//03 - Tipo (F-Fornecedor/C-Cliente/A-Ambos) X(1).
AdicionaCharD('C',VpaTabela.fieldbyname('C_TIP_CAD').AsString,1) + '","'+
//04 - Nome de fantasia X(19).
AdicionaCharD(' ',CopiaDireita(retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString),19),19) + '","'+
//05 - Razao Social X(47).
AdicionaCharD(' ',CopiaDireita(RetiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString),47), 47) + '","'+
//06 - Endereço X(47).
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_END_CLI').AsString,47), 47) + '","'+
//07 - Bairro X(31).
AdicionaCharD(' ',CopiaDireita(VpaTabela.fieldbyname('C_BAI_CLI').AsString,31), 31) + '","'+
//08 - Estado X(2).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) + '","'+
//09 - Codigo fiscal do municipio X(6)
AdicionaCharD(' ',VpfCodFiscalMunicipio, 6) + '","'+
//10 - Nome do municipio X(31)
AdicionaCharD(' ',UpperCase(RetiraAcentuacao(CopiaDireita(VpaTabela.fieldbyname('C_CID_CLI').AsString,31))), 31) +'","'+
//11 - CEP DO BAIRRO X(9)
AdicionaCharD(' ',VpaTabela.fieldbyname('C_CEP_CLI').AsString, 9) + '","'+
//12 - Numero DDD 9(4)
AdicionaCharE('0',FunClientes.RDDDCliente(VpaTabela.fieldbyname('C_FO1_CLI').AsString),4) + '","'+
//13 - Telefone X(08)
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FO1_CLI').AsString),8) + '","'+
//14 - FAX X(08)
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FON_FAX').AsString),8) + '","'+
//15 - TELEX X(08)
AdicionaCharD(' ','',8) + '","'+
//16 - CAIXA POSTAL X(5)
AdicionaCharD(' ','', 5) +'","'+
//17 - AGROPECUARIO (S/N) X(1)
AdicionaCharD(' ','N', 1) +'","'+
//18 - NUMERO DO CNPJ X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) +'","'+
//19 - NUMERO DA INSCRICAO ESTADUAL X(18)
VpaTabela.fieldbyname('C_INS_CLI').AsString +'","'+
//20 - CONTA CONTABIL DO FORNECEDOR 9(6)
AdicionaCharE('0',IntTostr(Varia.ContaContabilFornecedor),6) +'","'+
//21 - CONTA CONTABIL DO CLIENTE 9(6)
AdicionaCharE('0',inttostr(varia.ContaContabilCliente),6) +'","'+
//22 - NUMERO DA INSCRICAO MUNICIPAL X(15)
AdicionaCharD(' ','', 15) +'","'+
//23 - REGIME DE ICMS RETIDO NA FONTE
'N"';
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'LFDCD90.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.WKLiscalDosExportarNotas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar);
var
VpfTexto: TStringList;
VpfAuxStr, VpfNatureza,VpfContribuinte, VpfDesObservacao, VpfTipoCondicaoPgto: string;
VpfIndNotaCancelada : Boolean;
VpfValTotal, VpfValBase,VpfValIcms,VpfValAliquota, VpfValIPI : Double;
begin
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'1 Exportado dados da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
if VpaTabela.FieldByName('C_COD_NAT').AsString <> '' then
VpfNatureza := VpaTabela.FieldByName('C_COD_NAT').AsString
else
begin
if VpaTabela.FieldByName('C_EST_CLI').AsString <> 'SC' then
VpfNatureza := '6101'
else
VpfNatureza := '';
end;
IF VpaTabela.FieldByName('C_INS_CLI').AsString = '' then
VpfContribuinte := 'N'
else
VpfContribuinte := 'S';
if (VpaTabela.FieldByName('I_COD_PAG').AsInteger = Varia.CondPagtoVista) then
VpfTipoCondicaoPgto := '1' // a vista
else
VpfTipoCondicaoPgto := '2';//a prazo
VpfIndNotaCancelada := (VpaTabela.FieldByName('C_NOT_CAN').AsString = 'S');
if VpfIndNotaCancelada then
begin
VpfValTotal := 0;
VpfValBase := 0;
VpfValAliquota :=0;
VpfValIcms := 0;
VpfValIPI := 0;
VpfDesObservacao := 'NOTA FISCAL CANCELADA';
VpfNatureza := '5.949.99';
end
else
begin
VpfValtotal := VpaTabela.fieldbyname('N_TOT_NOT').AsFloat;
VpfValBase := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
VpfValIcms := VpaTabela.fieldbyname('N_VLR_ICM').AsFloat;
VpfValIpi := VpaTabela.fieldbyname('N_TOT_IPI').AsFloat;
VpfValAliquota := RAliquotaNota(VpaTabela.FieldByName('I_EMP_FIL').AsInteger,VpaTabela.FieldByName('I_SEQ_NOT').AsInteger);
if VpfValAliquota = 0 then
begin
VpfValBase := 0;
VpfValIPI := VpaTabela.FieldByName('N_TOT_PRO').AsFloat;
end;
VpfDesObservacao := DeletaChars(DeletaChars(CopiaEsquerda(VpaTabela.FieldByName('L_OB1_NOT').AsString,57),#13),'"');
VpfNatureza := WkLiscalDosMontaNatureza(VpfNatureza,VpfTipoCondicaoPgto,VpfValAliquota);
end;
VpfAuxStr :=
//01 - TIPO DE OPERACAO (I-INCLUSAO, A-ALTERACAO, E-EXCLUSA) X(1)
'"I","'+
//02 - FORNCEDOR CLIENTE (CNPJ) X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) + '","'+
//03 - CODIGO DA NATUREZA x(12)
VpfNatureza + '","'+
//04 - NUMERO DO DOCUMENTO X(6)
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//05 - ESPECIE DO DOCUMENTO X(3)
'NF' +'","'+
//06 - SERIE DO DOCUMENTO X(3)
VpaTabela.fieldbyname('C_SER_NOT').AsString +'","' +
//07 - DATA DE ENTRADA DO DOCUMENTO X(8)
FormatDateTime('ddmmyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//08 - DATA DE EMISSAO DO DOCUMENTO X(8)
FormatDateTime('ddmmyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//09 - ALIQUOTA DE ICMS 9(6)v99
SubstituiStr(FormatFloat('0.00',VpfValAliquota),',','.') +'","'+
//10 - VALOR CONTABIL 9(14)v99
SubstituiStr(FormatFloat('0.00',VpfValTotal),',','.') +'","'+
//11 - BASE REDUZIDA (S/N)
AdicionaCharD(' ','N', 1) +'","'+
//12 - BASE DE CALCULO DO PRIMEIRO IMPOSTO /ICMS
SubstituiStr(FormatFloat('0.00',VpfValBase),',','.') +'","'+
//13 - VALOR DO IMPOSTO
SubstituiStr(FormatFloat('0.00',VpfValIcms),',','.') +'","'+
//14 - VALOR DE ISENTAS - SEGUNDO ARNO DA ERB VAI O VALOR DO IPI
SubstituiStr(FormatFloat('0.00',VpfValIPI),',','.') +'","'+
//15 - VALOR DE OUTRAS - ZERADO
'0.00' +'","'+
//16 - VALOR BASE CALCULO IMPOSTO INDIRETO - ZERADO
'0.00' +'","'+
//17 - VALOR DO IMPOSTO INDIRETO - ZERADO
'0.00' +'","'+
//18 - BASE DE CALCULO DO SEGUNDO IMPOSTO - IPI
'0.00' +'","'+
//19 - VALOR DO SEGUNDO IMPOSTO - IPI
'0.00'+'","'+
//20 - VALOR DE ISENTAS
SubstituiStr(FormatFloat('0.00',VpfValTotal),',','.') +'","'+
//21 - VALOR DE OUTRAS
'0.00' +'","'+
//22 - OBSERVACOES
DeletaChars(DeletaChars(VpfDesObservacao,#13),#10) +'","'+
//23 - VALOR DO ACRESCIMO FINANCEIRO
'0.00' +'","'+
//24 - CONTA CREDORA DO VALOR CONTABIL
'' +'","'+
//'3168' +'","'+
//25 - CONTA DEVEDORA DO VALOR CONTABIL
// a vista 52
// a prazo 5345
'' +'","'+
//26 - CÓDIGO DO HISTÓRICO DO CRÉDITO VALOR CONTÁBIL
//historico a prazo 763
//historico a vista 778
'' +'","'+
//27 - CÓDIGO DO HISTÓRICO DO DÉBITO VALOR CONTÁBIL
'' +'","'+
//28 - CONTRIBUINTE (S/N)
AdicionaCharD('S',VpfContribuinte, 1) +'","'+
//29 - NUMERO FINAL DO INTERVALO DO DOCUMENTO
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//30 - ESTADO DE ORIGEM (SIGLA)
VpaTabela.FieldByName('C_EST_FIL').AsString+'","'+
//31 - ESTADO DE DESTINO (SIGLA)
VpaTabela.FieldByName('C_EST_CLI').AsString +'","'+
//32 - CODIGO FISCAL DO MUNICIO DE DESTINO
RCodigoFiscalMunicipio(VpaTabela.FieldByName('C_CID_CLI').AsString,VpaTabela.FieldByName('C_EST_CLI').AsString) +'","'+
//33 - IPI EMBUTIDO/ICMS RESPONSABILIDADE
'0.00' +'","'+
//34 - COMPLEMNTO CONTABIL DO DEBITO
'' +'","'+
//35 - COMPLEMNTO CONTABIL DO CRÉDITO
'' +'","'+
//36 - DATA DE VENCIMENTO DO DOCUMENTO
FormatDateTime('DDMMYY',VpaTabela.FieldByName('D_DAT_EMI').AsDatetime) +'","'+
//37 - NUMERO DO DOCUMENTO DE IMPORTACAO
'' +'","'+
//38 - TIPO DE FRETE 1 -CIF, 2 -FOB, 3 -OUTROS
AdicionaCharD(' ',CopiaDireita(VpaTabela.FieldByName('I_TIP_FRE').AsString,1),1) +'","'+
//39 - VALOR DO DESCONTO
'0.00' +'","'+
//40 - VALOR DO FRETE (DESPESAS ACESSORIAS)
SubstituiStr(FormatFloat('0.00',VpaTabela.fieldbyname('N_VLR_FRE').AsFloat),',','.') +'","'+
//41 - VALOR DO SEGURO (DESPESAS ACESSORIAS)
SubstituiStr(FormatFloat('0.00',VpaTabela.fieldbyname('N_VLR_SEG').AsFloat),',','.') +'","'+
//42 - VALOR DE OUTRAS DESPESAS ACESSORIAS
SubstituiStr(FormatFloat('0.00',VpaTabela.fieldbyname('N_OUT_DES').AsFloat),',','.') +'","'+
//43 - LANCAMENTO FUNDAP
AdicionaCharE('N','N',1) +'","'+
//44 - TIPO DO DOCUMENTO
AdicionaCharE('P','P',1) +'","'+
//45 - ICMS ANTECIPADO
'0.00'+'","'+
//46 - NUMERO DO FORMULARIO CONTINUO USADO PARA A EMISSAO DESTA NOTA (SISIF - CE)
'0' +'","'+
//47 - CODIGO QUE IDENTIFICA O TIPO DE ANTEC. TRIBUTARIA
AdicionaCharD(' ',' ',1) +'","'+
//48 - BASE DE CALCULO ICMS ANTECIPADO (SISIF - CE)
'0.00' +'","'+
//49 - TOTAL DO ICMS ANTECIPADO (SISIF - CE)
'0.00' +'","'+
//50 - CNPJ DO LOCAL DE SAIDA DA MERADORIA
AdicionaCharD(' ',VpaTabela.FieldByName('C_CGC_FIL').AsString,18) +'","'+
//51 - TIPO PAGAMENTO 1-AVISTA 2 - A PRAZO 3 - LEASING
AdicionaCharD(' ',VpfTipoCondicaoPgto,1) +'","'+
//52 - CNPJ DO LOCAL DE ENTREGA
'' +'"';
VpfTexto.Add(VpfAuxStr);
if not VpfIndNotaCancelada then
WkLiscalDosAdicionaParcelasNota(VpfTexto,VpaTabela.FieldByName('I_EMP_FIL').AsInteger,VpaTabela.FieldByName('I_SEQ_NOT').AsInteger);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'LFDCD50.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.WkLiscalDosAdicionaParcelasNota(VpaArquivo : TStringList;VpaCodFilial, VpaSeqNota : Integer);
var
VpfAuxStr, VpfDatRecebimento : String;
begin
AdicionaSQLAbreTabela(Aux,'SELECT MOV.I_NRO_PAR, MOV.C_NRO_DUP, MOV.D_DAT_VEN, CAD.I_NRO_NOT, D_DAT_PAG, N_VLR_PAR, N_VLR_PAG '+
' FROM CADCONTASARECEBER CAD, MOVCONTASARECEBER MOV '+
' Where CAD.I_EMP_FIL = MOV.I_EMP_FIL '+
' AND CAD.I_LAN_REC = MOV.I_LAN_REC '+
' AND CAD.I_EMP_FIL = '+ IntTostr(VpaCodFilial)+
' and CAD.I_SEQ_NOT = '+ IntToStr(VpaSeqNota));
While not Aux.Eof do
begin
if Aux.FieldByName('D_DAT_PAG').ASDatetime > MontaData(1,1,1900) then
VpfDatRecebimento := FormatDateTime('DDMMYY',Aux.FieldByName('D_DAT_PAG').AsDateTime)
else
VpfDatRecebimento := '';
VpfAuxStr := '"T","'+
//parcela
Aux.FieldByName('I_NRO_PAR').AsString+ '","'+
//Titulo
Aux.FieldByName('I_NRO_NOT').AsString + '","'+
//DT Vencimento
FormatDateTime('DDMMYY',Aux.FieldByName('D_DAT_VEN').AsDateTime)+ '","'+
//valor
SubstituiStr(FormatFloat('0.00',Aux.FieldByName('N_VLR_PAR').AsFloat),',','.') + '","'+
//DT RECEBIMENTO
VpfDatRecebimento + '","'+
//Valor recebido
SubstituiStr(FormatFloat('0.00',Aux.FieldByName('N_VLR_PAG').AsFloat),',','.') +'"';
VpaArquivo.Add(VpfAuxStr);
Aux.Next;
end;
Aux.Close;
end;
{******************************************************************************}
function TRBFuncoesExportacaoFiscal.WkLiscalDosMontaNatureza(VpaCodNatureza, VpaTipoPagamento : String;VpaPerAliquota : Double) : String;
begin
result := VpaCodNatureza;
insert('.',result,2);
result := result + '.'+ AdicionaCharE('0',WkLiscalRCodigoAliquota(VpaPerAliquota),2);
Result := result +'.'+AdicionaCharE('0',VpaTipoPagamento,2);
end;
{******************************************************************************}
function TRBFuncoesExportacaoFiscal.WkLiscalRCodigoAliquota(VpaPerAliquota :Double) : String;
begin
AdicionaSqlAbreTabela(Aux,'Select CODALIQUOTA FROM ALIQUOTAFISCAL'+
' Where PERALIQUOTA = '+SubstituiStr(FormatFloat('0.##',VpaPerAliquota),',','.'));
result := Aux.FieldByName('CODALIQUOTA').AsString;
Aux.Close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.WKRadarExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfTexto: TStringList;
VpfAuxStr: string;
VpfCodFiscalMunicipio : String;
begin
//Exporta os clientes para o sistema LISCAL versão 447 for DOS da WK sistemas
//Dúvidas referente ao layout foram tiradas com o Arno da ERB no dia 17/08/2005 as 16:30
//Os campos textos tem que vir entre " aspas duplas e os numericos com zero a esquerda, com o separador de campo vírgula
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
if VpfCodFiscalMunicipio = '' then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! O município cadastrado "'+VpaTabela.FieldByName('C_CID_CLI').AsString+ '" não existe para o Fisco');
TextoStatusBar(VpaBarraStatus,'1 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfAuxStr :=
//02 -Codigo reduzido do fornecedor / cliente 9(8).
AdicionaCharE('0',VpaTabela.fieldbyname('I_COD_CLI').AsString, 8) +'"|"'+
//04 - Nome de fantasia X(19).
retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_FAN').AsString) + '"|"'+
//05 - Razao Social X(47).
RetiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString) + '"|"'+
//18 - NUMERO DO CNPJ X(18)
VpaTabela.fieldbyname('CNPJ_CPF').AsString +'"|"'+
//06 - Endereço X(47).
VpaTabela.fieldbyname('C_END_CLI').AsString + '"|"'+
//07 - Bairro X(31).
VpaTabela.fieldbyname('C_BAI_CLI').AsString+ '"|"'+
//08 - Estado X(2).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) + '"|"'+
//09 - Codigo fiscal do municipio X(6)
AdicionaCharD(' ',VpfCodFiscalMunicipio, 6) + '"|"'+
//11 - CEP DO BAIRRO X(9)
VpaTabela.fieldbyname('C_CEP_CLI').AsString + '"|"'+
//12 - Numero DDD 9(4)
AdicionaCharE('0',FunClientes.RDDDCliente(VpaTabela.fieldbyname('C_FO1_CLI').AsString),4) + '"|"'+
//13 - Telefone X(08)
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FO1_CLI').AsString),8) + '"|"'+
//14 - FAX X(08)
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FON_FAX').AsString),8) + '"|"'+
//19 - NUMERO DA INSCRICAO ESTADUAL X(18)
VpaTabela.fieldbyname('C_INS_CLI').AsString +'"|"'+
//19 - INDICADOR DE AGROPECUARIO
VpaTabela.fieldbyname('C_IND_AGR').AsString+'"' ;
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'Pessoas.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SCISupremaExportaPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfTexto: TStringList;
VpfAuxStr, VpfTipoPessoa: string;
VpfCodFiscalMunicipio : String;
begin
//Exporta os clientes para o sistema SUPREMA Versão 3.02 for DOS da Santa Catarina Informática
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'3 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
if VpfCodFiscalMunicipio = '' then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! O município cadastrado "'+VpaTabela.FieldByName('C_CID_CLI').AsString+ '" não existe para o Fisco');
if VpaTabela.FieldByName('C_TIP_PES').AsString = 'J' then
VpfTipoPessoa := '0'
else
VpfTipoPessoa := '1';
VpfAuxStr :='"'+
//01 -Codigo do Cliente
AdicionaCharE('0',VpaTabela.fieldbyname('I_COD_CLI').AsString, 6) +'",'+
//02 - Tipo 0-cnpj / 1-cpf
VpfTipoPessoa+ ',"'+
//03 - NUMERO DO CNPJ/cpf X(14)
DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('CNPJ_CPF').AsString,'-'),'.'),'/') +'","'+
//04 - APELIDO DO CLIENTE X(14).
CopiaDireita(UpperCase(retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_FAN').AsString)),14) + '","'+
//05 - Razao Social X(40).
CopiaDireita(UpperCase(RetiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString)),40) + '","'+
//06 - Endereço X(40).
CopiaDireita(UpperCase(VpaTabela.fieldbyname('C_END_CLI').AsString),40) + '","'+
//07 - COMPLEMENTO X(40).
CopiaDireita(Uppercase(VpaTabela.fieldbyname('C_COM_END').AsString),40) + '","'+
//08 - Bairro X(31).
CopiaDireita(UpperCase(VpaTabela.fieldbyname('C_BAI_CLI').AsString),40) + '","'+
//09 - CEP DO BAIRRO X(9)
VpaTabela.fieldbyname('C_CEP_CLI').AsString+ '","'+
//10 - Codigo fiscal do municipio X(5)
VpfCodFiscalMunicipio + '","'+
//11 - Nome do municipio X(31)
UpperCase(RetiraAcentuacao(CopiaDireita(VpaTabela.fieldbyname('C_CID_CLI').AsString,30))) +'","'+
//12 - Estado X(2).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) + '","'+
//13 - TELEFONE DO CLIENTE X(14)
DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('C_FO1_CLI').AsString,'*'),'('),')') + '","'+
//14 - FAX X(14)
DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('C_FON_FAX').AsString,'*'),'('),')') + '","'+
//15 - NUMERO DA INSCRICAO ESTADUAL X(18)
DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('C_INS_CLI').AsString,'.'),'-'),'/') +'","'+
//16 - APELIDO DA CONTA CONTABIL DO CLIENTE PARA INTEGRAÇÃO COM O SISTEMA SUCESSOR
CopiaDireita(retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_FAN').AsString),14) + '","'+
//17 - NUMERO DA INSCRICAO MUNICIPAL X(15)
'' +'"';
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'CADCLI.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.SCISupremaExportaNotasVpa(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
begin
SintegraGeraArquivo(VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.TextoStatusBar(VpaStatusBar : TStatusBar;VpaTexto : String);
begin
VpaStatusBar.Panels[0].Text := VpaTexto;
VpaStatusBar.refresh;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.MTFiscalExportaPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfTexto: TStringList;
VpfAuxStr: string;
VpfCodFiscalMunicipio : String;
begin
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
if VpfCodFiscalMunicipio = '' then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! O município cadastrado "'+VpaTabela.FieldByName('C_CID_CLI').AsString+ '" não existe para o Fisco');
TextoStatusBar(VpaBarraStatus,'4 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfAuxStr :=
//Razao social.
AdicionaCharD(' ',RetiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString),50) + '|'+
//Tipo Pessoa.
VpaTabela.fieldbyname('C_TIP_PES').AsString + '|'+
//nUMERO DO CNPJ X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) +'|'+
//Endereço X(47).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_END_CLI').AsString, 50) + '|'+
//06 - numero DO Endereço X(47).
AdicionaCharD(' ',VpaTabela.fieldbyname('I_NUM_END').AsString,10) + '|'+
//Bairro X(31).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_BAI_CLI').AsString,40) + '|'+
//Estado X(2).
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) + '|'+
//Codigo fiscal do municipio X(6)
AdicionaCharD(' ',VpfCodFiscalMunicipio, 6) + '|'+
//CEP DO BAIRRO X(9)
AdicionaCharD(' ',VpaTabela.fieldbyname('C_CEP_CLI').AsString, 9) + '|'+
//19 - NUMERO DA INSCRICAO ESTADUAL X(18)
VpaTabela.fieldbyname('C_INS_CLI').AsString;
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'Pessoas.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.MTFiscalExportarNotas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar);
var
VpfTexto: TStringList;
VpfAuxStr, VpfContribuinte, VpfTipoCondicaoPgto,VpfNotaCancelada, VpfTipoFrete, VpfTipoDocumento, VpfModeloDocumento: string;
VpfIndNotaCancelada : Boolean;
VpfValTotal, VpfValBase,VpfValIsenta,VpfValIcms,VpfValAliquota, VpfValIPI : Double;
begin
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'1 Exportado dados da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
if (VpaTabela.FieldByName('N_TOT_PRO').AsFloat = 0) then
begin
VpaTabela.Next;
continue;
end;
if config.EmiteNFe then
begin
VpfTipoDocumento := 'NFE';
VpfModeloDocumento := '55';
end
else
begin
VpfTipoDocumento := 'NFF';
VpfModeloDocumento := '1';
end;
IF VpaTabela.FieldByName('I_TIP_FRE').AsInteger = 1 then
VpfTipoFrete := 'C'
else
VpfTipoFrete := 'F';
IF (VpaTabela.FieldByName('C_INS_CLI').AsString = '')or (UpperCase(VpaTabela.FieldByName('C_INS_CLI').AsString)= 'ISENTO') then
VpfContribuinte := 'N'
else
VpfContribuinte := 'S';
if (VpaTabela.FieldByName('I_COD_PAG').AsInteger = Varia.CondPagtoVista) then
VpfTipoCondicaoPgto := 'V' // a vista
else
VpfTipoCondicaoPgto := 'P';//a prazo
VpfIndNotaCancelada := (VpaTabela.FieldByName('C_NOT_CAN').AsString = 'S');
if VpfIndNotaCancelada then
begin
VpfValTotal := 0;
VpfValBase := 0;
VpfValAliquota :=0;
VpfValIcms := 0;
VpfValIPI := 0;
VpfValIsenta := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
VpfNotaCancelada := 'S';
end
else
begin
VpfValtotal := VpaTabela.fieldbyname('N_TOT_NOT').AsFloat;
// VpfValtotal := VpaTabela.fieldbyname('N_TOT_PRO').AsFloat;
// VpfValtotal := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
VpfValBase := VpfValTotal;
VpfValIcms := VpaTabela.fieldbyname('N_VLR_ICM').AsFloat;
VpfValIsenta := VpfValTotal;
VpfValIpi := VpaTabela.fieldbyname('N_TOT_IPI').AsFloat;
VpfValAliquota := RAliquotaNota(VpaTabela.FieldByName('I_EMP_FIL').AsInteger,VpaTabela.FieldByName('I_SEQ_NOT').AsInteger);
VpfNotaCancelada := 'N';
if VpfValAliquota = 0 then
begin
VpfValBase := 0;
end;
end;
VpfAuxStr :=
//01 - TIPO DE OPERACAO 1 X(1)
'"1","0001","'+
// CNPJ DA FILIAL (CNPJ) X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('C_CGC_FIL').AsString, 18) + '","'+
// FORNCEDOR CLIENTE (CNPJ) X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) + '","'+
// CODIGO DA NATUREZA x(12)
CopiaAteChar(VpaTabela.FieldByName('C_COD_NAT').AsString,'/') + '","'+
//NUMERO INICIO
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//NUMERO FIM
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//MODELO DO DOCUMENTO
VpfModeloDocumento+ '","'+
// ESPECIE DO DOCUMENTO X(3)
VpfTipoDocumento +'","'+
// SERIE DO DOCUMENTO X(3)
VpaTabela.fieldbyname('C_SER_NOT').AsString +'","' +
// CHAVE NFE X(3)
VpaTabela.fieldbyname('C_CHA_NFE').AsString +'","' +
//DATA DE ENTRADA DO DOCUMENTO X(8)
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//DATA DE EMISSAO DO DOCUMENTO X(8)
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//ESTADO DE DESTINO (SIGLA)
VpaTabela.FieldByName('C_EST_CLI').AsString +'","'+
//ESTADO DE ORIGEM (SIGLA)
VpaTabela.FieldByName('C_EST_FIL').AsString+'","'+
//CONTRIBUINTE (S/N)
AdicionaCharD('S',VpfContribuinte, 1) +'","'+
// NOTA CANCELADA
AdicionaCharD('S',VpfNotaCancelada, 1) +'","'+
// TIPO PAGAMENTO V-AVISTA P - PRAZO
AdicionaCharD(' ',VpfTipoCondicaoPgto,1) +'","'+
//TIPO DE FRETE 1 -CIF, 2 -FOB, 3 -OUTROS
AdicionaCharD(' ',VpfTipoFrete,1) +'","'+
//ALIQUOTA DE ICMS 9(6)v99
SubstituiStr(FormatFloat('0.00',VpfValAliquota),',','.') +'","'+
//VALOR CONTABIL 9(14)v99
SubstituiStr(FormatFloat('0.00',VpfValTotal),',','.') +'","'+
// BASE DE CALCULO DO PRIMEIRO IMPOSTO /ICMS
SubstituiStr(FormatFloat('0.00',VpfValBase),',','.') +'","'+
//VALOR DO IMPOSTO
SubstituiStr(FormatFloat('0.00',VpfValIcms),',','.') +'","'+
//VALOR DE ISENTAS
SubstituiStr(FormatFloat('0.00',VpfValIsenta),',','.') +'","'+
// VALOR DE OUTRAS
'0.00' +'","'+
// VALOR IPI EMBUTIDO NA NOTA
'0.00' +'","'+
// BASE CALCULO IPI
'0.00' +'","'+
// VALOR IPI
SubstituiStr(FormatFloat('0.00',VpfValIPI),',','.') +'","'+
// VALOR DE ISENTAS DO IPI
SubstituiStr(FormatFloat('0.00',VpfValTotal),',','.') +'","'+
// VALOR DE OUTROS DO IPI
'0.00' +'","'+
// VALOR DE REDUCAO DO IPI
'0.00"';
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'Produtos.txt');
VpfTexto.Clear;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'1 Exportado dados da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
if not ExistePalavra(VpaTabela.FieldByName('C_COD_NAT').AsString,'5933') then
begin
VpaTabela.Next;
continue;
end;
IF VpaTabela.FieldByName('I_TIP_FRE').AsInteger = 1 then
VpfTipoFrete := 'C'
else
VpfTipoFrete := 'F';
IF (VpaTabela.FieldByName('C_INS_CLI').AsString = '')or (UpperCase(VpaTabela.FieldByName('C_INS_CLI').AsString)= 'ISENTO') then
VpfContribuinte := 'N'
else
VpfContribuinte := 'S';
if (VpaTabela.FieldByName('I_COD_PAG').AsInteger = Varia.CondPagtoVista) then
VpfTipoCondicaoPgto := 'V' // a vista
else
VpfTipoCondicaoPgto := 'P';//a prazo
VpfIndNotaCancelada := (VpaTabela.FieldByName('C_NOT_CAN').AsString = 'S');
if VpfIndNotaCancelada then
begin
VpfValTotal := 0;
VpfValBase := 0;
VpfValAliquota :=0;
VpfValIcms := 0;
VpfValIPI := 0;
VpfNotaCancelada := 'S';
end
else
begin
VpfValtotal := VpaTabela.fieldbyname('N_TOT_SER').AsFloat;
VpfValBase := VpaTabela.fieldbyname('N_TOT_SER').AsFloat;
VpfValIcms := VpaTabela.fieldbyname('N_VLR_ISQ').AsFloat;
VpfValIpi := 0;
VpfValAliquota := VpaTabela.FieldByName('N_PER_ISQ').AsFloat;
VpfNotaCancelada := 'N';
end;
VpfAuxStr :=
//01 - TIPO DE OPERACAO 1 X(1)
'"1","0001","'+
// CNPJ DA FILIAL (CNPJ) X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('C_CGC_FIL').AsString, 18) + '","'+
// FORNCEDOR CLIENTE (CNPJ) X(18)
AdicionaCharD(' ',VpaTabela.fieldbyname('CNPJ_CPF').AsString, 18) + '","'+
// CODIGO DA NATUREZA x(12)
'8000","'+
//NUMERO INICIO
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//NUMERO FIM
VpaTabela.fieldbyname('I_NRO_NOT').AsString + '","'+
//MODELO DO DOCUMENTO
'1","'+
// ESPECIE DO DOCUMENTO X(3)
'NFF' +'","'+
// SERIE DO DOCUMENTO X(3)
VpaTabela.fieldbyname('C_SER_NOT').AsString +'","' +
//DATA DE ENTRADA DO DOCUMENTO X(8)
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//DATA DE EMISSAO DO DOCUMENTO X(8)
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) + '","'+
//ESTADO DE DESTINO (SIGLA)
VpaTabela.FieldByName('C_EST_CLI').AsString +'","'+
//ESTADO DE ORIGEM (SIGLA)
VpaTabela.FieldByName('C_EST_FIL').AsString+'","'+
//CONTRIBUINTE (S/N)
AdicionaCharD('S',VpfContribuinte, 1) +'","'+
// NOTA CANCELADA
AdicionaCharD('S',VpfNotaCancelada, 1) +'","'+
// TIPO PAGAMENTO V-AVISTA P - PRAZO
AdicionaCharD(' ',VpfTipoCondicaoPgto,1) +'","'+
//TIPO DE FRETE 1 -CIF, 2 -FOB, 3 -OUTROS
AdicionaCharD(' ',VpfTipoFrete,1) +'","'+
//ALIQUOTA DE ICMS 9(6)v99
SubstituiStr(FormatFloat('0.00',VpfValAliquota),',','.') +'","'+
//VALOR CONTABIL 9(14)v99
SubstituiStr(FormatFloat('0.00',VpfValTotal),',','.') +'","'+
// BASE DE CALCULO DO PRIMEIRO IMPOSTO /ICMS
SubstituiStr(FormatFloat('0.00',VpfValBase),',','.') +'","'+
//VALOR DO IMPOSTO
SubstituiStr(FormatFloat('0.00',VpfValIcms),',','.') +'","'+
//VALOR DE ISENTAS
'0.00' +'","'+
// VALOR DE OUTRAS
'0.00' +'","'+
// VALOR IPI EMBUTIDO NA NOTA
'0.00' +'","'+
// BASE CALCULO IPI
'0.00' +'","'+
// VALOR IPI
SubstituiStr(FormatFloat('0.00',VpfValIPI),',','.') +'","'+
// VALOR DE ISENTAS DO IPI
'0.00' +'","'+
// VALOR DE OUTROS DO IPI
'0.00' +'","'+
// VALOR DE REDUCAO DO IPI
'0.00"';
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.savetofile(VpaDiretorio + 'Servicos.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro10e11(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaArquivo : TStringList);
var
VpfLinha : String;
begin
AdicionaSQLAbreTabela(Tabela,'Select * from CADFILIAIS '+
' Where I_EMP_FIL = '+IntToStr(VpaCodfilial));
VpfLinha := '10'+
//CGC
DeletaChars(DeletaChars(DeletaChars(Tabela.FieldByName('C_CGC_FIL').AsString,'.'),'/'),'-')+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',DeletaChars(DeletaChars(Tabela.FieldByName('C_INS_FIL').AsString,'.'),'-'),14)+
//NOME DO CONTRIBUINTE
AdicionaCharD(' ',COPY(Tabela.FieldByName('C_NOM_FIL').AsString,1,35),35)+
//MUNICIPIO
AdicionaCharD(' ',COPY(Tabela.FieldByName('C_CID_FIL').AsString,1,30),30)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',Tabela.FieldByName('C_EST_FIL').AsString,2)+
//FAX
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(COPY(Tabela.FieldByName('C_FON_FIL').AsString,5,15),')'),' '),'-'),10)+
//DATA INICIAL
FormatDateTime('YYYYMMDD',VpaDatInicial)+
//DATA FINAL
FormatDateTime('YYYYMMDD',VpaDatFinal)+
//CODIGO DO CONVENIO
'3'+
//CODIGO DA IDENTIFICACAO DAS NATUREZAS INFORMADAS
'3'+
//CODIGO DA FINALIDADE DO ARQUIVO MAGNETICO
'1';
VpaArquivo.Add(VpfLinha);
//registro 11
VpfLinha := '11'+
//Logradouro
AdicionaCharD(' ',copy(Tabela.FieldByName('C_END_FIL').AsString,1,34),34)+
//NUMERO
AdicionaCharE('0',Tabela.FieldByName('I_NUM_FIL').AsString,5)+
//COMPLEMENTO
AdicionaCharD(' ','',22)+
//BAIRRO
AdicionaCharD(' ',Tabela.FieldByName('C_BAI_FIL').AsString,15)+
//CEP
AdicionaCharE('0',Tabela.FieldByName('I_CEP_FIL').AsString,8)+
//NOME DE CONTATO
AdicionaCharD(' ',Tabela.FieldByName('C_DIR_FIL').AsString,28)+
//TELEFONE CONTATO
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(COPY(Tabela.FieldByName('C_FAX_FIL').AsString,5,15),')'),' '),'-'),12);
VpaArquivo.Add(VpfLinha);
Tabela.Close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro50(VpaTabela : TDataSet;VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfInscricaoEstadual : String;
VpfLinha : String;
begin
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
inc(VpaQtdRegistros);
TextoStatusBar(VpaBarraStatus,'4 Validando a inscrição estadual');
VpfInscricaoEstadual := DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('C_INS_CLI').AsString,'.'),'-'),'/');
if (VpfInscricaoEstadual = '') or (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
VpfInscricaoEstadual := 'ISENTO';
if (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
begin
if not VerificaCPF(VpaTabela.FieldByName('CNPJ_CPF').AsString) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! CPF inválida');
end
else
begin
if not VerificarIncricaoEstadual(VpfInscricaoEstadual,VpaTabela.FieldByName('C_EST_CLI').AsString,false,true) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual inválida');
if VpfInscricaoEstadual = VpaInscricaoFilial then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual é a mesma da "'+varia.NomeFilial+'"');
end;
TextoStatusBar(VpaBarraStatus,'4 Inserindo registro 50 da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
//codigo do registro
VpfLinha := '50'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',VpfInscricaoEstadual,14)+
//DATA DE EMISSAO
FormatDateTime('YYYYMMDD',VpaTabela.FieldByName('D_DAT_EMI').AsDateTime)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',VpaTabela.FieldByName('C_EST_CLI').AsString,2)+
//MODELO
'01'+
//SERIE DA NOTA
AdicionaCharD(' ',VpaTabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',VpaTabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(VpaTabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//EMITENTE DA NOTA FISCAL
'P'+
//VALOR TOTAL
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_TOT_NOT').AsFloat),','),13)+
//BASE DE CALCULO DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_BAS_CAL').AsFloat),','),13)+
//VALOR DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_VLR_ICM').AsFloat),','),13)+
// ISENTA OU NÃO TRIBUTADA
AdicionaCharE('0','0',13)+
// OUTRAS
AdicionaCharE('0','0',13)+
//ALIQUOTA
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',RAliquotaNota(VpaTabela.FieldByName('I_EMP_FIL').AsInteger,VpaTabela.FieldByName('I_SEQ_NOT').AsInteger)),','),4)+
//SITUACAO DA NOTA FISCAL
AdicionaCharE('N',VpaTabela.FieldByName('C_NOT_CAN').AsString,1);
VpaArquivo.Add(VpfLinha);
VpaTabela.Next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro51(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfInscricaoEstadual : String;
VpfLinha : String;
begin
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
inc(VpaQtdRegistros);
TextoStatusBar(VpaBarraStatus,'4 Validando a inscrição estadual');
VpfInscricaoEstadual := DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('C_INS_CLI').AsString,'.'),'-'),'/');
if (VpfInscricaoEstadual = '') or (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
VpfInscricaoEstadual := 'ISENTO';
if (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
begin
if not VerificaCPF(VpaTabela.FieldByName('CNPJ_CPF').AsString) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! CPF inválida');
end
else
begin
if not VerificarIncricaoEstadual(VpfInscricaoEstadual,VpaTabela.FieldByName('C_EST_CLI').AsString,false,true) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual inválida');
if VpfInscricaoEstadual = VpaInscricaoFilial then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual é a mesma da "'+varia.NomeFilial+'"');
end;
TextoStatusBar(VpaBarraStatus,'3 Inserindo registro 51 da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
//codigo do registro
VpfLinha := '51'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',VpfInscricaoEstadual,14)+
//DATA DE EMISSAO
FormatDateTime('YYYYMMDD',VpaTabela.FieldByName('D_DAT_EMI').AsDateTime)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',VpaTabela.FieldByName('C_EST_CLI').AsString,2)+
//SERIE DA NOTA
AdicionaCharD(' ',VpaTabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',VpaTabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(VpaTabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//VALOR TOTAL
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_TOT_NOT').AsFloat),','),13)+
//VALOR DO IPI
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_TOT_IPI').AsFloat),','),13)+
// ISENTA OU NÃO TRIBUTADA
AdicionaCharE('0','0',13)+
// OUTRAS
AdicionaCharE('0','0',13)+
//BRANCOS 20
AdicionaCharE(' ','',20)+
//SITUACAO DA NOTA FISCAL
AdicionaCharE('N',VpaTabela.FieldByName('C_NOT_CAN').AsString,1);
VpaArquivo.Add(VpfLinha);
VpaTabela.Next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro53(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfInscricaoEstadual : String;
VpfLinha : String;
begin
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
inc(VpaQtdRegistros);
TextoStatusBar(VpaBarraStatus,'4 Validando a inscrição estadual');
VpfInscricaoEstadual := DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('C_INS_CLI').AsString,'.'),'-'),'/');
if (VpfInscricaoEstadual = '') or (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
VpfInscricaoEstadual := 'ISENTO';
if (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
begin
if not VerificaCPF(VpaTabela.FieldByName('CNPJ_CPF').AsString) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! CPF inválida');
end
else
begin
if not VerificarIncricaoEstadual(VpfInscricaoEstadual,VpaTabela.FieldByName('C_EST_CLI').AsString,false,true) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual inválida');
if VpfInscricaoEstadual = VpaInscricaoFilial then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! Inscrição estadual é a mesma da "'+varia.NomeFilial+'"');
end;
TextoStatusBar(VpaBarraStatus,'3 Inserindo registro 53 da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
//codigo do registro
VpfLinha := '53'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',VpfInscricaoEstadual,14)+
//DATA DE EMISSAO
FormatDateTime('YYYYMMDD',VpaTabela.FieldByName('D_DAT_EMI').AsDateTime)+
//UNIDADE DE FEDERACAO
AdicionaCharD(' ',VpaTabela.FieldByName('C_EST_CLI').AsString,2)+
//MODELO
'01'+
//SERIE DA NOTA
AdicionaCharD(' ',VpaTabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',VpaTabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(VpaTabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//EMITENTE DA NOTA FISCAL
'P'+
//BASE DE CALCULO DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_BAS_CAL').AsFloat),','),13)+
//VALOR DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_VLR_ICM').AsFloat),','),13)+
//DESPESAS ACESSORIAS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_VLR_FRE').AsFloat+VpaTabela.FieldByName('N_VLR_SEG').AsFloat+VpaTabela.FieldByName('N_OUT_DES').AsFloat),','),13)+
//SITUACAO DA NOTA FISCAL
AdicionaCharE('N',VpaTabela.FieldByName('C_NOT_CAN').AsString,1)+
//Codigo da antecipacao
''+
//BRANCOS
AdicionaCharE(' ','',29);
VpaArquivo.Add(VpfLinha);
VpaTabela.Next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro54(VpaTabela : TDataSet; VpaInscricaoFilial : String;Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfLinha : String;
begin
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
if (VpaTabela.FieldByName('C_TIP_PES').AsString = 'F') then
begin
if not VerificaCPF(VpaTabela.FieldByName('CNPJ_CPF').AsString) then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! CPF inválida');
end;
TextoStatusBar(VpaBarraStatus,'3 Inserindo registro 54 da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
AdicionaSQLAbreTabela(Produtos,'Select MOV.C_COD_CST, MOV.I_SEQ_MOV, MOV.C_COD_PRO, MOV.N_QTD_PRO, MOV.N_VLR_PRO, '+
' MOV.N_VLR_IPI, MOV.N_PER_ICM, MOV.N_TOT_PRO ' +
' from MOVNOTASFISCAIS MOV '+
' Where MOV.I_EMP_FIL = '+VpaTabela.FieldByname('I_EMP_FIL').AsString +
' and MOV.I_SEQ_NOT = '+VpaTabela.FieldByname('I_SEQ_NOT').AsString +
' ORDER BY MOV.I_SEQ_MOV ');
While not Produtos.eof do
begin
inc(VpaQtdRegistros);
//codigo do registro
VpfLinha := '54'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(VpaTabela.FieldByName('CNPJ_CPF').AsString,'.'),'/'),'-'),14)+
//MODELO
'01'+
//SERIE DA NOTA
AdicionaCharD(' ',VpaTabela.FieldByName('C_SER_NOT').AsString,3)+
//NUMERO DA NOTA FISCAL
AdicionaCharE('0',VpaTabela.FieldByName('I_NRO_NOT').AsString,6)+
//CFOP
AdicionaCharE('0',COPY(VpaTabela.FieldByName('C_COD_NAT').AsString,1,4),4)+
//CST
AdicionaCharE('0',COPY(Produtos.FieldByName('C_COD_CST').AsString,1,3),3)+
//NUMERO DO ITEM
AdicionaCharE('0',COPY(Produtos.FieldByName('I_SEQ_MOV').AsString,1,3),3)+
//CODIGO DO PRODUTO OU SERVICO
AdicionaCharD(' ',COPY(Produtos.FieldByName('C_COD_PRO').AsString,1,14),14)+
//QTD PRODUTO
AdicionaCharE('0',DeletaChars(FormatFloat('0.000',Produtos.FieldByName('N_QTD_PRO').AsFloat),','),11)+
//VALOR DO PRODUTO
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Produtos.FieldByName('N_VLR_PRO').AsFloat),','),12)+
//VALOR DO DESCONTO / DESPESA ACESSORIA
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),12)+
//BASE DE CALCULO DO ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Produtos.FieldByName('N_TOT_PRO').AsFloat),','),12)+
//BASE DE CALCULO PARA ICMS SUBSTITUICAO TRIBUTARIA
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),12)+
//VALOR DO IPI
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Produtos.FieldByName('N_VLR_IPI').AsFloat),','),12)+
//ALIQUOTA ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',Produtos.FieldByName('N_PER_ICM').AsFloat),','),4);
VpaArquivo.Add(VpfLinha);
Produtos.next;
end;
VpaTabela.Next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro50e51e53e54(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar;Var VpaQtdRegistro50, VpaQtdRegistro51, VpaQtdRegistro53, VpaQtdRegistro54 : Integer);
var
VpfInscricaoEstadualFilial : String;
begin
VpfInscricaoEstadualFilial := RInscricaoEstadualFilial(VpaCodFilial);
TextoStatusBar(VpaBarraStatus,'4 Localizando as notas fiscais');
LocalizaNotasExportacao(Tabela,VpaCodFilial,VpaDatInicial,VpaDatFinal,VpaUF);
ValidaPRAdiconaRegistro50(Tabela,VpfInscricaoEstadualFilial,VpaQtdRegistro50,VpaArquivo,VpaCritica,VpaBarraStatus);
ValidaPRAdiconaRegistro51(Tabela,VpfInscricaoEstadualFilial,VpaQtdRegistro51,VpaArquivo,VpaCritica,VpaBarraStatus);
ValidaPRAdiconaRegistro53(Tabela,VpfInscricaoEstadualFilial,VpaQtdRegistro53,VpaArquivo,VpaCritica,VpaBarraStatus);
ValidaPRAdiconaRegistro54(Tabela,VpfInscricaoEstadualFilial,VpaQtdRegistro54,VpaArquivo,VpaCritica,VpaBarraStatus);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro74(VpaTabela : TDataSet; VpaDatInventario : TDateTime; Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfLinha : String;
begin
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
inc(VpaQtdRegistros);
TextoStatusBar(VpaBarraStatus,'4 Registro 74 Exportando produto '+VpaTabela.FieldByname('C_COD_PRO').AsString);
//codigo do registro
VpfLinha := '74'+
//DATA DO EMISSAO
FormatDateTime('YYYYMMDD',VpaDatInventario)+
//CODIGO DO PRODUTO OU SERVICO
AdicionaCharD(' ',COPY(VpaTabela.FieldByName('C_COD_PRO').AsString,1,14),14)+
//QUANTIDADE PRODUTO
AdicionaCharE('0',DeletaChars(FormatFloat('0.000',VpaTabela.FieldByName('N_QTD_PRO').AsFloat),','),13)+
//VALOR BRUTO DO PRODUTO
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',(VpaTabela.FieldByName('N_QTD_PRO').AsFloat * VpaTabela.FieldByName('N_VLR_CUS').AsFloat)),','),13)+
//CODIGO DA POSSE DA MERCADORIA
'1'+
//CNPJ DO POSSUIDOR DO PRODUTO
'00000000000000'+
//INSCRICAO ESTADUAL DO POSSUIDOR
' '+
//UF DO POSSUIDOR
' '+
AdicionaCharD(' ','',45);
VpaArquivo.Add(VpfLinha);
// VpaArquivo.Add(IntToStr(VpaArquivo.Count+1)+ ' '+ VpfLinha);
VpaTabela.next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro75(VpaTabela : TDataSet; VpaDatInicial, VpaDatFinal : TDateTime; Var VpaQtdRegistros : Integer; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
var
VpfICMSPadrao, VpfValICMSREducao, vpfValICMSINternoUFDestino : Double;
VpfIndSubstituicaoTributaria : boolean;
VpfLinha : String;
begin
FunNotaFiscal.CarValICMSPadrao(VpfICMSPadrao,vpfValICMSINternoUFDestino, VpfValICMSREducao, Varia.UFFilial,'',TRUE,FALSE,VpfIndSubstituicaoTributaria);
VpaQtdRegistros := 0;
VpaTabela.First;
While not VpaTabela.Eof do
begin
inc(VpaQtdRegistros);
TextoStatusBar(VpaBarraStatus,'4 Registro 75 Exportando produto '+VpaTabela.FieldByname('C_COD_PRO').AsString);
//codigo do registro
VpfLinha := '75'+
//DATA INICIAL
FormatDateTime('YYYYMMDD',VpaDatInicial)+
//DATA FINAL
FormatDateTime('YYYYMMDD',VpaDatFinal)+
//CODIGO DO PRODUTO OU SERVICO
AdicionaCharD(' ',COPY(VpaTabela.FieldByName('C_COD_PRO').AsString,1,14),14)+
//CODIGO NCM
AdicionaCharD(' ','AB',8)+
//NOME DO PRODUTO
AdicionaCharD(' ',VpaTabela.FieldByName('C_NOM_PRO').AsString,53)+
//UM DO PRODUTO
AdicionaCharD(' ',VpaTabela.FieldByName('C_COD_UNI').AsString,6)+
//ALIQUOTA DE IPI
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_PER_IPI').AsFloat),','),5)+
//ALIQUOTA DE ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpfICMSPadrao ),','),4)+
//REDUCAO DE ICMS
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByName('N_RED_ICM').AsFloat),','),5)+
//BASE DE CALCULO DO ICMS SUBSTITUICAO
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13);
VpaArquivo.add(VpfLinha);
VpaTabela.next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro74e75(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar;Var VpaQtdRegistro74, VpaQtdRegistro75 : Integer);
var
VpfQtdRegistros : Integer;
begin
TextoStatusBar(VpaBarraStatus,'4 Localizando as notas fiscais');
LocalizaProdutosExportacao(Tabela,VpaCodFilial,VpaDatInicial,VpaDatFinal,VpaUF);
ValidaPRAdicionaRegistro74(Tabela,VpaDatInicial,VpaQtdRegistro74,VpaArquivo,VpaCritica,VpaBarraStatus);
ValidaPRAdicionaRegistro75(Tabela,VpaDatInicial,VpaDatFinal, VpaQtdRegistro75,VpaArquivo,VpaCritica,VpaBarraStatus);
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdiconaRegistro60Me60Ae60R(VpaCodFilial : Integer;VpaDatInicial,VpaDatFinal : TDateTime; VpaUF : String; VpaArquivo, VpaCritica : TStringList;VpaBarraStatus : TStatusBar);
begin
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro90porTipo(VpaQtdRegistro,VpaTipoRegistro : Integer;VpaCNPJ,VpaInscricaoEstadual : String; VpaArquivo : TStringList);
begin
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRAdicionaRegistro90(VpaCNPJ, VpaInscricaoEstadual : String;VpaQtdRegistro50, VpaQtdRegistro51,VpaQtdRegistro53,VpaQtdRegistro54,VpaQtdRegistro74,VpaQtdRegistro75 : Integer;VpaArquivo: TStringList);
begin
VpaArquivo.add('90'+
//cnpj destinatario
AdicionaCharE('0',DeletaChars(DeletaChars(DeletaChars(VpaCNPJ,'.'),'/'),'-'),14)+
//INSCRICAO ESTADUAL
AdicionaCharD(' ',DeletaChars(DeletaChars(DeletaChars(VpaInscricaoEstadual,'.'),'/'),'-'),14)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','50',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro50),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','51',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro51),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','53',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro53),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','54',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro54),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','60',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','3',8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','74',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro74),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','75',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaQtdRegistro75),8)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0','99',2)+
//TIPO A SER TOTALIZADO
AdicionaCharE('0',IntToStr(VpaArquivo.Count+1),8)+
//QUANTIDDE DE REGISTRO 90
AdicionaCharE(' ','',15)+
'1');
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaPRExportaNotas(VpaTabela : TDataSet;VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfArquivo : TStringList;
VpfDFilial : TRBDFilial;
VpfQtdRegistro50, VpfQtdRegistro51,VpfQtdRegistro53,VpfQtdRegistro54,VpfQtdRegistro74,VpfQtdRegistro75 : Integer;
begin
VpfArquivo := TStringList.create;
VpfDFilial := TRBDFilial.cria;
Sistema.CarDFilial(VpfDFilial,VpaCodFilial);
TextoStatusBar(VpaBarraStatus,'7 Adicionando registro 10');
ValidaPRAdicionaRegistro10e11(VpaCodFilial,VpaDatInicio,VpaDatFim, VpfArquivo);
ValidaPRAdiconaRegistro50e51e53e54(VpaCodFilial,VpaDatInicio,VpaDatFim,'',VpfArquivo,VpaCritica,VpaBarraStatus,VpfQtdRegistro50,VpfQtdRegistro51,VpfQtdRegistro53,VpfQtdRegistro54);
ValidaPRAdicionaRegistro74e75(VpaCodFilial,VpaDatInicio,VpaDatFim,'',VpfArquivo,VpaCritica,VpaBarraStatus,VpfQtdRegistro74,VpfQtdRegistro75);
ValidaPRAdicionaRegistro90(VpfDFilial.DesCNPJ,VpfDFilial.DesInscricaoEstadual,VpfQtdRegistro50,VpfQtdRegistro51,VpfQtdRegistro53,VpfQtdRegistro54,VpfQtdRegistro74,VpfQtdRegistro75,VpfArquivo);
VpfArquivo.SaveToFile(VpaDiretorio+InttoStr(Ano(VpaDatInicio))+AdicionaCharE('0',InttoStr(Mes(VpaDatFim)),2)+'.txt');
VpfDFilial.free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.DominioExportarPessoas(VpaTabela : TDataSet;VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfTexto: TStringList;
VpfAuxStr: string;
VpfCodFiscalMunicipio,VpfTipInscricao : String;
begin
VpfTexto := TStringList.Create;
VpaTabela.First;
while not VpaTabela.Eof do
begin
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
if VpfCodFiscalMunicipio = '' then
VpaCritica.Add('Cadastro do Cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'" incorreto!!! O município cadastrado "'+VpaTabela.FieldByName('C_CID_CLI').AsString+ '" não existe para o Fisco');
if VpaTabela.FieldByname('C_TIP_PES').AsString = 'F' then
VpfTipInscricao := '2'
else
VpfTipInscricao := '1';
TextoStatusBar(VpaBarraStatus,'1 Exportando o cliente "'+VpaTabela.FieldByName('I_COD_CLI').AsString+'"');
VpfAuxStr :=
//fixo 22- clientes
'22'+
//Codigo reduzido do fornecedor / cliente numerico7.
AdicionaCharE('0',IntToStr(varia.CodClienteExportacaoFiscal), 7)+
//Sigla estado
AdicionaCharD(' ',VpaTabela.fieldbyname('C_EST_CLI').AsString, 2) +
//Codigo da conta
AdicionaCharE('0',IntToStr(varia.ContaContabilCliente), 7)+
//Codigo fiscal do municipio 9(7)
AdicionaCharE('0',VpfCodFiscalMunicipio, 7) +
//Nome reduzido
AdicionacharD(' ',copy(retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_FAN').AsString),1,10),10) +
//nome do cliente
AdicionacharD(' ',copy(retiraAcentuacao(VpaTabela.fieldbyname('C_NOM_CLI').AsString),1,40),40) +
//endereco
AdicionacharD(' ',copy(VpaTabela.fieldbyname('C_END_CLI').AsString,1,40),40) +
//numero endereco
AdicionacharE('0',VpaTabela.fieldbyname('I_NUM_END').AsString,7) +
//brancos
AdicionacharD(' ','',30) +
//cep
VpaTabela.fieldbyname('C_CEP_CLI').AsString +
//cnpj
AdicionacharD(' ',DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('CNPJ_CPF').AsString,'.'),'-'),'/'),14) +
//NUMERO DA INSCRICAO ESTADUAL
AdicionacharD(' ',VpaTabela.fieldbyname('C_INS_CLI').AsString,20)+
//Telefone
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FO1_CLI').AsString),14) +
//FAX
AdicionaCharD(' ',FunClientes.RTelefoneSemDDD(VpaTabela.fieldbyname('C_FON_FAX').AsString),14) +
//INDICADOR DE AGROPECUARIO
VpaTabela.fieldbyname('C_IND_AGR').AsString+
//ICMS
'S'+
//tipo inscricao
VpfTipInscricao +
//inscricao municipal+
AdicionacharD(' ','',20) +
//bairro
AdicionacharD(' ',copy(retiraAcentuacao(VpaTabela.fieldbyname('C_BAI_CLI').AsString),1,20),20) +
//Numero DDD
AdicionaCharE('0',copy(FunClientes.RDDDCliente(VpaTabela.fieldbyname('C_FO1_CLI').AsString),1,4),4) +
//Aliquota icms
AdicionaCharE('0','0',5) +
//codigo do pais
AdicionaCharE('0','0',7) +
//suframa
AdicionaCharD(' ','',9) +
//suframa
AdicionaCharD(' ','',100);
VpfTexto.Add(VpfAuxStr);
VpaTabela.Next;
end;
VpfTexto.SaveToFile(VpaDiretorio + 'Pessoas.txt');
VpfTexto.Free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.DominioExportaNotas(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaDiretorio : String;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
var
VpfArquivo : TStringList;
begin
VpfArquivo := TStringList.create;
DominioCabecalhoNotas(VpaDatInicio,VpaDatFim,VpfArquivo);
DominioExportaNotasRegistro2(VpaTabela,VpaCodFilial,VpaDatInicio,VpaDatFim,VpaBarraStatus,VpaCritica,VpfArquivo);
VpfArquivo.SaveToFile(VpaDiretorio+InttoStr(Ano(VpaDatInicio))+AdicionaCharE('0',InttoStr(Mes(VpaDatFim)),2)+'.txt');
VpfArquivo.free;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.DominioCabecalhoNotas(VpaDatInicio, VpaDatFim : TDatetime;VpaArquivo : TStringList);
begin
VpaArquivo.add('01'+
AdicionaCharE('0',IntToStr(Varia.CodClienteExportacaoFiscal),7)+
AdicionacharD(' ',DeletaChars(DeletaChars(DeletaChars(Varia.CNPJFilial,'.'),'-'),'/'),14) +
FormatDateTime('DD/MM/YYYY',VpaDatInicio)+
FormatDateTime('DD/MM/YYYY',VpaDatFim)+
'N'+
'03'+
'00000'+
'1'+
'14');
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.DominioExportaNotasRegistro2(VpaTabela : TDataSet; VpaCodFilial : Integer;VpaDatInicio, VpaDatFim : TDatetime; VpaBarraStatus : TStatusBar;VpaCritica :TStringList;VpaArquivo : TStringList);
var
VpfTexto: TStringList;
VpfAuxStr, VpfCodFiscalMunicipio,VpfTipoFrete: string;
VpfIndNotaCancelada : Boolean;
VpfValTotal : Double;
VpfSequencial : Integer;
begin
VpfSequencial := 0;
VpaTabela.First;
while not VpaTabela.Eof do
begin
TextoStatusBar(VpaBarraStatus,'1 Exportado dados da nota fiscal "'+VpaTabela.FieldByName('I_NRO_NOT').AsString+'"');
inc(VpfSequencial);
IF VpaTabela.FieldByName('I_TIP_FRE').AsInteger = 1 then
VpfTipoFrete := 'C'
else
VpfTipoFrete := 'F';
VpfCodFiscalMunicipio := RCodigoFiscalMunicipio(RetiraAcentuacao(VpaTabela.FieldByName('C_CID_CLI').AsString),VpaTabela.FieldByName('C_EST_CLI').AsString);
VpfIndNotaCancelada := (VpaTabela.FieldByName('C_NOT_CAN').AsString = 'S');
if VpfIndNotaCancelada then
begin
VpfValTotal := 0;
end
else
begin
VpfValtotal := VpaTabela.fieldbyname('N_BAS_CAL').AsFloat;
end;
VpfAuxStr :=
//fixo 02
'02'+
//Sequencial
AdicionaCharE('0',IntToStr(VpfSequencial),7)+
// codigo da empresa
AdicionaCharE('0',IntToStr(Varia.CodClienteExportacaoFiscal),7)+
// Inscricao do cliente
AdicionaCharD(' ',DeletaChars(DeletaChars(DeletaChars(VpaTabela.fieldbyname('CNPJ_CPF').AsString,'.'),'-'),'/'),14) +
//codigo da especie
'0000000'+
//codigo da exclusao da Dief
'00'+
//codigo do acumulador
'0000000'+
//codigo da natureza
AdicionaCharE('0',CopiaAteChar(VpaTabela.FieldByName('C_COD_NAT').AsString,'/'),7)+
//ESTADO DE DESTINO (SIGLA)
AdicionaCharE(' ',VpaTabela.FieldByName('C_EST_CLI').AsString,2) +
//seguinte
'00'+
//numero nota
AdicionaCharE('0',VpaTabela.fieldbyname('I_NRO_NOT').AsString,7) +
// serie
AdicionaCharD(' ',VpaTabela.fieldbyname('C_SER_NOT').AsString,7) +
//documento final
AdicionaCharE('0',VpaTabela.fieldbyname('I_NRO_NOT').AsString,7) +
//data de saisa
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) +
//data de emissao
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) +
//valor contabil
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpfValTotal),','),13)+
//valor da exclusa da DIEF
AdicionaCharE('0','0',13)+
//obervacoes
AdicionaCharD(' ',DeletaChars(copy(VpaTabela.FieldByname('L_OB1_NOT').AsString,1,30),#13),30)+
//TIPO DE FRETE 1 -CIF, 2 -FOB, 3 -OUTROS
AdicionaCharD(' ',VpfTipoFrete,1) +
//Codigo fiscal do municipio 9(7)
AdicionaCharE('0',VpfCodFiscalMunicipio, 7) +
//fato gerador
'E'+
//fato gerador DA CRFOP
'E'+
//fato gerador DA IRRFP
'E'+
// tipo de receita 1-proprio 2-terceiros
'1'+
//branco
' '+
//cfop extendido/ detalhado
'0000000'+
//codigo da transferencia
'0000000'+
//codigo da observacao
'0000000'+
//data do visto
FormatDateTime('dd/mm/yyyy', VpaTabela.fieldbyname('D_DAT_EMI').AsDateTime) +
//codigo que identifica tipo da antecipacao tributaria
'000000'+
//valor do frete
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByname('N_VLR_FRE').AsFloat),','),13)+
//valor do seguro
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByname('N_VLR_SEG').AsFloat),','),13)+
//valor das despesas acessorias
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByname('N_OUT_DES').AsFloat),','),13)+
//valor dos produtos
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',VpaTabela.FieldByname('N_TOT_PRO').AsFloat),','),13)+
// Valor B.C ICMS ST
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13)+
// Outras saidas
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13)+
// Saidas insentas
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13)+
// Saidas insentas Cupom Fiscal
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13)+
// Saidas insentas Nota Fiscal modelo 2
AdicionaCharE('0',DeletaChars(FormatFloat('0.00',0),','),13)+
// codigo do modelo do documento
'0000001'+
//codigo fiscal da prestacao de servico
'0000000'+
//codigo da situação tributaria
'0000000'+
//subseries
'0000000'+
//tipo de titulo
'00'+ //00-Duplicata
//identificacao do titulo
AdicionaCharD(' ',VpaTabela.fieldbyname('I_NRO_NOT').AsString,50) +
//inscricao estadual do cliente
AdicionaCharD(' ',VpaTabela.FieldByName('C_INS_CLI').AsString,20) +
//inscricao municipal do cliente
AdicionaCharD(' ','',20) +
//brancos
AdicionaCharD(' ','',60);
VpaArquivo.Add(VpfAuxStr);
VpaTabela.Next;
end;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ValidaVariaveisExportacaoFiscal(VpaCritica : TStringList);
begin
if (varia.ContaContabilFornecedor = 0 ) then
VpaCritica.Add('CONFIGURAÇÕES DA EXPORTAÇÃO!!!Falta preencher a conta contabil do fornecedor');
if (varia.ContaContabilCliente = 0) then
VpaCritica.Add('CONFIGURAÇÕES DA EXPORTAÇÃO!!!Falta preencher a conta contabil do cliente');
end;
{******************************************************************************}
function TRBFuncoesExportacaoFiscal.RAliquotaNota(VpaCodfilial, VpaSeqNota : Integer) : Double;
begin
AdicionaSQlAbreTabela(Aux,'Select N_PER_ICM from MOVNOTASFISCAIS '+
' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+
' and I_SEQ_NOT = '+ IntToStr(VpaSeqNota));
result := Aux.FieldByName('N_PER_ICM').AsFloat;
end;
{*****************************************************************************}
function TRBFuncoesExportacaoFiscal.RCodigoFiscalMunicipio(VpaDesCidade, VpaDesUF : string) : String;
begin
result := '';
AdicionaSqlAbreTabela(Aux,'Select COD_FISCAL from CAD_CIDADES ' +
' Where DES_CIDADE = '''+VpaDesCidade+''''+
' and COD_ESTADO = '''+VpaDesUF+'''' );
if not Aux.Eof then
result := Aux.FieldByName('COD_FISCAL').AsString;
end;
{******************************************************************************}
function TRBFuncoesExportacaoFiscal.RInscricaoEstadualFilial(VpaCodFilial : Integer) :String;
begin
AdicionaSQLAbreTabela(Aux,'Select * from CADFILIAIS '+
' Where I_EMP_FIL = '+IntToStr(VpaCodfilial));
result := Aux.FieldByName('C_INS_FIL').AsString;
result := DeletaChars(DeletaChars(DeletaChars(Result,'.'),'/'),'-');
if result = 'ISENTO' then
result := '-1';
Aux.Close;
end;
{******************************************************************************}
procedure TRBFuncoesExportacaoFiscal.ExportarNotasPessoas(VpaCodFilial : Integer;VpaDataInicial, VpaDataFinal: TDateTime; VpaDiretorio: string;VpaBarraStatus : TStatusBar;VpaCritica :TStringList);
begin
VpaCritica.clear;
ValidaVariaveisExportacaoFiscal(VpaCritica);
TextoStatusBar(VpaBarraStatus,'Limpando diretório "'+VpaDiretorio+'"');
DeletaArquivo(VpaDiretorio+'\*.*');
if varia.FormatoExportacaoFiscal = feSintegra then
begin
SintegraGeraArquivo(VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica);
end
else
begin
TextoStatusBar(VpaBarraStatus,'Localizando os clientes');
LocalizaPessoasExportacao(Tabela, VpaCodFilial, VpaDataInicial, VpaDataFinal);
if varia.FormatoExportacaoFiscal = feLince then
LINCEExportarPessoas(Tabela, VpaDiretorio,VpaBarraStatus)
else
if varia.FormatoExportacaoFiscal = feWKLiscalForDos then
WKLiscalDosExportarPessoas(Tabela,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feSantaCatarina then
SCISupremaExportaPessoas(Tabela,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feMTFiscal then
MTFiscalExportaPessoas(Tabela,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feWKRadar then
WKRadarExportarPessoas(Tabela,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feDominioSistemas then
DominioExportarPessoas(Tabela,VpaDiretorio,VpaBarraStatus,VpaCritica);
TextoStatusBar(VpaBarraStatus,'Localizando as notas fiscais');
LocalizaNotasExportacao(Tabela,VpaCodFilial, VpaDataInicial, VpaDataFinal,'');
if Varia.FormatoexportacaoFiscal = feLince then
LINCEExportarNotas(Tabela, VpaDiretorio,VpaBarraStatus)
else
if varia.FormatoExportacaoFiscal = feWKLiscalForDos then
WKLiscalDosExportarNotas(Tabela,VpaDiretorio,VpaBarraStatus)
else
if varia.FormatoExportacaoFiscal = feSantaCatarina then
SCISupremaExportaNotasVpa(VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feMTFiscal then
MTFiscalExportarNotas(Tabela,VpaDiretorio,VpaBarraStatus)
else
if varia.FormatoExportacaoFiscal = feWKRadar then
MTFiscalExportarNotas(Tabela,VpaDiretorio,VpaBarraStatus)
else
if varia.FormatoExportacaoFiscal = feValidaPR then
ValidaPRExportaNotas(Tabela,VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica)
else
if varia.FormatoExportacaoFiscal = feDominioSistemas then
DominioExportaNotas(Tabela,VpaCodFilial,VpaDataInicial,VpaDataFinal,VpaDiretorio,VpaBarraStatus,VpaCritica);
FechaTabela(Tabela);
end;
TextoStatusBar(VpaBarraStatus,'Notas fiscais exportadas com sucesso!!!');
end;
end.
|
unit ncaFrmFundo;
{
ResourceString: Dario 11/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, ActnList, Buttons, LMDControl, dxBar,
cxClasses;
type
TFrmFundo = class(TForm)
Imagem: TImage;
ActionList1: TActionList;
OpenDlg: TOpenDialog;
barMgr: TdxBarManager;
barTopo: TdxBar;
btnSelImagem: TdxBarLargeButton;
btnEnviar: TdxBarLargeButton;
btnSemFundo: TdxBarLargeButton;
cmFechar: TdxBarLargeButton;
procedure btnSemFundoClick(Sender: TObject);
procedure btnEnviarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSelImagemClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmFecharClick(Sender: TObject);
private
FDesktop: Boolean;
FUArq: String;
{ Private declarations }
public
procedure Mostrar(aDesktop: Boolean);
{ Public declarations }
end;
var
FrmFundo: TFrmFundo;
implementation
uses
ncaDM,
ncaFrmPri, ufmImagens;
// START resource string wizard section
resourcestring
SDesejaRealmenteApagarAImagemDeFu = 'Deseja realmente apagar a imagem de fundo das máquinas clientes?';
SVocêNãoEnviouAImagemParaAsMáquin = 'Você não enviou a imagem para as máquinas clientes. Deseja enviar agora?';
SArquivosJPEGJpg = 'Arquivos JPEG|*.jpg';
SArquivosJPEGJpgArquivosGIFGif = 'Arquivos JPEG|*.jpg|Arquivos GIF|*.gif';
// END resource string wizard section
{$R *.dfm}
procedure TFrmFundo.btnEnviarClick(Sender: TObject);
begin
Dados.CM.EnviaArqFundo(FUArq, FDesktop);
btnSemFundo.Enabled := True;
btnEnviar.Enabled := False;
end;
procedure TFrmFundo.btnSelImagemClick(Sender: TObject);
begin
if OpenDlg.Execute then begin
Imagem.Picture.LoadFromFile(OpenDlg.FileName);
FUArq := OpenDlg.FileName;
btnEnviar.Enabled := True;
btnSemFundo.Enabled := True;
end;
end;
procedure TFrmFundo.btnSemFundoClick(Sender: TObject);
begin
if SimNaoH(SDesejaRealmenteApagarAImagemDeFu, Handle) then begin
Dados.CM.LimpaFundo(FDesktop);
Imagem.Picture.Bitmap.FreeImage;
btnSemFundo.Enabled := False;
btnEnviar.Enabled := False;
end;
end;
procedure TFrmFundo.cmFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFrmFundo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
try
if btnEnviar.Enabled and SimNaoH(SVocêNãoEnviouAImagemParaAsMáquin, Handle) then
btnEnviarClick(nil);
Action := caFree;
except
Action := caNone;
end;
end;
procedure TFrmFundo.FormCreate(Sender: TObject);
begin
FUArq := '';
end;
procedure TFrmFundo.Mostrar(aDesktop: Boolean);
begin
FDesktop := aDesktop;
with Dados do
if aDesktop then begin
OpenDlg.Filter := SArquivosJPEGJpg;
if CM.NomeArqDesktop>'' then begin
if FileExists(CM.NomeArqDesktop) then begin
Imagem.Picture.LoadFromFile(CM.NomeArqDesktop);
btnSemFundo.Enabled := True;
end;
end;
end else begin
OpenDlg.Filter := SArquivosJPEGJpgArquivosGIFGif;
if CM.NomeArqLogin>'' then begin
if FileExists(CM.NomeArqLogin) then begin
Imagem.Picture.LoadFromFile(CM.NomeArqLogin);
btnSemFundo.Enabled := True;
end;
end;
end;
ShowModal;
end;
end.
|
unit Adler;
(************************************************************************
adler32.c -- compute the Adler-32 checksum of a data stream
Copyright (C) 1995-1998 Mark Adler
Pascal translation
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Feb 2002
- replaced inner while loop with for
- Source code reformating/reordering
Mar 2005
- Code cleanup for WWW upload
------------------------------------------------------------------------
*************************************************************************)
interface
uses
zlibh;
function adler32(adler: uLong; buf: pBytef; len: uInt): uLong;
{-Update a running Adler-32 checksum with the bytes buf[0..len-1] and
return the updated checksum. If buf is nil, this function returns
the required initial value for the checksum.
An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
much faster. Usage example:
var
adler: uLong;
begin
adler := adler32(0, Z_NULL, 0);
while read_buffer(buf, len)<>EOF do adler := adler32(adler, buf, len);
if adler<>original_adler then error();
end;}
implementation
const
BASE = uLong(65521); {largest prime smaller than 65536}
NMAX = 3854; {value for signed 32 bit integer}
{NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^31-1}
{NMAX = 5552; original value for unsigned 32 bit integer}
{The penalty is the time loss in the extra mod-calls.}
{---------------------------------------------------------------------------}
function adler32(adler: uLong; buf: pBytef; len: uInt): uLong;
{-Update a running Adler-32 checksum with the bytes buf[0..len-1]}
var
s1, s2: uLong;
i,k: int;
begin
s1 := adler and $ffff;
s2 := (adler shr 16) and $ffff;
if not Assigned(buf) then begin
adler32 := uLong(1);
exit;
end;
while len>0 do begin
if len<NMAX then k := len else k := NMAX;
dec(len, k);
for i:=1 to k do begin
inc(s1, buf^);
inc(s2, s1);
inc(buf);
end;
s1 := s1 mod BASE;
s2 := s2 mod BASE;
end;
adler32 := (s2 shl 16) or s1;
end;
end.
|
unit LLVM.Imports.IPO;
interface
//based on IPO.h
uses
LLVM.Imports,
LLVM.Imports.Types;
type
TcallbackPass = function (par: TLLVMValueRef): TLLVMBool; cdecl;
{* See llvm::createArgumentPromotionPass function. }
procedure LLVMAddArgumentPromotionPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createConstantMergePass function. }
procedure LLVMAddConstantMergePass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{ See llvm::createCalledValuePropagationPass function. }
procedure LLVMAddCalledValuePropagationPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createDeadArgEliminationPass function. }
procedure LLVMAddDeadArgEliminationPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createFunctionAttrsPass function. }
procedure LLVMAddFunctionAttrsPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createFunctionInliningPass function. }
procedure LLVMAddFunctionInliningPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createAlwaysInlinerPass function. }
procedure LLVMAddAlwaysInlinerPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createGlobalDCEPass function. }
procedure LLVMAddGlobalDCEPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createGlobalOptimizerPass function. }
procedure LLVMAddGlobalOptimizerPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createIPConstantPropagationPass function. }
procedure LLVMAddIPConstantPropagationPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createPruneEHPass function. }
procedure LLVMAddPruneEHPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createIPSCCPPass function. }
procedure LLVMAddIPSCCPPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createInternalizePass function. }
procedure LLVMAddInternalizePass(PM: TLLVMPassManagerRef; AllButMain: Cardinal); cdecl; external CLLVMLibrary;
(**
* Create and add the internalize pass to the given pass manager with the
* provided preservation callback.
*
* The context parameter is forwarded to the callback on each invocation.
* As such, it is the responsibility of the caller to extend its lifetime
* until execution of this pass has finished.
*
* @see llvm::createInternalizePass function.
*)
procedure LLVMAddInternalizePassWithMustPreservePredicate(PM : TLLVMPassManagerRef;
Context : TLLVMContextRef;
MustPreserve: TcallbackPass = nil); cdecl; external CLLVMLibrary;
{* See llvm::createStripDeadPrototypesPass function. }
procedure LLVMAddStripDeadPrototypesPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
{* See llvm::createStripSymbolsPass function. }
procedure LLVMAddStripSymbolsPass(PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
implementation
end.
|
//******************************************************************************
//*** LUA SCRIPT FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2006 ***
//*** ***
//*** ***
//******************************************************************************
// File : Script_Classes.pas (rev. 1.0)
//
// Description : Access from scripts to Class declared in "Classes.pas"
//
//******************************************************************************
unit Script_Classes;
interface
uses TypInfo, Script_System;
type
TScriptComponent = class(TScriptObject)
protected
class function GetPublicPropertyAccessClass :TClass; override;
public
//TClass TComponent TComponent
function ScriptCreate(ObjClass :Integer; AOwner :Integer) :Integer; overload;
function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override;
function GetArrayProp(Name :String; index :Variant) :Variant; override;
function GetElementType(Name :String) :PTypeInfo; override;
function GetElement(Name :String) :Variant; override;
end;
implementation
uses Classes, SysUtils, StdCtrls, Variants;
type
TComponentAccess = class(TComponent)
published
property ComponentIndex;
property ComponentCount;
end;
function TScriptComponent.ScriptCreate(ObjClass :Integer; AOwner :Integer) :Integer;
Var
xObjClass :TClass;
begin
xObjClass :=TClass(ObjClass);
if (xObjClass.InheritsFrom(TComponent))
then Result :=Integer(TComponentClass(xObjClass).Create(TComponent(AOwner)))
else Result :=Integer(TComponent(ScriptCreate(ObjClass)));
end;
function TScriptComponent.GetArrayPropType(Name :String; index :Variant) :PTypeInfo;
begin
Name :=Uppercase(Name);
Result :=nil;
if (Name='COMPONENTS')
then begin
if (TComponent(InstanceObj).Components[index]<>nil)
then Result :=TypeInfo(TComponent)
else Result :=nil;
end;
end;
function TScriptComponent.GetArrayProp(Name :String; index :Variant) :Variant;
begin
Name :=Uppercase(Name);
Result :=NULL;
if (Name='COMPONENTS')
then begin
if (TComponent(InstanceObj).Components[index]<>nil)
then Result :=Integer(TComponent(InstanceObj).Components[index]);
end;
end;
function TScriptComponent.GetElementType(Name :String) :PTypeInfo;
Var
upName :String;
begin
upName :=Uppercase(Name);
Result :=nil;
if (upName='COMPONENTS')
then Result :=@TypeInfoArray
else
if (TComponent(InstanceObj).FindComponent(Name)<>nil)
then Result :=TypeInfo(TComponent);
end;
function TScriptComponent.GetElement(Name :String) :Variant;
Var
theComponent :TComponent;
begin
Result :=NULL;
theComponent :=TComponent(InstanceObj).FindComponent(Name);
if (theComponent<>nil)
then Result :=Integer(theComponent);
end;
class function TScriptComponent.GetPublicPropertyAccessClass :TClass;
begin
Result :=TComponentAccess;
end;
initialization
Script_System.RegisterClass(TComponent, TScriptComponent);
end.
|
unit ClsUbicaciones;
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls,VCIF1Lib_TLB, StdCtrls,
IB_Components, IB_StoredProc, StrMan, ESBDates,IniFiles;
type
TUbicacion = class(TObject) {Business Services}
constructor Create;
destructor Destroy;
private
// Tabla: Ubicaciones
FUBICACION_ID: Integer;
FRACK: String;
FSECCION: String;
FNIVEL: String;
FTIEMPO_MIN: Integer;
FDIFICULTAD: SmallInt;
FUSERINS: String;
FFHINS: TDateTime;
// Tabla: Ubicacion_Prod
FUBIPROD_ID: Integer;
FNUMALMACEN: String;
FUBICACION: String;
FCODPRODSER: String;
FDESCRIPPRO: String;
FCODFAMILIA: String;
FCANTIDAD: Double;
FTIPO_ALMACENAJE: SmallInt;
FNUMERO_TARIMA: Integer;
FCOMENTARIOS: String;
FACTIVO:SmallInt;
FUSERACT: String;
FFHACT: TDateTime;
FError:Integer;
FErrorMSg:TStringList;
icuS00,icu,icu1:TIB_Cursor;
icuS01:TIB_Cursor;
icuS02:TIB_Cursor;
icuS03:TIB_Cursor;
icuS10:TIB_Cursor;
isqlI00:TIB_DSQL;
isqlU00,isqlU01,isqlU02:TIB_DSQL;
isqlD00:TIB_DSQL;
tS00,tsql1,tS02:String;
public
// Tabla: Ubicaciones
property UBICACION_ID: Integer read FUBICACION_ID write FUBICACION_ID;
property NUMALMACEN: String read FNUMALMACEN write FNUMALMACEN;
property UBICACION: String read FUBICACION write FUBICACION;
property RACK: String read FRACK write FRACK;
property SECCION: String read FSECCION write FSECCION;
property NIVEL: String read FNIVEL write FNIVEL;
property TIEMPO_MIN: Integer read FTIEMPO_MIN write FTIEMPO_MIN;
property DIFICULTAD: SmallInt read FDIFICULTAD write FDIFICULTAD;
property USERINS: String read FUSERINS write FUSERINS;
property FHINS: TDateTime read FFHINS write FFHINS;
property USERACT: String read FUSERACT write FUSERACT;
property FHACT: TDateTime read FFHACT write FFHACT;
// Tabla: Ubicacion_Prod
property UBIPROD_ID: Integer read FUBIPROD_ID write FUBIPROD_ID;
property CODPRODSER: String read FCODPRODSER write FCODPRODSER;
property DESCRIPPRO: String read FDESCRIPPRO write FDESCRIPPRO;
property CODFAMILIA: String read FCODFAMILIA write FCODFAMILIA;
property CANTIDAD: Double read FCANTIDAD write FCANTIDAD;
property TIPO_ALMACENAJE: SmallInt read FTIPO_ALMACENAJE write FTIPO_ALMACENAJE;
property NUMERO_TARIMA: Integer read FNUMERO_TARIMA write FNUMERO_TARIMA;
property ACTIVO: SmallInt read FACTIVO write FACTIVO;
property COMENTARIOS: String read FCOMENTARIOS write FCOMENTARIOS;
property Error:Integer read FError write FError;
property ErrorMsg:TStringList read FErrorMsg write FErrorMsg;
procedure Prepare;
procedure Insert;
procedure Update;
procedure Update01;
procedure DardeBaja;
procedure Delete;
procedure SelectById(AUBIPROD_ID:integer = 0);
procedure SelectByClave(ANUMALMACEN:String = '');
procedure SelectByNombre(AUBICACION:String = '');
procedure AsignarPropiedades(Aicu:TIB_Cursor);
procedure FillRacks(ACbo:TStrings);
procedure FillFamilias2(ACbo:TStrings);
procedure Clear;
end;
implementation
uses DM_MBA;
{==================================================================
Implementacion TUbicacion
==================================================================}
constructor TUbicacion.Create;
begin
inherited Create; // Inicializa las partes heredadas
FError := 0;
FErrorMsg := TStringList.Create;
Prepare;
end;
destructor TUbicacion.Destroy;
begin
inherited Destroy;
FreeAndNil(FErrorMsg);
end;
procedure TUbicacion.Prepare;
begin
FError :=0;
{Preparar: icuS00}
icuS00 := TIB_Cursor.Create(nil);
icuS00.IB_Connection := DM1.cnMBA;
icuS00.IB_Transaction := DM1.trMBA;
icuS00.SQL.Clear;
icuS00.SQL.Add('SELECT ');
icuS00.SQL.Add(' UBIPROD_ID,');
icuS00.SQL.Add(' NUMALMACEN,');
icuS00.SQL.Add(' UBICACION,');
icuS00.SQL.Add(' CODPRODSER,');
icuS00.SQL.Add(' DESCRIPPRO,');
icuS00.SQL.Add(' CODFAMILIA,');
icuS00.SQL.Add(' CANTIDAD,');
icuS00.SQL.Add(' TIPO_ALMACENAJE,');
icuS00.SQL.Add(' NUMERO_TARIMA,');
icuS00.SQL.Add(' COMENTARIOS,');
icuS00.SQL.Add(' ACTIVO,');
icuS00.SQL.Add(' USERACT,');
icuS00.SQL.Add(' FHACT ');
icuS00.SQL.Add('FROM UBICACION_PROD ');
icuS00.SQL.Add('WHERE (UBIPROD_ID = ?UBIPROD_ID);');
{Preparar: icuS01}
icuS01 := TIB_Cursor.Create(nil);
icuS01.IB_Connection := DM1.cnMBA;
icuS01.IB_Transaction := DM1.trMBA;
icuS01.SQL.Clear;
icuS01.SQL.Add('SELECT ');
icuS01.SQL.Add(' UBIPROD_ID,');
icuS01.SQL.Add(' NUMALMACEN,');
icuS01.SQL.Add(' UBICACION,');
icuS01.SQL.Add(' CODPRODSER,');
icuS01.SQL.Add(' DESCRIPPRO,');
icuS01.SQL.Add(' CODFAMILIA,');
icuS01.SQL.Add(' CANTIDAD,');
icuS01.SQL.Add(' TIPO_ALMACENAJE,');
icuS01.SQL.Add(' NUMERO_TARIMA,');
icuS01.SQL.Add(' COMENTARIOS,');
icuS01.SQL.Add(' ACTIVO,');
icuS01.SQL.Add(' USERACT,');
icuS01.SQL.Add(' FHACT ');
icuS01.SQL.Add('FROM UBICACION_PROD ');
icuS01.SQL.Add('ORDER BY UBICACION;');
{Preparar: icuS02}
icuS02 := TIB_Cursor.Create(nil);
icuS02.IB_Connection := DM1.cnMBA;
icuS02.IB_Transaction := DM1.trMBA;
icuS02.SQL.Clear;
icuS02.SQL.Add('SELECT ');
icuS02.SQL.Add(' UBIPROD_ID,');
icuS02.SQL.Add(' NUMALMACEN,');
icuS02.SQL.Add(' UBICACION,');
icuS02.SQL.Add(' CODPRODSER,');
icuS02.SQL.Add(' DESCRIPPRO,');
icuS02.SQL.Add(' CODFAMILIA,');
icuS02.SQL.Add(' CANTIDAD,');
icuS02.SQL.Add(' TIPO_ALMACENAJE,');
icuS02.SQL.Add(' NUMERO_TARIMA,');
icuS02.SQL.Add(' COMENTARIOS,');
icuS02.SQL.Add(' ACTIVO,');
icuS02.SQL.Add(' USERACT,');
icuS02.SQL.Add(' FHACT ');
icuS02.SQL.Add('FROM UBICACION_PROD ');
icuS02.SQL.Add('WHERE (NUMALMACEN = ?NUMALMACEN);');
{Preparar: icuS03}
icuS03 := TIB_Cursor.Create(nil);
icuS03.IB_Connection := DM1.cnMBA;
icuS03.IB_Transaction := DM1.trMBA;
icuS03.SQL.Clear;
icuS03.SQL.Add('SELECT FIRST 1 ');
icuS03.SQL.Add(' UBIPROD_ID,');
icuS03.SQL.Add(' NUMALMACEN,');
icuS03.SQL.Add(' UBICACION,');
icuS03.SQL.Add(' CODPRODSER,');
icuS03.SQL.Add(' DESCRIPPRO,');
icuS03.SQL.Add(' CODFAMILIA,');
icuS03.SQL.Add(' CANTIDAD,');
icuS03.SQL.Add(' TIPO_ALMACENAJE,');
icuS03.SQL.Add(' NUMERO_TARIMA,');
icuS03.SQL.Add(' COMENTARIOS,');
icuS03.SQL.Add(' ACTIVO,');
icuS03.SQL.Add(' USERACT,');
icuS03.SQL.Add(' FHACT ');
icuS03.SQL.Add('FROM UBICACION_PROD ');
icuS03.SQL.Add('WHERE (UBICACION CONTAINING ?UBICACION);');
{Preparar: isqlI00}
isqlI00 := TIB_DSQL.Create(nil);
isqlI00.IB_Connection := DM1.cnMBA;
isqlI00.IB_Transaction := DM1.trMBA;
isqlI00.SQL.Clear;
isqlI00.SQL.Add('INSERT INTO UBICACION_PROD( ');
isqlI00.SQL.Add(' UBIPROD_ID,');
isqlI00.SQL.Add(' NUMALMACEN,');
isqlI00.SQL.Add(' UBICACION,');
isqlI00.SQL.Add(' CODPRODSER,');
isqlI00.SQL.Add(' DESCRIPPRO,');
isqlI00.SQL.Add(' CODFAMILIA,');
isqlI00.SQL.Add(' CANTIDAD,');
isqlI00.SQL.Add(' TIPO_ALMACENAJE,');
isqlI00.SQL.Add(' NUMERO_TARIMA,');
isqlI00.SQL.Add(' COMENTARIOS,');
isqlI00.SQL.Add(' ACTIVO,');
isqlI00.SQL.Add(' USERACT,');
isqlI00.SQL.Add(' FHACT) ');
isqlI00.SQL.Add('VALUES ( ');
isqlI00.SQL.Add(' ?UBIPROD_ID,');
isqlI00.SQL.Add(' ?NUMALMACEN,');
isqlI00.SQL.Add(' ?UBICACION,');
isqlI00.SQL.Add(' ?CODPRODSER,');
isqlI00.SQL.Add(' ?DESCRIPPRO,');
isqlI00.SQL.Add(' ?CODFAMILIA,');
isqlI00.SQL.Add(' ?CANTIDAD,');
isqlI00.SQL.Add(' ?TIPO_ALMACENAJE,');
isqlI00.SQL.Add(' ?NUMERO_TARIMA,');
isqlI00.SQL.Add(' ?COMENTARIOS,');
isqlI00.SQL.Add(' ?ACTIVO,');
isqlI00.SQL.Add(' ?USERACT,');
isqlI00.SQL.Add(' ?FHACT);');
{Preparar: isqlU00}
isqlU00 := TIB_DSQL.Create(nil);
isqlU00.IB_Connection := DM1.cnMBA;
isqlU00.IB_Transaction := DM1.trMBA;
isqlU00.SQL.Clear;
isqlU00.SQL.Add('UPDATE UBICACION_PROD SET ');
isqlU00.SQL.Add(' UBIPROD_ID = ?UBIPROD_ID,');
isqlU00.SQL.Add(' NUMALMACEN = ?NUMALMACEN,');
isqlU00.SQL.Add(' UBICACION = ?UBICACION,');
isqlU00.SQL.Add(' CODPRODSER = ?CODPRODSER,');
isqlU00.SQL.Add(' DESCRIPPRO = ?DESCRIPPRO,');
isqlU00.SQL.Add(' CODFAMILIA = ?CODFAMILIA,');
isqlU00.SQL.Add(' CANTIDAD = ?CANTIDAD,');
isqlU00.SQL.Add(' TIPO_ALMACENAJE = ?TIPO_ALMACENAJE,');
isqlU00.SQL.Add(' NUMERO_TARIMA = ?NUMERO_TARIMA,');
isqlU00.SQL.Add(' COMENTARIOS = ?COMENTARIOS,');
isqlU00.SQL.Add(' ACTIVO = ?ACTIVO,');
isqlU00.SQL.Add(' USERACT = ?USERACT,');
isqlU00.SQL.Add(' FHACT = ?FHACT ');
isqlU00.SQL.Add('WHERE (UBIPROD_ID = ?UBIPROD_ID);');
{Preparar: isqlU01}
isqlU01 := TIB_DSQL.Create(nil);
isqlU01.IB_Connection := DM1.cnMBA;
isqlU01.IB_Transaction := DM1.trMBA;
isqlU01.SQL.Clear;
isqlU01.SQL.Add('UPDATE UBICACION_PROD SET ');
isqlU01.SQL.Add(' UBICACION = ?UBICACION,');
isqlU01.SQL.Add(' CODPRODSER = ?CODPRODSER,');
isqlU01.SQL.Add(' DESCRIPPRO = ?DESCRIPPRO,');
isqlU01.SQL.Add(' CODFAMILIA = ?CODFAMILIA,');
isqlU01.SQL.Add(' CANTIDAD = ?CANTIDAD,');
isqlU01.SQL.Add(' NUMERO_TARIMA = ?NUMERO_TARIMA,');
isqlU01.SQL.Add(' USERACT = ?USERACT,');
isqlU01.SQL.Add(' FHACT = ?FHACT ');
isqlU01.SQL.Add('WHERE (UBIPROD_ID = ?UBIPROD_ID);');
{Preparar: isqlD00}
isqlU02 := TIB_DSQL.Create(nil);
isqlU02.IB_Connection := DM1.cnMBA;
isqlU02.IB_Transaction := DM1.trMBA;
isqlU02.SQL.Clear;
isqlU02.SQL.Add('UPDATE UBICACION_PROD SET ');
isqlU02.SQL.Add(' ACTIVO = 2,'); //Activo = 2, es baja por tipo 2
isqlU02.SQL.Add(' COMENTARIOS = ?COMENTARIOS,');
isqlU02.SQL.Add(' USERACT = ?USERACT,');
isqlU02.SQL.Add(' FHACT = ?FHACT ');
isqlU02.SQL.Add('WHERE (UBIPROD_ID = ?UBIPROD_ID);');
// Activo es cuando es 0 y 1
{Preparar: isqlD00}
isqlD00 := TIB_DSQL.Create(nil);
isqlD00.IB_Connection := DM1.cnMBA;
isqlD00.IB_Transaction := DM1.trMBA;
isqlD00.SQL.Clear;
isqlD00.SQL.Add('DELETE UBICACION_PROD ');
isqlD00.SQL.Add('WHERE (UBIPROD_ID = ?UBIPROD_ID);');
// Tabla Ubicaciones
icuS10 := TIB_Cursor.Create(nil);
icuS10.IB_Connection := DM1.cnMBA;
icuS10.IB_Transaction := DM1.trMBA;
icuS10.SQL.add ('Select DISTINCT RACK from UBICACIONES order by RACK;');
icuS10.Prepare;
end;
procedure TUbicacion.SelectById(AUBIPROD_ID:integer = 0);
begin
Error := 0;
if AUBIPROD_ID <=0 then AUBIPROD_ID := FUBIPROD_ID;
icuS00.Close;
icuS00.Prepare;
icuS00.ParamByName('UBIPROD_ID').AsInteger := AUBIPROD_ID;
icuS00.Open;
if (icuS00.Eof) then begin
Error := 1;
icuS00.Close;
FErrorMsg.Add (' ' + sm.strfloat(AUBIPROD_ID,'#') + ' NO se encontró!');
exit;
end;
AsignarPropiedades(icuS00);
icuS00.Close;
end;
procedure TUbicacion.SelectByClave(ANUMALMACEN:String = '');
begin
Error := 0;
if length(ANUMALMACEN) <=0 then ANUMALMACEN := FNUMALMACEN;
icuS01.Close;
icuS01.Prepare;
icuS01.ParamByName('NUMALMACEN').AsString := ANUMALMACEN;
icuS01.Open;
if (icuS01.Eof) then begin
Error := 1;
icuS01.Close;
FErrorMsg.Add (' ' + ANUMALMACEN + ' NO se encontró!');
exit;
end;
AsignarPropiedades(icuS01);
icuS01.Close;
end;
procedure TUbicacion.SelectByNombre(AUBICACION:String = '');
begin
Error := 0;
if length(AUBICACION) <=0 then AUBICACION := FNUMALMACEN;
icuS02.Close;
icuS02.Prepare;
icuS02.ParamByName('UBICACION').AsString := AUBICACION;
icuS02.Open;
if (icuS02.Eof) then begin
Error := 1;
icuS02.Close;
FErrorMsg.Add (' ' + AUBICACION + ' NO se encontró!');
exit;
end;
AsignarPropiedades(icuS02);
icuS02.Close;
end;
procedure TUbicacion.AsignarPropiedades(Aicu:TIB_Cursor);
begin
FUBIPROD_ID := Aicu.FieldByName('UBIPROD_ID').AsInteger;
FNUMALMACEN := Aicu.FieldByName('NUMALMACEN').AsString;
FUBICACION := Aicu.FieldByName('UBICACION').AsString;
FCODPRODSER := Aicu.FieldByName('CODPRODSER').AsString;
FDESCRIPPRO := Aicu.FieldByName('DESCRIPPRO').AsString;
FCODFAMILIA := Aicu.FieldByName('CODFAMILIA').AsString;
FCANTIDAD := Aicu.FieldByName('CANTIDAD').AsDouble;
FTIPO_ALMACENAJE := Aicu.FieldByName('TIPO_ALMACENAJE').AsSmallInt;
FNUMERO_TARIMA := Aicu.FieldByName('NUMERO_TARIMA').AsInteger;
FCOMENTARIOS := Aicu.FieldByName('COMENTARIOS').AsString;
FUSERACT := Aicu.FieldByName('USERACT').AsString;
FFHACT := Aicu.FieldByName('FHACT').AsDateTime;
end;
procedure TUbicacion.Insert;
begin
FError :=0;
FUBIPROD_ID := DM1.GetCatalogoID;
isqlI00.ParamByName('UBIPROD_ID').AsDouble := FUBIPROD_ID;
isqlI00.ParamByName('NUMALMACEN').AsString := FNUMALMACEN;
isqlI00.ParamByName('UBICACION').AsString := FUBICACION;
isqlI00.ParamByName('CODPRODSER').AsString := FCODPRODSER;
isqlI00.ParamByName('DESCRIPPRO').AsString := FDESCRIPPRO;
isqlI00.ParamByName('CODFAMILIA').AsString := FCODFAMILIA;
isqlI00.ParamByName('CANTIDAD').AsDouble := FCANTIDAD;
isqlI00.ParamByName('TIPO_ALMACENAJE').AsSmallInt := FTIPO_ALMACENAJE;
isqlI00.ParamByName('NUMERO_TARIMA').AsInteger := FNUMERO_TARIMA;
isqlI00.ParamByName('COMENTARIOS').AsString := FCOMENTARIOS;
isqlI00.ParamByName('ACTIVO').AsSmallInt := FACTIVO;
isqlI00.ParamByName('USERACT').AsString := FUSERACT;
isqlI00.ParamByName('FHACT').AsDateTime := FFHACT;
try
isqlI00.Execute;
except
FError :=1
end;
end;
procedure TUbicacion.Update;
begin
FError :=0;
isqlU00.ParamByName('UBIPROD_ID').AsDouble := FUBIPROD_ID;
isqlU00.ParamByName('NUMALMACEN').AsString := FNUMALMACEN;
isqlU00.ParamByName('UBICACION').AsString := FUBICACION;
isqlU00.ParamByName('CODPRODSER').AsString := FCODPRODSER;
isqlU00.ParamByName('DESCRIPPRO').AsString := FDESCRIPPRO;
isqlU00.ParamByName('CODFAMILIA').AsString := FCODFAMILIA;
isqlU00.ParamByName('CANTIDAD').AsDouble := FCANTIDAD;
isqlU00.ParamByName('TIPO_ALMACENAJE').AsSmallInt := FTIPO_ALMACENAJE;
isqlU00.ParamByName('NUMERO_TARIMA').AsInteger := FNUMERO_TARIMA;
isqlU00.ParamByName('COMENTARIOS').AsString := FCOMENTARIOS;
isqlU00.ParamByName('USERACT').AsString := FUSERACT;
isqlU00.ParamByName('FHACT').AsDateTime := FFHACT;
try
isqlU00.Execute;
except
FError :=1
end;
end;
procedure TUbicacion.Update01;
begin
FError :=0;
isqlU01.ParamByName('UBIPROD_ID').AsDouble := FUBIPROD_ID;
isqlU01.ParamByName('UBICACION').AsString := FUBICACION;
isqlU01.ParamByName('CODPRODSER').AsString := FCODPRODSER;
isqlU01.ParamByName('DESCRIPPRO').AsString := FDESCRIPPRO;
isqlU01.ParamByName('CODFAMILIA').AsString := FCODFAMILIA;
isqlU01.ParamByName('CANTIDAD').AsDouble := FCANTIDAD;
isqlU01.ParamByName('NUMERO_TARIMA').AsInteger := FNUMERO_TARIMA;
isqlU01.ParamByName('USERACT').AsString := FUSERACT;
isqlU01.ParamByName('FHACT').AsDateTime := FFHACT;
try
isqlU01.Execute;
except
FError :=1
end;
end;
procedure TUbicacion.DardeBaja;
begin
FError :=0;
isqlU02.ParamByName('UBIPROD_ID').AsDouble := FUBIPROD_ID;
isqlU02.ParamByName('COMENTARIOS').AsString := FCOMENTARIOS;
isqlU02.ParamByName('USERACT').AsString := FUSERACT;
isqlU02.ParamByName('FHACT').AsDateTime := FFHACT;
try
isqlU02.Execute;
except
FError :=1
end;
end;
procedure TUbicacion.Delete;
begin
FError :=0;
isqlD00.ParamByName('UBIPROD_ID').AsInteger := FUBIPROD_ID;
try
isqlD00.Execute;
except
FError :=1
end;
end;
procedure TUbicacion.FillRacks(ACbo:TStrings);
var tNum,tNombre:String;
iCod:integer;
begin
icuS10.Open;
ACbo.Clear;
iCod := 0;
while not icuS10.Eof do begin
tNum := Trim(icuS10.FieldByName('RACK').AsString);
ACbo.Add (tNum);
icuS10.Next;
end;
icuS10.Close;
end;
procedure TUbicacion.FillFamilias2(ACbo:TStrings);
var tNum,tNombre:String;
iCod:integer;
begin
icu1.Open;
ACbo.Clear;
while not icu1.Eof do begin
tNum := Trim(icu1.FieldByName('CODFAM').AsString);
iCod := sm.ToI(tNum);
tNombre := Trim(icu1.FieldByName('DESCRIPFAM').AsString);
ACbo.AddObject (tNum + ' | ' + tNombre,TObject(iCod));
icu1.Next;
end;
icu1.Close;
end;
procedure TUbicacion.Clear;
begin
FError :=0;
FErrorMsg.Clear;
FUBIPROD_ID := 0;
FNUMALMACEN := '';
FUBICACION := '';
FCODPRODSER := '';
FDESCRIPPRO := '';
FCODFAMILIA := '';
FCANTIDAD := 0;
FTIPO_ALMACENAJE := 0;
FNUMERO_TARIMA := 0;
FCOMENTARIOS := '';
FUSERACT := '';
FFHACT := 0;
end;
//==============================================================
end.
|
unit int_32_3;
interface
implementation
var G: Int32;
procedure Test;
var
x, y, z, a, b, c: Int32;
begin
x := -1;
y := -2;
z := -3;
a := x + y;
b := x + z;
c := a + b;
G := x*a + y*b + z*c;
end;
initialization
Test();
finalization
Assert(G = 32);
end. |
unit UnMovimentoDeCaixaImpressaoView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit,
JvCheckedMaskEdit, JvDatePickerEdit, JvExControls, JvButton,
JvTransparentButton, ExtCtrls,
{ helsonsant }
Util, DataUtil, UnModelo, UnAplicacao, UnMovimentoDeCaixaListaRegistrosModelo;
type
TMovimentoDeCaixaImpressaoView = class(TForm, ITela)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Panel1: TPanel;
btnGravar: TJvTransparentButton;
txtInicio: TJvDatePickerEdit;
txtFim: TJvDatePickerEdit;
txtTipo: TComboBox;
private
FControlador: IResposta;
FMovimentoDeCaixaListaRegistrosModelo: TMovimentoDeCaixaListaRegistrosModelo;
public
function Descarregar: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
end;
var
MovimentoDeCaixaImpressaoView: TMovimentoDeCaixaImpressaoView;
implementation
{$R *.dfm}
{ TMovimentoDeCaixaImpressaoView }
function TMovimentoDeCaixaImpressaoView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TMovimentoDeCaixaImpressaoView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FMovimentoDeCaixaListaRegistrosModelo := nil;
Result := Self;
end;
function TMovimentoDeCaixaImpressaoView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TMovimentoDeCaixaImpressaoView.Modelo(
const Modelo: TModelo): ITela;
begin
Self.FMovimentoDeCaixaListaRegistrosModelo :=
(Modelo as TMovimentoDeCaixaListaRegistrosModelo);
Result := Self;
end;
function TMovimentoDeCaixaImpressaoView.Preparar: ITela;
begin
Result := Self;
end;
end.
|
{******************************************************************************
* *
* PROJECT : EOS Digital Software Development Kit EDSDK *
* NAME : camera.pas *
* *
* Description: This is the Sample code to show the usage of EDSDK. *
* *
* *
*******************************************************************************
* *
* Written and developed by Camera Design Dept.53 *
* Copyright Canon Inc. 2006 All Rights Reserved *
* *
*******************************************************************************
* File Update Information: *
* DATE Identify Comment *
* ----------------------------------------------------------------------- *
* 06-03-22 F-001 create first version. *
* *
******************************************************************************}
unit camera;
interface
uses
Classes, Sysutils, EDSDKApi, EDSDKType, EDSDKError;
type
TCamera = class(TObject)
private
FDeviceInfo : EdsDeviceInfo;
{ capture parameter }
FModelName : PChar;
FAeMode : EdsUInt32;
FAv : EdsUInt32;
FTv : EdsUInt32;
FIso : EdsUInt32;
{ available range list of capture paramter }
FAeModeDesc : EdsPropertyDesc;
FAvDesc : EdsPropertyDesc;
FTvDesc : EdsPropertyDesc;
FIsoDesc : EdsPropertyDesc;
public
constructor Create( devInfo : EdsDeviceInfo );
procedure getModelName( var name : string );
{ capture parameter }
property AEMode:EdsUInt32 read FAeMode write FAeMode;
property Av:EdsUInt32 read FAv write FAv;
property Tv:EdsUInt32 read FTv write FTv;
property Iso:EdsUInt32 read FIso write FIso;
{ interface procedure and function }
procedure setPropertyUInt32( id : EdsPropertyID; value : EdsUInt32 );
function getPropertyUInt32( id : EdsPropertyID ): EdsUInt32;
procedure setPropertyString( id : EdsPropertyID ; const str : PChar );
procedure getPropertyString( id : EdsPropertyID ; var str : PChar );
procedure setPropertyDesc(id: EdsPropertyID; desc: EdsPropertyDesc );
function getPropertyDesc( id: EdsPropertyID ) : EdsPropertyDesc;
end;
implementation
constructor TCamera.Create( devinfo : EdsDeviceInfo );
begin
FDeviceInfo := devInfo;
end;
procedure TCamera.getModelName( var name : string );
var buffer : PChar;
begin
GetMem( buffer,Length( FDeviceInfo.szDeviceDescription ) );
StrCopy( buffer, FDeviceInfo.szDeviceDescription );
name := buffer;
FreeMem( buffer );
end;
procedure TCamera.setPropertyUInt32(id: EdsPropertyID; value: EdsUInt32);
begin
Case id of
kEdsPropID_AEMode: FAeMode := value;
kEdsPropID_Tv: FTv := value;
kEdsPropID_Av: FAv := value;
kEdsPropID_ISOSpeed: FIso := value;
end;
end;
function TCamera.getPropertyUInt32( id : EdsPropertyID ): EdsUInt32;
var value : EdsUInt32;
begin
value := $ffffffff;
Case id of
kEdsPropID_AEMode: value := FAeMode;
kEdsPropID_Tv: value := FTv;
kEdsPropID_Av: value := FAv;
kEdsPropID_ISOSpeed: value := FIso;
end;
Result := value;
end;
procedure TCamera.setPropertyString( id : EdsPropertyID ; const str : PChar );
begin
Case id of
kEdsPropID_ProductName: StrCopy( FModelName, str );
end;
end;
procedure TCamera.getPropertyString( id : EdsPropertyID ; var str : PChar );
begin
Case id of
kEdsPropID_ProductName: StrCopy( str, FModelName );
end;
end;
procedure TCamera.setPropertyDesc(id: EdsPropertyID; desc: EdsPropertyDesc );
begin
Case id of
kEdsPropID_AEMode: FAeModeDesc := desc;
kEdsPropID_Tv: FtvDesc := desc;
kEdsPropID_Av: FAvDesc := desc;
kEdsPropID_ISOSpeed: FIsoDesc := desc;
end;
end;
function TCamera.getPropertyDesc( id: EdsPropertyID ) : EdsPropertyDesc;
var desc : EdsPropertyDesc;
begin
desc.form := 0;
desc.access := kEdsAccess_Read;
desc.numElements := 0;
Case id of
kEdsPropID_AEMode: desc := FAeModeDesc;
kEdsPropID_Tv: desc := FTvDesc;
kEdsPropID_Av: desc := FAvDesc;
kEdsPropID_ISOSpeed: desc := FIsoDesc;
end;
Result := desc;
end;
end.
|
unit SKUtil;
interface
uses Objects;
type
{Структура для хранения списка пройденных вершин}
PTops = ^TTops;
TTops = record
Co : Integer;
NextItem: PTops;
end;
{Очередь}
PQueue = ^TQueue;
TQueue = object(TObject)
Head: PTops; {Указатель на начало очереди}
Tail: PTops; {Указатель на конец очереди}
constructor Init; {Конструктор}
destructor Done; virtual; {Деструктор}
procedure Clear; {Очистка очереди}
procedure PutItem(Data: Integer); {Добавление элемента в очередь}
function GetItem: Integer; {Извлечение элемента из очереди}
end;
MatrRec = record
RowValue : byte;
ColValue : byte;
PDim : pointer;
end;
MatrPtr = ^MatrRec;
{ Создание прямоугольной матрицы }
function CreateMatr(RValue,CValue : byte) : MatrPtr;
{ Заполнение матрицы указанным числом }
function FillMatr(Mp: MatrPtr; El : Integer) : boolean;
{ Отображение матрицы на консоль }
function PrintMatr(Mp : MatrPtr; Im: byte) : boolean;
{ Освобождение памяти выделенное под матрицу, в случае успеха возвращает True }
function ClearMemMatrix(var Mp : MatrPtr) : boolean;
{ Присвоение значения определённого элемента матрицы }
procedure SetElement(Mp : MatrPtr;RValue,CValue : byte; Me : Integer);
{ Возвращает значение заданного элемента матрицы }
function GetElement(Mp : MatrPtr;RValue,CValue : byte) : Integer;
{ Умножает соответствующие элементы матриц одинакового размера без сложения элементов}
function MultMatrixNotAdd(Mp1,Mp2 : MatrPtr) : MatrPtr;
{ Умножение матрицы на матрицу алгебраически }
function MultipleMatr(Mp1,Mp2 : MatrPtr) : MatrPtr;
{ Транспонирует матрицу }
function TranspMatr(Mp : MatrPtr) : MatrPtr;
{ Умножает элементы матриц одинакового размера алгебраически с логическим сложением}
function MultMatrixLogical(Mp1,Mp2 : MatrPtr) : MatrPtr;
implementation
constructor TQueue.Init;
begin
Head := nil;
Tail := nil;
end;
destructor TQueue.Done;
begin
Clear;
end;
procedure TQueue.Clear;
var
p, p1: PTops;
begin
p := Head;
while (p <> nil) do begin
p1 := p;
p := p1^.nextItem;
Dispose(p1); {Освобождаем память, занимаемую эелементом очереди}
end;
end;
{Процедура добавления эелемента в очередь}
procedure TQueue.PutItem(Data: Integer);
var
p: PTops;
begin
New(P);
P^.Co := Data;
P^.NextItem := nil;
if Head <> nil then
Tail^.NextItem := P
else
Head := P;
Tail := P;
end;
{Извлечение элемента из очереди}
function TQueue.GetItem: Integer;
var
p: PTops;
begin
GetItem := 0; {Значение, если очередь пуста}
p := Head;
if p <> nil then begin
Head := p^.NextItem;
GetItem := p^.Co;
Dispose(p);
end;
end;
{ Создание прямоугольной матрицы }
function CreateMatr(RValue,CValue : byte) : MatrPtr;
var
TmpPtr : MatrPtr;
begin
TmpPtr:= nil;
GetMem(TmpPtr,SizeOf(MatrRec));
if TmpPtr = nil then begin
CreateMatr:= nil;
Exit;
end;
with TmpPtr^ do begin
RowValue:= RValue;
ColValue:= CValue;
PDim:= nil;
GetMem(PDim,RValue*CValue*SizeOf(Integer));
if PDim = nil then begin
FreeMem(TmpPtr,SizeOf(MatrRec));
CreateMatr:= nil;
Exit;
end;
end;
FillMatr(TmpPtr,0);
CreateMatr:= TmpPtr;
end;
{ Освобождение памяти выделенное под матрицу, в случае успеха возвращает True }
function ClearMemMatrix(var Mp : MatrPtr) : boolean;
begin
if Mp = nil then ClearMemMatrix:= False
else with Mp^ do begin
if PDim <> nil then
FreeMem(PDim,RowValue*ColValue*SizeOf(Integer));
FreeMem(Mp,SizeOf(MatrRec));
Mp:= nil;
ClearMemMatrix:= True;
end;
end;
{ Отображение матрицы на консоль }
function PrintMatr(Mp : MatrPtr; Im: byte) : boolean;
var
i,j : byte;
begin
if Mp = nil then PrintMatr:= False
else with Mp^ do begin
for i:= 1 to RowValue do begin
for j:= 1 to ColValue do
write(GetElement(Mp,i,j) : Im);
writeln;
end;
PrintMatr:= True;
end;
end;
{ Заполнение матрицы указанным числом }
function FillMatr(Mp: MatrPtr; El : Integer) : boolean;
var
i,j : byte;
begin
if Mp = nil then FillMatr:= False
else with Mp^ do begin
for i:= 1 to RowValue do
for j:= 1 to ColValue do
SetElement(Mp,i,j,El);
FillMatr:= True;
end;
end;
{ Присвоение значения определённого элемента матрицы }
procedure SetElement(Mp : MatrPtr;RValue,CValue : byte; Me : Integer);
var
TmpPtr : ^Integer;
begin
if Mp <> nil then
if (RValue <> 0) or (CValue <> 0) then with Mp^ do begin
pointer(TmpPtr):= pointer(PDim);
Inc(TmpPtr,RowValue*(CValue-1)+RValue-1);
TmpPtr^:= Me;
end;
end;
{ Возвращает значение заданного элемента матрицы }
function GetElement(Mp : MatrPtr;RValue,CValue : byte) : Integer;
var
TmpPtr : ^Integer;
begin
if Mp <> nil then begin
if (RValue <> 0) and (CValue <> 0) then with Mp^ do begin
pointer(TmpPtr):= pointer(PDim);
Inc(TmpPtr,RowValue*(CValue-1)+RValue-1);
GetElement:= TmpPtr^;
end else GetElement:= 0;
end else GetElement:= 0;
end;
{ Транспонирует матрицу }
function TranspMatr(Mp : MatrPtr) : MatrPtr;
var
i,j : byte;
TmpPtr : MatrPtr;
begin
if (Mp <> nil) or (Mp^.PDim <> nil) then
with Mp^ do begin
TmpPtr:= CreateMatr(ColValue,RowValue);
for i:= 1 to RowValue do
for j:= 1 to ColValue do
SetElement(TmpPtr,j,i,GetElement(Mp,i,j));
TranspMatr:= TmpPtr;
end else TranspMatr:= nil;
end;
{ умножает соответствующие элементы матриц одинакового размера без сложения элементов}
function MultMatrixNotAdd(Mp1,Mp2 : MatrPtr) : MatrPtr;
var
TmpPtr : MatrPtr;
i,j,k : byte;
begin
if (Mp1 <> nil) and (Mp2 <> nil) then begin
TmpPtr:= CreateMatr(Mp1^.RowValue,Mp1^.ColValue);
if TmpPtr = nil then begin
MultMatrixNotAdd:= nil;
Exit;
end;
for i:= 1 to TmpPtr^.RowValue do
for j:= 1 to TmpPtr^.ColValue do
SetElement(TmpPtr,i,j,
GetElement(Mp1,i,j)*GetElement(Mp2,i,j));
MultMatrixNotAdd:= TmpPtr;
end else MultMatrixNotAdd :=nil;
end;
{ умножает матрицу на матрицу алгебраически }
function MultipleMatr(Mp1,Mp2 : MatrPtr) : MatrPtr;
var
i,j,k : byte;
TmpPtr : MatrPtr;
begin
if (Mp1 <> nil) and (Mp2 <> nil) then begin
TmpPtr:= CreateMatr(Mp1^.RowValue,Mp2^.ColValue);
if TmpPtr = nil then begin
MultipleMatr:= nil;
Exit;
end;
for i:= 1 to TmpPtr^.RowValue do
for j:= 1 to TmpPtr^.ColValue do
for k:= 1 to Mp1^.ColValue do
SetElement(TmpPtr,i,j,GetElement(TmpPtr,i,j)+
GetElement(Mp1,i,k)*GetElement(Mp2,k,j));
MultipleMatr:= TmpPtr;
end else MultipleMatr:= nil;
end;
function LogicSumm(I1, I2: Integer): Integer;
begin
if (I1 = 0) and (I2 = 0) then
LogicSumm := 0
else
LogicSumm := 1;
end;
{ Умножает элементы матриц одинакового размера алгебраически с логическим сложением}
function MultMatrixLogical(Mp1,Mp2 : MatrPtr) : MatrPtr;
var
i,j,k : byte;
TmpPtr : MatrPtr;
begin
if (Mp1 <> nil) and (Mp2 <> nil) then begin
TmpPtr:= CreateMatr(Mp1^.RowValue,Mp1^.ColValue);
if TmpPtr = nil then begin
MultMatrixLogical:= nil;
Exit;
end;
for i:= 1 to TmpPtr^.RowValue do
for j:= 1 to TmpPtr^.ColValue do
for k:= 1 to Mp1^.ColValue do
SetElement(TmpPtr,i,j, LogicSumm(GetElement(TmpPtr,i,j),
GetElement(Mp1,i,k)*GetElement(Mp2,k,j)));
MultMatrixLogical:= TmpPtr;
end else MultMatrixLogical:= nil;
end;
end.
|
unit BCEditor.Editor.WordWrap.Colors;
interface
uses
Classes, Graphics, BCEditor.Consts;
type
TBCEditorWordWrapColors = class(TPersistent)
strict private
FArrow: TColor;
FLines: TColor;
FOnChange: TNotifyEvent;
procedure SetArrow(const Value: TColor);
procedure SetLines(const Value: TColor);
procedure DoChange;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property Arrow: TColor read FArrow write SetArrow default clWordWrapIndicatorArrow;
property Lines: TColor read FLines write SetLines default clWordWrapIndicatorLines;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorCodeFoldingColors }
constructor TBCEditorWordWrapColors.Create;
begin
inherited;
FArrow := clWordWrapIndicatorArrow;
FLines := clWordWrapIndicatorLines;
end;
procedure TBCEditorWordWrapColors.Assign(Source: TPersistent);
begin
if Source is TBCEditorWordWrapColors then
with Source as TBCEditorWordWrapColors do
begin
Self.FArrow := FArrow;
Self.FLines := FLines;
Self.DoChange;
end
else
inherited;
end;
procedure TBCEditorWordWrapColors.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorWordWrapColors.SetArrow(const Value: TColor);
begin
if Value <> FArrow then
begin
FArrow := Value;
DoChange;
end;
end;
procedure TBCEditorWordWrapColors.SetLines(const Value: TColor);
begin
if Value <> FLines then
begin
FLines := Value;
DoChange;
end;
end;
end.
|
unit SortFlds;
interface
uses Classes, HTTPApp, Db, DbClient, Midas,
XMLBrokr, WebComp, PagItems, MidItems, MidComp;
type
TSortTextColumn = class(TTextColumn, IFormatColumn, IScriptComponent)
private
FButtonCaption: string;
protected
function FormatColumnHeading(Options: TWebContentOptions): string;
function FormatColumnData(const Content: string; Options: TWebContentOptions): string;
{ IScriptComponent }
procedure AddElements(AddIntf: IAddScriptElements);
function GetSubComponents: TObject;
public
constructor Create(AOwner: TComponent); override;
published
property ButtonCaption: string read FButtonCaption write FButtonCaption;
end;
implementation
uses sysutils, MidProd;
resourcestring
sButtonCaption = 'Sort';
const
sSortFunctionName = 'SortXMLDisplay';
sSortFunction =
'function %0:s(xmld,name)' + #13#10 +
'{' + #13#10 +
' xmld.sort(name);' + #13#10 +
'}' + #13#10;
constructor TSortTextColumn.Create(AOwner: TComponent);
begin
inherited;
ButtonCaption := sButtonCaption;
end;
function TSortTextColumn.FormatColumnData(const Content: string; Options: TWebContentOptions): string;
begin
Result := MidItems.FormatColumnData(Self, Content);
end;
function TSortTextColumn.FormatColumnHeading(Options: TWebContentOptions): string;
var
Attribs: string;
Button: string;
Events: string;
begin
AddQuotedAttrib(Attribs, 'VALUE', ButtonCaption);
if not (csDesigning in ComponentState) then
Events := Format('onclick=''if(%3:s)%0:s(%1:s,"%2:s");''', [sSortFunctionName,
GetXMLDisplayName, FieldName, sXMLReadyVar]);
if GetXMLDisplayName <> '' then
Button := Format('<INPUT TYPE=BUTTON %s %s>',
[Attribs, Events]);
Attribs := '';
AddQuotedAttrib(Attribs, 'STYLE', CaptionAttributes.Style);
AddCustomAttrib(Attribs, CaptionAttributes.Custom);
AddQuotedAttrib(Attribs, 'CLASS', CaptionAttributes.StyleRule);
Result := Format('<TH%s>%s%s</TH>'#13#10, [Attribs, Caption, Button]);
end;
function TSortTextColumn.GetSubComponents: TObject;
begin
Result := nil;
end;
procedure TSortTextColumn.AddElements(AddIntf: IAddScriptElements);
begin
inherited;
AddIntf.AddFunction(sSortFunctionName, Format(sSortFunction, [sSortFunctionName]));
end;
end.
|
unit Persistence.Entity.City;
interface
uses
System.Classes,
Spring,
Spring.Persistence.Mapping.Attributes,
Persistence.Consts;
type
TCommonCity = class(TObject)
strict private
FId: int;
FName: string;
FStateId: int;
protected
property Id: int read FId write FId;
property Name: string read FName write FName;
property StateId: int read FStateId write FStateId;
end;
[Entity]
[Table(CITY_TABLE, PUBLIC_SCHEMA)]
[Sequence(CITY_ID_SEQ, 1, 1)]
TCity = class(TCommonCity)
public
[Column(ID_COL, [cpRequired])]
property Id;
[Column(NAME_COL, [], 50)]
property Name;
[Column(STATE_ID_COL, [])]
property StateId;
end;
implementation
end.
|
unit JSONHelper;
interface
function EscapeJSON(s : WideString) : String;
function JSONElement(name, value : WideString) : String; overload;
function JSONElement(name : String; value : Integer) : String; overload;
function JSONElementMoney(name : String; value : Double) : String;
function JSONElementDate(name : String; value : TDateTime) : String;
function JSONElementDateTime(name : String; value : TDateTime) : String;
function JSONElementBool(name : String; value : Boolean) : string;
function JSONElement(name : String; value : Boolean) : string; overload;
function JSONObject(name, sObjData : WideString) : string;
function JSONArray(name : String; sObjects : String) : string;
implementation
uses
System.SysUtils;
function EscapeJSON(s : WideString) : String;
begin
Result := StringReplace(StringReplace(s, '\', '\\', [rfReplaceAll]), '"', '\"', [rfReplaceAll]);
Result := StringReplace(Result, #13, '\\r', [rfReplaceAll]);
Result := StringReplace(Result, #10, '\\n', [rfReplaceAll]);
end;
function JSONElement(name, value : WideString) : String; overload;
begin
Result := Format('"%s":"%s"', [EscapeJSON(name), EscapeJSON(value)]);
end;
function JSONElement(name : String; value : Integer) : String; overload;
var
ws : WideString;
begin
ws := Format('%d', [value]);
Result := JSONElement(name, ws);
end;
function JSONElementMoney(name : String; value : Double) : String;
begin
Result := JSONElement(name, FormatFloat('0.00', value));
end;
function JSONElementDate(name : String; value : TDateTime) : String;
begin
Result := JSONElement(name, FormatDateTime('yyyy-mm-dd', value));
end;
function JSONElementDateTime(name : String; value : TDateTime) : String;
begin
// TODO: This should really be zulu time...
Result := JSONElement(name, FormatDateTime('yyyy-mm-dd hh:nn:ss AMPM', value));
end;
// Special version so boolean is not quoted.
function JSONElementBool(name : String; value : Boolean) : string;
begin
if value then
Result := Format('"%s":%s', [EscapeJSON(name), 'true'])
else
Result := Format('"%s":%s', [EscapeJSON(name), 'false'])
end;
function JSONElement(name : String; value : Boolean) : string; overload;
begin
if value then
Result := JSONElement(name, 'true')
else
Result := JSONElement(name, 'false');
end;
function JSONObject(name, sObjData : WideString) : string;
begin
Result := Format('"%s":{%s}', [name, sObjData]);
end;
function JSONArray(name : String; sObjects : String) : string;
begin
Result := Format('"%s":[%s]', [name, sObjects]);
end;
end.
|
unit GameTexture;
interface
uses
Windows, ASDHeader, ASDUtils, ASDType, GameType {, Graphics};
type
TAdlerTexFile = class(TObject)
private
FW: Integer;
FH: Integer;
FBPP: Integer;
FTexMem: Pointer;
FTexImage: ITexImage;
FName: string;
function BytesPerScanline(PixelsPerScanline, BitsPerPixel,
Alignment: Integer): Longint;
function GetScanLine(bmBits: Pointer; Row: Integer): Pointer;
public
procedure LoadFromSource(TexName, MaskName: string);
function LoadFromFile(FileName: string): ITexImage;
procedure SaveToFile(FileName: string);
function MakeTexImage(Name: string): ITexImage;
property TexImage: ITexImage read FTexImage;
property W: Integer read FW;
property H: Integer read FH;
property BPP: Integer read FBPP;
property Name: string read FName;
end;
const
GL_RGB8 = $8051;
GL_RGBA8 = $8058;
GL_BGR = $80E0;
GL_BGRA = $80E1;
implementation
{ TAdlerTexFile }
procedure TAdlerTexFile.LoadFromSource(TexName, MaskName: string);
var
I, X, Y: Integer;
R: ^TRGBA;
T, M: TRGBA;
Temp: Pointer;
StensilColor: TRGBA;
LText, LMask: Pointer;
TexMem: Pointer;
MaskMem: Pointer;
begin
if Pointer(FTexImage) <> FTexMem then
Exit;
Texture.LoadDataFromFile(PChar(MaskName), FW, FH, FBPP, MaskMem);
if FBPP <> 32 then
Exit;
Texture.LoadDataFromFile(PChar(TexName), FW, FH, FBPP, TexMem);
if FBPP <> 32 then
Exit;
GetMem(Temp, FH * FW * 4);
I := 0;
for Y := FH - 1 downto 0 do
begin
LText := GetScanLine(TexMem, Y);
LMask := GetScanLine(MaskMem, Y);
for X := 0 to FW - 1 do
begin
T := TWrapRGBA(LText^)[X];
M := TWrapRGBA(LMask^)[X];
R := @TWrapRGBA(Temp^)[I];
R.R := T.R;
R.G := T.G;
R.B := T.B;
R.A := (M.R + M.G + M.B) div 3;
Inc(I);
end;
end;
Texture.Free(MaskMem);
Texture.Free(TexMem);
FTexMem := Temp;
FBPP := 32;
end;
function TAdlerTexFile.GetScanLine(bmBits: Pointer; Row: Integer): Pointer;
begin
if FH > 0 then
Row := FH - Row - 1;
Integer(Result) := Integer(bmBits) +
Row * BytesPerScanline(FW, FBPP, 32);
end;
function TAdlerTexFile.BytesPerScanline(PixelsPerScanline, BitsPerPixel,
Alignment: Longint): Longint;
begin
Dec(Alignment);
Result := ((PixelsPerScanline * BitsPerPixel) + Alignment) and not Alignment;
Result := Result div 8;
end;
function TAdlerTexFile.LoadFromFile(FileName: string): ITexImage;
var
Stream: IFileStream;
H: record
Magic: string[3];
W, H, BPP: Integer;
end;
Size: Integer;
S: string;
begin
Stream := Tools.InitFileStream(PChar(FileName), fmOpenRead);
Stream.ReadBuffer(H, SizeOf(H));
if H.Magic <> 'ATF' then
Exit;
FW := H.W;
FH := H.H;
Size := FW * FH * 4;
FBPP := H.BPP;
GetMem(FTexMem,Size);
Stream.ReadBuffer(FTexMem^, Size);
Result := MakeTexImage(FileName);
FreeMem(FTexMem);
FTexMem := nil;
Stream.UnLoad;
end;
procedure TAdlerTexFile.SaveToFile(FileName: string);
var
Stream: IFileStream;
H: record
Magic: string[3];
W, H, BPP: Integer;
end;
begin
if (FTexImage <> nil) or (FTexMem = nil) then
Exit;
Stream := Tools.InitFileStream(PChar(FileName), fmCreate);
H.Magic := 'ATF';
H.W := FW;
H.H := FH;
H.BPP := FBPP;
Stream.WriteBuffer(H, SizeOf(H));
Stream.WriteBuffer(FTexMem^, FW * FH * 4);
FreeMem(FTexMem);
FTexMem := nil;
FName := FileName;
Stream.UnLoad;
end;
function TAdlerTexFile.MakeTexImage(Name: string): ITexImage;
begin
if (FTexMem = nil) and (FTexImage <> nil) then
Exit;
FName := Name;
FTexImage := Texture.NewTex(PChar(FName), FTexMem, GL_RGBA8, GL_BGRA, FW, FH,
0, False, True);
Result := FTexImage;
end;
end.
|
unit UnitFormProgress;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin,
Vcl.ExtCtrls,
Vcl.StdCtrls, System.ImageList, Vcl.ImgList, Vcl.Imaging.pngimage;
type
TProgressInfo = record
Cmd: int64;
Progress: int64;
Max: int64;
What: string;
end;
TFormProgress = class(TForm)
ImageList4: TImageList;
ImageInfo: TImage;
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
ProgressBar1: TProgressBar;
Panel3: TPanel;
private
{ Private declarations }
public
{ Public declarations }
procedure Progress(x: TProgressInfo);
end;
var
FormProgress: TFormProgress;
implementation
uses math, dateutils, UnitApiClient;
{$R *.dfm}
procedure TFormProgress.Progress(x: TProgressInfo);
begin
Label1.Caption := x.What;
case x.Cmd of
0:
Hide;
1:
begin
ProgressBar1.Max := x.Max;
Show;
Top := 100500;
end;
2:
begin
ProgressBar1.Position := x.Progress;
end;
end;
end;
end.
|
unit LazFileUtils;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
* DeleteFileUTF8 and RenameFileUTF8 added
Version 1.01:
Version 1.00:
* File creation.
* UTF8 file functions (equivalent of SysUtils ones)
Notes:
- specific to FPC/Lazarus (not used with Delphi).
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
SysUtils;
function FileCreateUTF8(const FileName: string) : THandle;
function FileOpenUTF8(const FileName: string; Mode: cardinal) : THandle;
function FileExistsUTF8(const Filename: string): boolean;
function FileSetDateUTF8(const FileName: string; Age: integer): integer;
function FileAgeUTF8(const FileName: string): integer;
function FindFirstUTF8(const Path: string; Attr: longint; out Rslt: TSearchRec): longint;
function FindNextUTF8(var Rslt: TSearchRec): longint;
procedure FindCloseUTF8(var F: TSearchrec);
function FileSizeUTF8(const Filename: string): int64;
function GetCurrentDirUTF8(): string;
function SetCurrentDirUTF8(const NewDir: string): boolean;
function DirectoryExistsUTF8(const Directory: string): boolean;
function ForceDirectoriesUTF8(const Dir: string): boolean;
function CreateDirUTF8(const Dir: string): boolean;
function RemoveDirUTF8(const Dir: string): boolean;
function DeleteFileUTF8(const FileName: string): boolean;
function RenameFileUTF8(const OldName, NewName: string): boolean;
// (No GetFileVersionUTF8 function)
//------------------------------------------------------------------------------
implementation
uses
LLCLOSInt, Windows;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
function LFUFindMatchingFile(var F: TSearchRec): integer; forward;
function LFUInternalFileOpen(const FileName: string; Mode: cardinal; var LastOSError: cardinal) : THandle; forward;
function LFUInternalFileAge(const FileName: string; var LastWriteTime: TFileTime): boolean; forward;
function LFUSysFileAttributes(const FileName: string; var LastWriteTime: TFileTime): boolean; forward;
//------------------------------------------------------------------------------
function FileCreateUTF8(const FileName: string) : THandle;
var LastOSError: cardinal;
begin
result := LLCL_CreateFile(@FileName[1], GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0, LastOSError);
end;
function LFUInternalFileOpen(const FileName: string; Mode: cardinal; var LastOSError: cardinal) : THandle;
const
AccessMode: array[0..2] of cardinal = (GENERIC_READ, GENERIC_WRITE,
GENERIC_READ or GENERIC_WRITE);
ShareMode: array[0..4] of cardinal = (0, 0, FILE_SHARE_READ, FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE);
begin
result := LLCL_CreateFile(@FileName[1], AccessMode[Mode and 3],
ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0, LastOSError);
end;
function FileOpenUTF8(const FileName: string; Mode: cardinal) : THandle;
var LastOSError: cardinal;
begin
result := LFUInternalFileOpen(FileName, Mode, LastOSError);
end;
function FileExistsUTF8(const Filename: string): boolean;
var Dummy: TFileTime;
begin
result := LFUSysFileAttributes(FileName, Dummy);
end;
function FileSetDateUTF8(const FileName: string; Age: integer): integer;
var Handle: THandle;
var LastOSError: cardinal;
begin
Handle := LFUInternalFileOpen(FileName, fmOpenWrite, LastOSError);
if Handle = THandle(-1) then
result := LastOSError
else
begin
result := FileSetDate(Handle, Age);
FileClose(Handle);
end;
end;
function FileAgeUTF8(const FileName: string): integer;
var TmpFileTime, LocalFileTime: TFileTime;
begin
if LFUInternalFileAge(FileName, TmpFileTime) then
begin
LLCL_FileTimeToLocalFileTime(TmpFileTime, LocalFileTime);
if LLCL_FileTimeToDosDateTime(LocalFileTime, LongRec(result).Hi, LongRec(result).Lo) then
exit;
end;
result := -1;
end;
function FindFirstUTF8(const Path: string; Attr: longint; out Rslt: TSearchRec): longint;
const faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
var FileName: string;
var LastOSError: cardinal;
begin
Rslt.ExcludeAttr := not Attr and faSpecial;
Rslt.FindHandle := LLCLS_FindFirstNextFile(Path, 0, Rslt.FindData, FileName, LastOSError);
if Rslt.FindHandle<>INVALID_HANDLE_VALUE then
begin
Rslt.Name := {$if Defined(UNICODE) and (not Defined(FPC_UNICODE_RTL))}utf8string(FileName){$else}FileName{$ifend};
result := LFUFindMatchingFile(Rslt);
if result<>0 then FindCloseUTF8(Rslt);
end
else
result := LastOSError;
end;
function FindNextUTF8(var Rslt: TSearchRec): longint;
var FileName: string;
var LastOSError: cardinal;
begin
if LLCLS_FindFirstNextFile('', Rslt.FindHandle, Rslt.FindData, FileName, LastOSError)<>0 then
begin
Rslt.Name := {$if Defined(UNICODE) and (not Defined(FPC_UNICODE_RTL))}utf8string(FileName){$else}FileName{$ifend};
result := LFUFindMatchingFile(Rslt);
end
else
result := LastOSError;
end;
procedure FindCloseUTF8(var F: TSearchrec);
begin
if F.FindHandle<>INVALID_HANDLE_VALUE then
begin
LLCL_FindClose(F.FindHandle);
F.FindHandle := INVALID_HANDLE_VALUE;
end;
end;
// (FileSize for Fileutil and FileSizeUTF8 for LazFileUtils)
function FileSizeUTF8(const Filename: string): int64;
var FileAttribute: TWin32FileAttributeData;
var LastOSError: cardinal;
begin
if LLCL_GetFileAttributesEx(@FileName[1], GetFileExInfoStandard, @FileAttribute, LastOSError) then
result := int64(int64(FileAttribute.nFileSizeHigh) shl 32) + int64(FileAttribute.nFileSizeLow)
else
result := -1;
end;
function GetCurrentDirUTF8(): string;
begin
result := LLCLS_GetCurrentDirectory();
end;
function SetCurrentDirUTF8(const NewDir: string): boolean;
begin
result := LLCL_SetCurrentDirectory(@NewDir[1]);
end;
function DirectoryExistsUTF8(const Directory: string): boolean;
var code: integer;
begin
code := LLCL_GetFileAttributes(@Directory[1]);
result := (code<>INVALID_FILE_ATTRIBUTES) and ((FILE_ATTRIBUTE_DIRECTORY and code)<>0);
end;
function ForceDirectoriesUTF8(const Dir: string): boolean;
var E: EInOutError;
var TmpDir: string;
begin
result := true;
TmpDir := ExcludeTrailingPathDelimiter(Dir);
if TmpDir = '' then begin
E := EInOutError.Create(LLCL_STR_SYSU_CANTCREATEDIR);
E.ErrorCode := 3;
raise E;
end;
if DirectoryExistsUTF8(TmpDir) then exit;
if (Length(TmpDir) < 3) or (ExtractFilePath(TmpDir) = TmpDir) then
result := CreateDirUTF8(TmpDir)
else
result := ForceDirectories(ExtractFilePath(TmpDir)) and CreateDirUTF8(TmpDir);
end;
function CreateDirUTF8(const Dir: string): boolean;
begin
result := LLCL_CreateDirectory(@Dir[1], nil);
end;
function RemoveDirUTF8(const Dir: string): boolean;
begin
result := LLCL_RemoveDirectory(@Dir[1]);
end;
function DeleteFileUTF8(const FileName: string): boolean;
begin
result := LLCL_DeleteFile(@FileName[1]);
end;
function RenameFileUTF8(const OldName, NewName: string): boolean;
begin
result := LLCL_MoveFile(@OldName[1], @NewName[1]);
end;
//------------------------------------------------------------------------------
function LFUFindMatchingFile(var F: TSearchRec): integer;
var LocalFileTime: TFileTime;
var FileName: string;
var LastOSError: cardinal;
begin
with F do begin
while (FindData.dwFileAttributes and ExcludeAttr)<>0 do
begin
if LLCLS_FindFirstNextFile('', FindHandle, FindData, FileName, LastOSError)=0 then
begin
result := LastOSError;
exit;
end;
Name := {$if Defined(UNICODE) and (not Defined(FPC_UNICODE_RTL))}utf8string(FileName){$else}FileName{$ifend};
end;
LLCL_FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
LLCL_FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi, LongRec(Time).Lo);
Size := int64(int64(FindData.nFileSizeHigh) shl 32) + int64(FindData.nFileSizeLow);
Attr := FindData.dwFileAttributes;
// Name := FindData.cFileName; // (Already done)
end;
result := 0;
end;
function LFUInternalFileAge(const FileName: string; var LastWriteTime: TFileTime): boolean;
begin
result := LFUSysFileAttributes(FileName, LastWriteTime);
end;
function LFUSysFileAttributes(const FileName: string; var LastWriteTime: TFileTime): boolean;
var FileAttribute: TWin32FileAttributeData;
var Handle: THandle;
var FindData: TCustomWin32FindData;
var OutFileName: string;
var LastOSError: cardinal;
begin
result := LLCL_GetFileAttributesEx(@FileName[1], GetFileExInfoStandard, @FileAttribute, LastOSError);
if result then
begin
LastWriteTime := FileAttribute.ftLastWriteTime;
result := ((FileAttribute.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0);
end
else
if (LastOSError=ERROR_SHARING_VIOLATION) or (LastOSError=ERROR_LOCK_VIOLATION) or (LastOSError=ERROR_SHARING_BUFFER_EXCEEDED) then
begin
Handle := LLCLS_FindFirstNextFile(FileName, 0, FindData, OutFileName, LastOSError);
if Handle<>INVALID_HANDLE_VALUE then
begin
LLCL_FindClose(Handle);
LastWriteTime := FindData.ftLastWriteTime;
result := ((FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0);
end;
end;
end;
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
{-----------------------------------------------------------------------------
Unit Name: SettingPersistent
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2005 All Rights Reserved.
Author: Erwien Saputra
Purpose: A simple persistent framework using RTTI. The persistent framework
works by reading the properties of TSetting. All properties that
must be persisted must be declared in the published section.
If the class that needs to be persisted cannot be inherited from
TSetting, use Abstract Pattern.
If the order of property is important during loading from persistent
layer, write the property in the order of execution. The property on
the top will be read/write first.
Future improvements:
- Add feature to capture Windows message when the user changed the
screen size, add this code in the TFormSetting.
- Implement the persistent manager as singleton.
- Implement XML persistent.
History:
04/01/2005 - Initial version. Based on my original pet project with persistent
framework that I did on 2001-2002.
04/11/2005 - Added support for nested object at the ini persistent manager.
-----------------------------------------------------------------------------}
unit SettingPersistent;
interface
uses
Classes, Windows, TypInfo, Forms, IniFiles;
type
//TSetting is the base class. It exposes Name property. The persistent
//framework uses this property as identifier. If the subclass does not
//override GetName, this class will return the class name.
//The SetDefault is a placeholder. This method is used to get the default
//state of the object.
{$M+}
TSetting = class
protected
function GetName : string; virtual;
public
procedure SetDefault; virtual;
published
property Name : string read GetName;
end;
{$M-}
TPropRec = record
PropCount : integer;
PropList : TPropList;
end;
//TFormSetting is used for TForm and its descendants. Use this class to works
//with persistent framework. This class works as abstract pattern for TForm.
//At very basic level, this class stores the desktop size, the original form
//size and a reference to the form.
//This class must be created by passing a TForm in the constructor.
//This class exposes Top, Left, Height and Width, it must be executed in that
//order.
TFormSetting = class (TSetting)
private
FForm : TForm;
FDesktopSize: TRect;
FOriginalSize : TRect;
function GetHeight: integer;
function GetLeft: integer;
function GetTop: integer;
function GetWidth: integer;
procedure SetHeight(const Value: integer);
procedure SetLeft(const Value: integer);
procedure SetTop(const Value: integer);
procedure SetWidth(const Value: integer);
procedure GetWorkAreaSize;
protected
property Form : TForm read FForm write FForm;
property DesktopSize : TRect read FDesktopSize write FDesktopSize;
property OriginalSize : TRect read FOriginalSize write FOriginalSize;
public
constructor Create (const AForm : TForm);
destructor Destroy; override;
procedure ResetSizeAndPos;
procedure SetDefault; override;
published
property Top : integer read GetTop write SetTop;
property Left : integer read GetLeft write SetLeft;
property Height : integer read GetHeight write SetHeight;
property Width : integer read GetWidth write SetWidth;
end;
//Persistent manager interface. All concrete persistent manager must implement
//this class.
ISettingPersistentManager = interface
['{16FD2B74-2AED-4F3C-93FE-796AFA406C0A}']
procedure SaveSetting (const ASetting : TSetting);
procedure LoadSetting (const ASetting : TSetting);
end;
//Persistent manager that will read and save to an ini file.
TINISettingPersistentManager = class (TInterfacedObject,
ISettingPersistentManager)
private
FIniFileName : string;
procedure LoadPropList (const ASetting : TSetting; var PropRec : TPropRec);
procedure ReadSetting (const ASetting: TSetting;
const APropRec : TPropRec; const AStrings : TStrings);
procedure SaveSetting (const ASetting : TSetting; const AIniFile : TIniFile;
SectionName : string = ''); overload;
procedure LoadSetting(const ASetting: TSetting; const AIniFile : TIniFile;
SectionName : string = ''); overload;
public
constructor Create (const AFileName : string; CanCreate : boolean = true);
procedure SaveSetting (const ASetting : TSetting); overload;
procedure LoadSetting (const ASetting : TSetting); overload;
end;
//Factory funciton for INISettingManager.
function GetIniPersistentManager : ISettingPersistentManager;
implementation
uses
SysUtils, ShlObj;
const
//Supported property types.
SUPPORTED_PROPERTY = [tkInteger, tkChar, tkEnumeration, tkFloat, tkString,
tkInt64, tkWString, tkLString, tkClass];
var
PersistentManager : ISettingPersistentManager;
function GetSpecialFolderPath(FolderID: Integer; CanCreate: Boolean = True): string;
var
FilePath: array [0..MAX_PATH] of Char;
begin
SHGetSpecialFolderPath(0, @FilePath[0], FolderID, CanCreate);
Result := IncludeTrailingPathDelimiter(FilePath);
end;
function GetIniPersistentManager : ISettingPersistentManager;
begin
if Assigned (PersistentManager) = false then
PersistentManager := TIniSettingPersistentManager.Create (
GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) +
ChangeFileExt(ExtractFileName(Application.ExeName), '.ini'));
Result := PersistentManager;
end;
{ TSetting }
function TSetting.GetName: string;
begin
Result := ClassType.ClassName;
end;
//Place holder. It is not implemented to prevent Abstract error.
procedure TSetting.SetDefault;
begin
//Not implemented.
end;
{ TINISettingPersistentManager }
constructor TINISettingPersistentManager.Create(const AFileName: string;
CanCreate: boolean);
var
FileHandle : integer;
begin
inherited Create;
FIniFileName := AFileName;
if SameText (FIniFileName, EmptyStr) = true then
raise Exception.Create ('File Name cannot be empty.');
FIniFileName := AFileName;
if FileExists (FIniFileName) = false then begin
FileHandle := FileCreate (FIniFileName);
if FileHandle <> -1 then
FileClose (FileHandle);
end;
end;
//Load the property list into internal list.
procedure TINISettingPersistentManager.LoadPropList(const ASetting: TSetting;
var PropRec : TPropRec);
begin
FillChar (PropRec.PropList, SizeOf (PropRec.PropList), 0);
PropRec.PropCount := GetPropList (PTypeInfo (ASetting.ClassInfo),
SUPPORTED_PROPERTY, @PropRec.PropList,
false);
end;
//Load the setting from the peristent layer to the object. If the setting does
//not exist, there will be nothing.
procedure TINISettingPersistentManager.LoadSetting(const ASetting: TSetting;
const AIniFile : TIniFile; SectionName : string = '');
var
Loop : integer;
Values : TStringList;
PropRec : TPropRec;
Obj : TObject;
begin
Values := TStringList.Create;
if SectionName = '' then
SectionName := ASetting.Name;
try
//Load a section from the ini file to a stringlist.
if AIniFile.SectionExists (SEctionName) = true then begin
LoadPropList (ASetting, PropRec);
AIniFile.ReadSectionValues (SectionName, Values);
ReadSetting (ASetting, PropRec, Values);
//For each nested object, recursively call this method.
for Loop := 0 to PropRec.PropCount - 1 do
if PropRec.PropList[Loop]^.PropType^.Kind = tkClass then begin
Obj := GetObjectProp (ASetting, PropRec.PropList[Loop], TSetting);
if Assigned (Obj) then
LoadSetting (Obj as TSetting, AIniFile,
SectionName + '-' + PropRec.PropList[Loop]^.Name);
end;
end;
finally
Values.Free;
end;
end;
//Verify the name value pairs in a strings and assign it to the object. The only
//exception is the Name property, it is used as identifier not as read-write
//property.
procedure TINISettingPersistentManager.LoadSetting(const ASetting: TSetting);
var
IniFile : TIniFile;
begin
IniFile := TIniFile.Create (FIniFileName);
try
LoadSetting (ASetting, IniFile, '');
finally
IniFile.Free;
end;
end;
//Assign values from AStrings to the object of TSetting.
procedure TINISettingPersistentManager.ReadSetting(const ASetting: TSetting;
const APropRec : TPropRec; const AStrings : TStrings);
var
Loop : integer;
Prop : TPropInfo;
Value : variant;
begin
//Iterate through the property of the object.
for Loop := 0 to APropRec.PropCount - 1 do begin
Prop := APropRec.PropList [Loop]^;
//Do not set the name property, the property does not have Setter method, or
//the property is an object.
if SameText (Prop.Name, 'Name') or
(Prop.SetProc = nil) or
(AStrings.IndexOfName (Prop.Name) = -1) or
(Prop.PropType^.Kind = tkClass) then
Continue;
Value := AStrings.Values [Prop.Name];
SetPropValue (ASetting, Prop.Name, Value);
end;
end;
//Persist an object.
{ TODO : Consider refactoring this method. }
procedure TINISettingPersistentManager.SaveSetting (const ASetting: TSetting;
const AIniFile : TIniFile; SectionName : string = '');
var
Values : TStringList;
Loop : integer;
Obj : TObject;
PropRec : TPropRec;
begin
Values := TStringList.Create;
if SameText (SectionName, EmptyStr) = true then
SectionName := ASetting.Name;
try
//Read the property into the internal list.
LoadPropList (ASetting, PropRec);
//Write the property one by one. If the property is write-only, don't bother
//to save it. :)
for Loop := 0 to PropRec.PropCount - 1 do begin
if (PropRec.PropList[Loop]^.PropType^.Kind <> tkClass) and
(SameText (PropRec.PropList[Loop]^.Name, 'Name') or
(PropRec.PropList[Loop]^.GetProc = nil)) then
Continue;
AIniFile.WriteString (SectionName, PropRec.PropList[Loop]^.Name,
GetPropValue (ASetting, PropRec.PropList[Loop]^.Name,
true))
end;
//Persist the nested object.
for Loop := 0 to PropRec.PropCount - 1 do begin
if PropRec.PropList[Loop]^.PropType^.Kind <> tkClass then
Continue;
Obj := GetObjectProp (ASetting, PropRec.PropList[Loop], TSetting);
if Assigned (Obj) then begin
AIniFile.WriteString (SectionName, PropRec.PropList[Loop]^.Name,
SectionName + '-' + PropRec.PropList[Loop]^.Name);
SaveSetting (Obj as TSetting, AIniFile,
SectionName + '-' + PropRec.PropList[Loop]^.Name);
end;
end;
finally
Values.Free;
end;
end;
//Persist a setting to an INI file.
procedure TINISettingPersistentManager.SaveSetting(const ASetting: TSetting);
var
ini : TIniFile;
begin
ini := TIniFile.Create (FIniFileName);
try
SaveSetting (ASetting, ini, '');
finally
ini.Free;
end;
end;
{ TFormSetting }
function TFormSetting.GetWidth: integer;
begin
Result := self.FForm.Width;
end;
//Set the form width. If it is off screen, adjust it.
procedure TFormSetting.SetWidth(const Value: integer);
begin
FForm.Width := Value;
//If the width is wider than the work are, the saved size will be reset to
//the width of the work area.
if self.FForm.Width > self.FDesktopSize.Right then
self.FForm.Width := self.FDesktopSize.Right ;
end;
function TFormSetting.GetTop: integer;
begin
Result := self.FForm.Top;
end;
//Set the form top position. If it is off screen, adjust it.
procedure TFormSetting.SetTop(const Value: integer);
begin
FForm.Top := Value;
//If the Top of the form is less than the top of the work area, reset it.
if FForm.Top < FDesktopSize.Top then
FForm.Top := FDesktopSize.Top
else
//If the top if bigger than the work area size, or part of the form is out
//of the work area, reset the top so when the app is reloaded, the form
//will be displayed entirely.
if (FForm.Top > FDesktopSize.Bottom) or
((FForm.Top + FForm.Height) > FDesktopSize.Bottom) then
FForm.Top := FDesktopSize.Bottom - FForm.Height;
end;
function TFormSetting.GetHeight: integer;
begin
Result := self.FForm.Height;
end;
//Set the form height. If the form is off screen, adjust it.
procedure TFormSetting.SetHeight(const Value: integer);
begin
FForm.Height := Value;
//If the height is bigger than the work area, the saved size will be reset
//to the height of the work area.
if FForm.Height > FDesktopSize.Bottom then
FForm.Height := FDesktopSize.Bottom;
end;
function TFormSetting.GetLeft: integer;
begin
Result := self.FForm.Left;
end;
//Set the left position of the form. If the form is position off the screen,
//adjust it.
procedure TFormSetting.SetLeft(const Value: integer);
begin
FForm.Left := Value;
//If the left is out of the work area, reset it.
if FForm.Left < FDesktopSize.Left then
FForm.Left := FDesktopSize.Left
else
//If the form is off to the right or some of the form is hidden to the
//right, reset the left property.
if (FForm.Left > FDesktopSize.Right) or
((FForm.Left + FForm.Width) > FDesktopSize.Right) then
FForm.Left := FDesktopSize.Right - FForm.Width;
end;
//Get the desktop size.
procedure TFormSetting.GetWorkAreaSize;
begin
SystemParametersInfo (SPI_GETWORKAREA, 0, @FDesktopSize, 0);
end;
constructor TFormSetting.Create (const AForm : TForm);
begin
inherited Create;
//Keep the reference of the AForm.
self.FForm := AForm;
//Get the deskop size,
GetWorkAreaSize;
//Get the original size.
self.FOriginalSize.Left := FForm.Left;
self.FOriginalSize.Top := FForm.Top;
self.FOriginalSize.Right := FForm.Width;
self.FOriginalSize.Bottom := FForm.Height;
end;
destructor TFormSetting.Destroy;
begin
inherited;
end;
//Reset the form position and size to the original position and size.
procedure TFormSetting.ResetSizeAndPos;
begin
self.FForm.Top := FOriginalSize.Top;
self.FForm.Left := FOriginalSize.Left;
self.FForm.Height := FOriginalSize.Bottom;
self.FForm.Width := FOriginalSize.Right;
end;
procedure TFormSetting.SetDefault;
begin
inherited;
ResetSizeAndPos;
end;
end.
|
unit SeniorLimitMaintenanceAddNewLimitDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, wwdblook, Db, DBTables, Wwtable, Buttons;
type
TAddNewLimitSetDialog = class(TForm)
Label1: TLabel;
SwisCodeTable: TwwTable;
Table1: TTable;
Panel1: TPanel;
PreviousButton: TBitBtn;
NextButton: TBitBtn;
Notebook: TNotebook;
ApplyToMunicipalityRadioGroup: TRadioGroup;
SwisCodeListBox: TListBox;
Label2: TLabel;
Label3: TLabel;
SchoolCodeListBox: TListBox;
SchoolCodeTable: TTable;
procedure FormCreate(Sender: TObject);
procedure ApplyToMunicipalityRadioGroupClick(Sender: TObject);
procedure NextButtonClick(Sender: TObject);
procedure PreviousButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
MunicipalityTypeSelected : Integer;
end;
var
AddNewLimitSetDialog: TAddNewLimitSetDialog;
implementation
{$R *.DFM}
uses WinUtils, GlblCnst, GlblVars;
{===========================================================}
Procedure TAddNewLimitSetDialog.FormCreate(Sender: TObject);
begin
FillOneListBox(SwisCodeListBox, SwisCodeTable,
'SwisCode', 'MunicipalityName', 15, True, True,
NextYear, GlblNextYear);
FillOneListBox(SchoolCodeListBox, SwisCodeTable,
'SchoolCode', 'SchoolName', 15, True, True,
NextYear, GlblNextYear);
end; {FormCreate}
{===========================================================}
Procedure TAddNewLimitSetDialog.ApplyToMunicipalityRadioGroupClick(Sender: TObject);
begin
case ApplyToMunicipalityRadioGroup.ItemIndex of
lsAll,
lsCounty :
begin
NextButton.Enabled := True;
NextButton.Caption := 'Add Set';
end;
lsCountyTown,
lsTown,
lsSchoolTown :
begin
NextButton.Enabled := True;
PreviousButton.Enabled := True;
Notebook.PageIndex := 1; {Swis code page}
If (ApplyToMunicipalityRadioGroup.ItemIndex in [lsTown, lsCountyTown])
then NextButton.Caption := 'Add Set';
end; {lsCountyTown ...}
lsCountySchool,
lsSchool:
begin
NextButton.Enabled := True;
PreviousButton.Enabled := True;
Notebook.PageIndex := 1; {Swis code page}
NextButton.Caption := 'Add Set';
end; {lsCountySchool...}
end; {case ApplyToMunicipalityRadioGroup.ItemIndex of}
MunicipalityTypeSelected := ApplyToMunicipalityRadioGroup.ItemIndex;
end; {ApplyToMunicipalityRadioGroupClick}
{===========================================================}
Procedure TAddNewLimitSetDialog.NextButtonClick(Sender: TObject);
begin
If (MunicipalityTypeSelected = lsSchoolTown)
then
begin
Notebook.PageIndex := 2; {School code page}
NextButton.Caption := 'Add Set';
end
else Close;
end; {NextButtonClick}
{===========================================================}
Procedure TAddNewLimitSetDialog.PreviousButtonClick(Sender: TObject);
begin
If ((MunicipalityTypeSelected = lsSchoolTown) and
(Notebook.PageIndex = 2))
then
begin
Notebook.PageIndex := 1;
NextButton.Caption := 'Next';
end
else
begin
Notebook.PageIndex := 0;
PreviousButton.Enabled := False;
NextButton.Caption := 'Next';
end; {else of If ((MunicipalityTypeSelected = lsSchoolTown) and ...}
end; {PreviousButtonClick}
end.
|
unit reghelper;
interface
uses hash,classes;
// ------------------------------------------------------------ Useful Functions
function GetURL(url:string): string;
function GetAppPath():string;
function CSVify(s:string):string;
// ---------------------------------------------------------- Data Storage Types
type TClassinfo = record
course: string; // course name
coursecode: string; // 4 digit course number
department: string; // department name
departmentcode: string; // 4 letter department abbreviation. Not on page, taken from department hash table deptlist
subject: string; // full subject name
subjectcode: string; // 4 letter subject abbreviation
division: string; // division name
divisioncode:string; // 1 or 2 letter division code
divisionscode:string; // 1 letter division code
classname: string; // class name
classsection: string; // 3 digit section ie '001', '002', 'R01'
year: string; // four digit year
semester: string; // 'spring', 'fall', 'summer'
instructor: string; // full name
students: string; // number of students
school: string; // school name
time: string; // class time
location:string; // class location
callnumber:string; // 5 digit call number
end;
type SubjectItem = class(TCollectionItem)
public url:string;
end;
type ClassItem = class(TCollectionItem)
public url:string;
end;
// ----------------------------------------------------------- Main Helper Class
type TSpider = class
public
deptlist: TStringKeyHashTable; // used to map department names (key) into four letter codes (data)
subjectlist: TCollection; // stores a list of subjects & urls from most recently parsed directory listing
classlist: TCollection; // stores a list of classes & urls from most recently parsed directory listing
classinfo: TClassinfo; // stores information about individual classes from most recently parsed class page
procedure ParseDeptPage(page:string);
procedure ParseSubjectList(page:string; baseurl:string);
procedure ParseClassList(page:string; baseurl:string);
procedure ParseClassPage(page:string);
destructor Destroy; override;
end;
implementation
uses Windows, wininet, Messages, SysUtils, Graphics, Controls, Forms, Dialogs, StdCtrls;
type
WinException = class
private
_err:longword;
_msg:string;
public
constructor create (msg:string);
procedure show();
end;
constructor WinException.create (msg:string);
begin
_err := GetLastError();
_msg := msg;
end;
procedure WinException.show();
var b1: string;
var b2: array[0..255] of Char;
begin
b1 := Format(_msg + ', Error %d',[_err]);
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,nil,_err,0,@b2,255,nil);
MessageBox (0,@b2,pchar(b1),MB_ICONEXCLAMATION or MB_OK);
end;
function GetURL(url:string): string;
const buffersize = 1024;
var buffer: array[0..buffersize] of Char;
var return: string;
var ihandle: HINTERNET;
var fhandle: HINTERNET;
var size: DWORD;
begin
return := '';
ihandle := InternetOpen('regripper 1.1',INTERNET_OPEN_TYPE_PRECONFIG,nil,nil,0);
fhandle := InternetOpenUrl(ihandle,pchar(url),nil,0,INTERNET_FLAG_RAW_DATA, 0);
try
try
repeat
if (not InternetReadFile(fhandle,@buffer,buffersize,size)) then Raise WinException.create('InternetReadFile Failed');
buffer[size] := Char(0);
return := return + buffer;
until size = 0;
except
on e:WinException do e.show;
end;
finally
InternetCloseHandle(fhandle);
InternetCloseHandle(ihandle);
GetURL := return;
end;
end;
function GetAppPath():string;
var name:array[0..255] of char; l:integer;
begin
l := GetModuleFileName(HInstance,@name,255) - 1;
while(name[l] <> '\') do dec(l);
name[l] := char(0);
GetAppPath := string(name);
end;
function CSVify(s:string):string;
var i:integer;
quoted:boolean;
begin
quoted := false;
i := 1;
while i <= length(s) do
begin
if (ord(s[i]) < 32) then s[i] := ' ';
if (not quoted) and ((s[i] = ',') or (s[i] = '"')) then
begin
s := '"' + s + '"';
inc(i);
quoted := true;
end;
if (s[i] = '"') and not((i=length(s)) and quoted) then
begin
insert('"',s,i);
inc(i);
end;
inc(i);
end;
result := s;
end;
function StringPos(subst: string; s: string; startat:integer):integer;
{
StringPos searches for a substring, subst, within a string, s,
and returns the position where it finds the first occurence.
It is exactly like pascal's Pos function except that it includes
a third parameter, startat, which lets the search begin from
from the middle of the string instead of at the beginning.
}
var p:integer;
begin
if startat < 1 then startat := 1;
if (startat > length(s)) then
StringPos := 0
else if (subst = '') then
StringPos := 1
else
begin
p := pos(subst,Pchar(@s[startat]));
if (p>0) then StringPos := p + startat -1 else StringPos := 0;
end;
end;
function StripHTML(s:string):string;
{
StripHTML will remove any text that falls between '<' and '>'
in a string. It replaces any whitespace in the middle of a string
with a single space (' ') and trims all whitespace from the
beginning and end.
}
var i:integer;
return: string;
goodstuff,postspace: boolean;
begin
goodstuff := true;
postspace := false;
return := '';
for i := 1 to length(s) do
begin
if s[i]='<' then
goodstuff := false
else if s[i]='>' then
goodstuff := true
else if goodstuff then
begin
if (ord(s[i]) <= 32) then
begin
if length(return)>0 then postspace := true;
end
else
begin
if postspace then begin return := return + ' '; postspace := false; end;
return := return + s[i];
end
end;
end;
StripHTML := return;
end;
function KeepNumbers(s:string):string;
{
Returns the digits at the beginning of a string
}
var i:integer;
return:string;
begin
return := '';
if (length(s) >0) then
begin
i := 1;
while (('0' <= s[i]) and (s[i] <= '9')) do
begin
return := return + s[i];
inc(i);
end;
end;
KeepNumbers := return;
end;
function getvalue(findfirst,opener,closer,page:string; startat:integer):string;
{
GetValue is a function that can be used to extract a substring from a
larger string. It is only useful when the substring is surrounded by
the opener and closer strings and preceded by the findfirst string.
For example,
getvalue('heading', '(' , ')' , 'junk heading morejunk (value)', 0)
returns 'value' because it is between the parentheses and after the
heading.
Delphi does not include any built in support for regular expressions.
}
var spos,epos:integer;
begin
getvalue := '';
spos := StringPos(findfirst,page,startat);
if (spos<1) then exit;
spos := StringPos(opener,page,spos);
if (spos<1) then exit;
epos := StringPos(closer,page,spos);
if (epos<spos) then exit;
getvalue := Copy(page,spos+length(opener),epos-spos-length(opener));
end;
procedure TSpider.ParseDeptPage(page:string);
var no,nc,vo,vc,vm: string;
deptname, deptabbv:string;
pos1,pos2,pos3,pos4,pos5,pos6:integer;
begin
if deptlist = nil then deptlist := TStringKeyHashTable.Create;
no := '<tr valign=top><td bgcolor=#DADADA>';
nc := '</td>';
vo := '<a href="';
vm := 'sel/';
vc := '">';
pos2 := 1;
repeat
pos1 := StringPos(no,page,pos2);
pos2 := StringPos(nc,page,pos1);
deptname := Copy(page,pos1 + length(no), pos2 - pos1 - length(no));
pos3 := Stringpos(vo,page,pos2);
pos4 := Stringpos(vm,page,pos3);
pos5 := Stringpos('_',page,pos3);
pos6 := Stringpos(vc,page,pos3);
if (pos4 + length(vm) < pos5 ) and (pos5 < pos6) then
deptabbv := Copy(page,pos4 + length(vm),pos5 - pos4 - length(vm))
else
deptabbv := '';
deptlist.Value[deptname] := deptabbv;
until (pos1 = 0) or (pos2=0)
end;
procedure TSpider.ParseSubjectList(page:string; baseurl:string);
var item: SubjectItem;
opener,closer: string;
pos1,pos2: integer;
begin
if subjectlist <> nil then subjectlist.Destroy;
subjectlist := TCollection.Create(SubjectItem);
opener := '<IMG SRC="/icons/folder.gif" ALT="[DIR]"> <A HREF="';
closer := '/">';
pos2 := 1;
repeat
pos1 := StringPos(opener,page,pos2);
pos2 := StringPos(closer,page,pos1);
if pos2 - pos1 - length(opener) = 4 then
begin
item := SubjectItem(subjectlist.add());
item.url := baseurl + Copy(page,pos1+length(opener),pos2-pos1-length(opener)) + '/';
end;
until (pos1 = 0) or (pos2 = 0);
end;
procedure TSpider.ParseClassList(page:string; baseurl:string);
var item: ClassItem;
opener,closer: string;
pos1,pos2: integer;
begin
if classlist <> nil then classlist.Destroy;
classlist := TCollection.Create(ClassItem);
opener := '<IMG SRC="/icons/folder.gif" ALT="[DIR]"> <A HREF="';
closer := '/">';
pos2 := 1;
repeat
pos1 := StringPos(opener,page,pos2);
pos2 := StringPos(closer,page,pos1);
if (pos1 > 0) and (pos2 > 0) and (page[pos2 - 4] = '-') and (page[pos2-10] = '-') then
begin
item := ClassItem(classlist.add());
item.url := baseurl + Copy(page,pos1+length(opener),pos2-pos1-length(opener)) + '/';
end;
until (pos1 = 0) or (pos2 = 0);
end;
procedure TSpider.ParseClassPage(page:string);
var titleopen,tableopen,pos:integer;
no,nc,vo,vc:string;
key,coords:string;
begin
no := '<tr valign=top><td bgcolor=#99CCFF>'; // name opener
nc := '</td>'; // name closer
vo := '<td bgcolor=#DADADA>'; // value opener
vc := '</td></tr>'; // value closer
titleopen := StringPos('<td colspan=2 bgcolor=#99CCFF><b><br>',page,1);
tableopen := StringPos('<tr valign=top><td bgcolor=#99CCFF>',page,1);
classinfo.course := getvalue('','<font size=+2>','</font><br>',page,titleopen);
classinfo.classname := StripHTML(getvalue('<font size=+2>','</font><br>','<tr valign=top><td bgcolor=#99CCFF>',page,titleopen));
classinfo.instructor := getvalue(no+'Instructor'+nc,vo,vc,page,tableopen);
if length(classinfo.instructor) = 0 then
classinfo.instructor := getvalue(no+'Instructors'+nc,vo,vc,page,tableopen);
classinfo.department := StripHTML(getvalue(no+'Department'+nc,vo,vc,page,tableopen));
classinfo.students := KeepNumbers(getvalue(no+'Enrollment'+nc,vo,vc,page,tableopen));
classinfo.subject := getvalue(no+'Subject' + nc,vo,vc,page,tableopen);
classinfo.division := getvalue(no+'Division' + nc,vo,vc,page,tableopen);
classinfo.school := StripHTML(getvalue(no+'School'+nc,vo,vc,page,tableopen));
classinfo.callnumber := getvalue(no + 'Call Number' + nc,vo,vc,page,tableopen);
classinfo.divisioncode := getvalue(no + 'Number' + nc,vo,vc,page,tableopen);
classinfo.divisioncode := Copy(classinfo.divisioncode,1,length(classinfo.divisioncode)-4);
key := getvalue(no+'Section key'+nc,vo,vc,page,tableopen);
if length(key) = 17 then
begin
classinfo.year := Copy(key,1,4);
case key[5] of
'3': classinfo.semester := 'fall';
'2': classinfo.semester := 'summer';
'1': classinfo.semester := 'spring';
else
classinfo.semester := 'unknown';
end;
classinfo.subjectcode := Copy(key,6,4);
classinfo.coursecode := Copy(key,10,4);
classinfo.divisionscode := string(key[14]);
classinfo.classsection := Copy(key,15,3);
end;
classinfo.departmentcode := string(deptlist.Value[classinfo.department]);
coords := getvalue(no + 'Day & Time<br>Location' + nc,vo,vc,page,tableopen);
pos := StringPos('<br>',coords,1);
classinfo.time := Copy(coords,0,pos-1);
classinfo.location := Copy(coords,pos+4,length(coords)-pos-3);
end;
destructor TSpider.Destroy;
begin
if (deptlist <> nil) then deptlist.Destroy;
if (subjectlist <> nil) then subjectlist.Destroy;
if (classlist <> nil) then classlist.Destroy;
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Performance.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
ADAPT, ADAPT.Intf;
{$I ADAPT_RTTI.inc}
type
/// <summary><c>Common Interface for all Performance Counter Types.</c></summary>
/// <remarks>
/// <para><c>Keeps track of Performance both Instant and Average, in units of Things Per Second.</c></para>
/// <para><c>Note that this does NOT operate like a "Stopwatch", it merely takes the given Time Difference (Delta) Values to calculate smooth averages.</c></para>
/// </remarks>
IADPerformanceCounter = interface(IADInterface)
['{6095EB28-79FC-4AC8-8CED-C11BA9A2CF48}']
{ Getters }
function GetAverageOver: Cardinal;
function GetAverageRate: ADFloat;
function GetInstantRate: ADFloat;
{ Setters }
procedure SetAverageOver(const AAverageOver: Cardinal = 10);
{ Public Methods }
procedure RecordSample(const AValue: ADFloat);
procedure Reset;
/// <summary><c>The number of Samples over which to calculate the Average</c></summary>
property AverageOver: Cardinal read GetAverageOver write SetAverageOver;
/// <summary><c>The Average Rate (based on the number of Samples over which to calculate it)</c></summary>
property AverageRate: ADFloat read GetAverageRate;
/// <summary><c>The Instant Rate (based only on the last given Sample)</c></summary>
property InstantRate: ADFloat read GetInstantRate;
end;
/// <summary><c>Common Interface for all Performance Limiter Types.</c></summary>
/// <remarks>
/// <para><c>Limiters serve to enforce precise-as-possible Time Differential Based (Delta-Based) calculations.</c></para>
/// </remarks>
IADPerformanceLimiter = interface(IADInterface)
['{279704C6-BBAF-415F-897D-77953D049E8E}']
{ Getters }
function GetNextDelta: ADFloat;
function GetRateDesired: ADFloat;
function GetRateLimit: ADFloat;
function GetThrottleInterval: Cardinal;
{ Setters }
procedure SetRateDesired(const ARateDesired: ADFloat);
procedure SetRateLimit(const ARateLimit: ADFloat);
procedure SetThrottleInterval(const AThrottleInterval: Cardinal);
{ Public Methods }
{ Properties }
property NextDelta: ADFloat read GetNextDelta;
property RateDesired: ADFloat read GetRateDesired write SetRateDesired;
property RateLimit: ADFloat read GetRateLimit write SetRateLimit;
property ThrottleInterval: Cardinal read GetThrottleInterval write SetThrottleInterval;
end;
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995, 1999 Inprise Corporation }
{ }
{*******************************************************}
unit CDSEdit;
interface
uses SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, DB, DBClient, DsgnIntf;
type
TClientDataForm = class(TForm)
GroupBox1: TGroupBox;
DataSetList: TListBox;
OkBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure OkBtnClick(Sender: TObject);
procedure HelpBtnClick(Sender: TObject);
procedure DataSetListDblClick(Sender: TObject);
procedure DataSetListKeyPress(Sender: TObject; var Key: Char);
private
FDataSet: TClientDataSet;
FDesigner: IFormDesigner;
procedure CheckComponent(const Value: string);
function Edit: Boolean;
end;
function EditClientDataSet(ADataSet: TClientDataSet; ADesigner: IFormDesigner): Boolean;
function LoadFromFile(ADataSet: TClientDataSet): Boolean;
procedure SaveToFile(ADataSet: TClientDataSet);
implementation
uses DsnDBCst, TypInfo, LibHelp, DBConsts, Consts, Provider;
{$R *.DFM}
function EditClientDataSet(ADataSet: TClientDataSet; ADesigner: IFormDesigner): Boolean;
begin
with TClientDataForm.Create(Application) do
try
Caption := Format(SClientDataSetEditor, [ADataSet.Owner.Name, DotSep, ADataSet.Name]);
FDataSet := ADataSet;
FDesigner := ADesigner;
Result := Edit;
finally
Free;
end;
end;
function LoadFromFile(ADataSet: TClientDataSet): Boolean;
begin
with TOpenDialog.Create(nil) do
try
Title := sOpenFileTitle;
DefaultExt := 'cds';
Filter := SClientDataFilter;
Result := Execute;
if Result then ADataSet.LoadFromFile(FileName);
finally
Free;
end;
end;
procedure SaveToFile(ADataSet: TClientDataSet);
begin
with TSaveDialog.Create(nil) do
try
Options := [ofOverwritePrompt];
DefaultExt := 'cds';
Filter := SClientDataFilter;
if Execute then ADataSet.SaveToFile(FileName);
finally
Free;
end;
end;
procedure TClientDataForm.CheckComponent(const Value: string);
var
DataSet: TDataSet;
begin
DataSet := TDataSet(FDesigner.GetComponent(Value));
if (DataSet.Owner <> FDataSet.Owner) then
DataSetList.Items.Add(Concat(DataSet.Owner.Name, '.', DataSet.Name))
else
if AnsiCompareText(DataSet.Name, FDataSet.Name) <> 0 then
DataSetList.Items.Add(DataSet.Name);
end;
function TClientDataForm.Edit: Boolean;
begin
DataSetList.Clear;
FDesigner.GetComponentNames(GetTypeData(TDataSet.ClassInfo), CheckComponent);
if DataSetList.Items.Count > 0 then
begin
DataSetList.Enabled := True;
DataSetList.ItemIndex := 0;
OkBtn.Enabled := True;
ActiveControl := DataSetList;
end else
ActiveControl := CancelBtn;
Result := ShowModal = mrOK;
end;
procedure TClientDataForm.OkBtnClick(Sender: TObject);
var
DataSet: TDataSet;
DSProv: TDataSetProvider;
begin
try
if DataSetList.ItemIndex >= 0 then
begin
Screen.Cursor := crHourGlass;
try
with DataSetList do
DataSet := FDesigner.GetComponent(Items[ItemIndex]) as TDataSet;
if (DataSet is TClientDataSet) then
FDataSet.Data := TClientDataSet(DataSet).Data
else
begin
DSProv := TDataSetProvider.Create(nil);
try
DSProv.DataSet := DataSet;
FDataSet.Data := DSProv.Data
finally
DSProv.Free;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end
else
FDataSet.Data := varNull;
except
ModalResult := mrNone;
raise;
end;
end;
procedure TClientDataForm.FormCreate(Sender: TObject);
begin
HelpContext := hcDAssignClientData;
end;
procedure TClientDataForm.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TClientDataForm.DataSetListDblClick(Sender: TObject);
begin
if OkBtn.Enabled then OkBtn.Click;
end;
procedure TClientDataForm.DataSetListKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #13) and OkBtn.Enabled then OkBtn.Click;
end;
end.
|
program l_dwukierunkowa;
uses crt,dos;
//struktura opisujaca dana osobe, element listy
type osobaPTR = ^osoba;
osoba = record
nazwisko : String;
stanowisko : String;
zarobki : Integer;
nastepny : osobaPTR;
poprzedni : osobaPTR;
end;
var pracownicy : osobaPTR;
//dodawanie elementu na początek listy
procedure pushFRONT(var lista : osobaPTR; nazwisko : String; stanowisko : String; zarobki : Integer);
var dodawany : osobaPTR;
begin
New(dodawany);
dodawany^.nazwisko := nazwisko;
dodawany^.stanowisko := stanowisko;
dodawany^.zarobki := zarobki;
dodawany^.nastepny := lista;
dodawany^.poprzedni := nil;
lista^.poprzedni := dodawany;
lista := dodawany;
end;
//dodawanie elementu do listy po danym nazwisku
procedure pushMIDDLE(var lista : osobaPTR; poKtorejNazwisko : String; nazwisko : String; stanowisko : String; zarobki : Integer);
var dodawany : osobaPTR;
var pomoc : osobaPTR;
begin
pomoc := lista;
New(dodawany);
dodawany^.nazwisko := nazwisko;
dodawany^.stanowisko := stanowisko;
dodawany^.zarobki := zarobki;
while pomoc^.nazwisko <> poKtorejNazwisko do
begin
pomoc := pomoc^.nastepny;
end;
dodawany^.poprzedni := pomoc^.nastepny^.poprzedni;
dodawany^.nastepny := pomoc^.nastepny;
pomoc^.nastepny := dodawany;
end;
//wyswielanie listy
procedure printList(lista : osobaPTR);
var pomoc : osobaPTR;
begin
writeln;
pomoc := lista;
while pomoc^.nastepny <> nil do
begin
writeln(pomoc^.nazwisko,' | ',pomoc^.stanowisko,' | ',pomoc^.zarobki);
pomoc := pomoc^.nastepny;
end;
writeln;
end;
begin
New(pracownicy);
pracownicy^.nastepny := nil;
pracownicy^.poprzedni := nil;
{
//DO DEBUGGINGU
pushFRONT(pracownicy,'duda','ochlej',100);
pushFRONT(pracownicy,'blach','smartGUY',200);
pushFRONT(pracownicy,'kaminski','student',300);
pushFRONT(pracownicy,'chrzanowska','wtf',400);
printList(pracownicy);
pushMIDDLE(pracownicy,'blach','baranowski','student',500);
pushMIDDLE(pracownicy,'duda','porzycki','laborant',1000);
pushMIDDLE(pracownicy,'chrzanowska','synowiec','hab',300);
printList(pracownicy);
readln;
}
end.
|
unit uLocalization;
interface
uses
Windows, Messages,Menus, StdCtrls, SysUtils, Variants, Classes, Controls, Forms,
Generics.Collections, Buttons, ComCtrls, StrUtils, Vcl.ExtCtrls,
{XML}
Xml.xmldom, Xml.XMLIntf, Xml.Win.msxmldom, Xml.XMLDoc;
type TLocalization = class
private const
RootNodeName = 'Language';
HeadNodeName = 'Header';
FormsNodeName = 'Forms';
StringsNodeName = 'Strings';
HintSuffix = 'Hint';
SelfCaptionName = 'FormCaption';
strDefaultLanguageName = 'By default (English)';
strDefaultLanguageSName = 'Default';
public type TLanguage = class
Name: string;
ShortName: string;
Author: string;
FileName: string;
Date: string;
Version: string;
public
constructor Create(Name: String = strDefaultLanguageName;
shortName: String = strDefaultLanguageSName); overload;
end;
private
LocXML: IXMLDocument;
RootNode: iXMLNode;
HeadNode: iXMLNode;
FormsNode: iXMLNode;
StringsNode: iXMLNode;
FLanguages: TList<TLanguage>;
FCurLanguage: TLanguage;
constructor Create; overload;
//FFileList: TDictionary <string, string>;
function ListLanguages(LocFolderPath: string): TList<TLanguage>;
function ValidateLanguageXML(XML: IXMLDocument): boolean;
function GetLanguage(LocFileName: string): TLanguage;
procedure ApplyLanguage;
protected
//
public
//constructor Create(const XMLLocFilePath: string); overload;
constructor Create(LocFolderPath: string); overload;
property Languages: TList<TLanguage> read FLanguages;
property CurrentLanguage: TLanguage read FCurLanguage write FCurLanguage;
function Strings(StringId: string; Default: string): string;
function SetLanguage(ByShortName: string): boolean; overload;
function SetLanguage(ByIndex: integer): boolean; overload;
function FindLanguage(lngShortName: string): Integer;
function HaveTranslation(FormName: String; ComponentName: String): Boolean;
function GetTranslation(FormName: String; ComponentName: String): String;
procedure TranslateForm(Form: TForm);
//published
//
end;
implementation
uses uLog;
constructor TLocalization.TLanguage.Create(Name: String = strDefaultLanguageName;
shortName: String = strDefaultLanguageSName);
begin
Self.Name:= Name;
Self.ShortName:=shortName;
Self.FileName:= 'Default.xml';
end;
constructor TLocalization.Create();
begin
inherited Create;
LocXML:=TXMLDocument.Create(nil);
LocXML.Options :=[doNodeAutoIndent, doAttrNull];
LocXML.Active:=True;
end;
constructor TLocalization.Create(LocFolderPath: string);
begin
Self.Create;
if ExtractFileDrive(LocFolderPath) = '' then
//LocFolderPath := ExtractFilePath(Application.ExeName) + LocFolderPath;
LocFolderPath:= ExpandFileName(LocFolderPath);
LocFolderPath := IncludeTrailingPathDelimiter(LocFolderPath);
if not DirectoryExists(LocFolderPath) then raise Exception.Create('Directory not found: ' + LocFolderPath);
FLanguages:= ListLanguages(LocFolderPath);
Log('Languages found: ', Flanguages.Count);
end;
function TLocalization.ListLanguages(LocFolderPath: string): TList<TLanguage>;
var
fs: TSearchRec;
tempLng: TLanguage;
begin
Result:= TList<TLanguage>.Create;
// Result.Add(TLanguage.Create()); //язык по умолчанию
if FindFirst(LocFolderPath + '*.xml', faAnyFile - faDirectory, fs) = 0 then repeat
tempLng:= GetLanguage(LocFolderPath + fs.Name);
if tempLng<> nil then Result.Add(tempLng);
until FindNext(fs) <> 0;
FindClose(fs);
end;
function TLocalization.GetLanguage(LocFileName: String): TLanguage;
var
tXML: IXMLDocument;
HeaderNode: IXMLNode; //temporary xml
begin
Result:= TLanguage.Create;
tXML:=TXMLDocument.Create(nil);
tXML.LoadFromFile(LocFileName);
tXML.Active:=True;
if ValidateLanguageXML(tXML) then begin;
HeaderNode:= tXML.ChildNodes[RootNodeName].ChildNodes[HeadNodeName];
Result.Name:= HeaderNode.ChildNodes['Name'].Text;
Result.ShortName:= HeaderNode.ChildValues['SName'];
Result.Author:= HeaderNode.ChildNodes['Author'].Text;
Result.Date:= HeaderNode.ChildNodes['Date'].Text;
Result.Version:= HeaderNode.ChildNodes['Version'].Text;
Result.FileName:= LocFileName;
end else FreeAndNil(Result);
tXML._Release;
end;
function TLocalization.SetLanguage(ByShortName: string): boolean;
var
Lang: TLanguage;
begin
Result:= False;
for Lang in fLanguages do
if Lang.ShortName = ByShortName then
Result:= SetLanguage(Languages.IndexOf(Lang));
end;
function TLocalization.SetLanguage(ByIndex: integer): boolean;
begin
Result:= (ByIndex < FLanguages.Count);
if Result then begin
FCurLanguage:= FLanguages[ByIndex];
ApplyLanguage;
end;
end;
procedure TLocalization.ApplyLanguage;
begin
//if Languages.IndexOf(FCurLanguage) = 0 then Exit;
LocXML.LoadFromFile(FCurLanguage.FileName);
RootNode:= LocXML.ChildNodes[RootNodeName];
HeadNode:= LocXML.ChildNodes[RootNodeName].ChildNodes[HeadNodeName];
FormsNode:= LocXML.ChildNodes[RootNodeName].ChildNodes[FormsNodeName];
StringsNode:= LocXML.ChildNodes[RootNodeName].ChildNodes[StringsNodeName];
end;
function TLocalization.ValidateLanguageXML(XML: IXMLDocument): boolean;
begin;
Result:=True;
//Result:= (XML.Node.NodeName = RootNodeName);
//Result:= Result and (XML.ChildNodes[RootNodeName].ChildNodes.First.NodeName = HeaderNodeName);
//
end;
function TLocalization.Strings(StringId: string; Default: string): string;
begin
if (StringsNode.ChildNodes.FindNode(StringId) = nil)
then Result:=Default
else Result:= StringReplace(StringsNode.ChildValues[StringId], '|', sLineBreak, [rfReplaceAll] );
end;
function TLocalization.FindLanguage(lngShortName: string): integer;
var
tempLng: TLanguage;
begin
Result:=-1;
for tempLng in FLanguages do begin
if tempLng.ShortName = lngShortName then
Result:= FLanguages.IndexOf(tempLng);
end;
end;
procedure TLocalization.TranslateForm(Form: TForm);
var
i: integer;
Com: TComponent;
begin
if HaveTranslation(Form.Name, SelfCaptionName) then
Form.Caption:= GetTranslation(Form.Name, SelfCaptionName);
for i := 0 to Form.ComponentCount - 1 do begin
Com:= Form.Components[i];
if (Com is TMenuItem) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TMenuItem).Caption:= GetTranslation(Form.Name, Com.Name);
if (Com is TCheckBox) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TCheckBox).Caption:= GetTranslation(Form.Name, Com.Name);
if (Com is TLabel) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TLabel).Caption:= StringReplace(GetTranslation(Form.Name, Com.Name), '|', sLineBreak, [rfReplaceAll]);
if (Com is TEdit) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TEdit).Text:= GetTranslation(Form.Name, Com.Name);
if (Com is TButtonedEdit) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TButtonedEdit).Text:= GetTranslation(Form.Name, Com.Name);
if (Com is TTabSheet) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TTabSheet).Caption:= GetTranslation(Form.Name, Com.Name);
if (Com is TStaticText) then
if HaveTranslation(Form.Name, Com.Name) then
(Com as TStaticText).Caption:= GetTranslation(Form.Name, Com.Name);
if (Com is TSpeedButton) then begin
if HaveTranslation(Form.Name, Com.Name) then
(Com as TSpeedButton).Caption:= GetTranslation(Form.Name, Com.Name);
if HaveTranslation(Form.Name, Com.Name + HintSuffix) then
(Com as TSpeedButton).Hint:= GetTranslation(Form.Name, Com.Name + HintSuffix);
end;
if (Com is TButton) then begin
if HaveTranslation(Form.Name, Com.Name) then
(Com as TButton).Caption:= GetTranslation(Form.Name, Com.Name);
if HaveTranslation(Form.Name, Com.Name + HintSuffix) then
(Com as TButton).Hint:= GetTranslation(Form.Name, Com.Name + HintSuffix);
end;
end;
end;
function TLocalization.HaveTranslation(FormName: String; ComponentName: String): Boolean;
begin
Result:= (FormsNode.ChildNodes.FindNode(FormName) <> nil) and
(FormsNode.ChildNodes[FormName].ChildNodes.FindNode(ComponentName) <> nil);
end;
function TLocalization.GetTranslation(FormName: String; ComponentName: String): String;
begin
Result:=VarToStr(FormsNode.ChildNodes[FormName].ChildValues[ComponentName]);
end;
end.
|
unit QlpBits;
{$I ..\Include\QRCodeGenLib.inc}
interface
type
TBits = class sealed(TObject)
public
/// <summary>
/// Calculates Arithmetic shift right.
/// </summary>
/// <param name="AValue">Int32 value to compute 'Asr' on.</param>
/// <param name="AShiftBits">Byte, number of bits to shift value to.</param>
/// <returns>Shifted value.</returns>
/// <remarks>
/// Emulated Implementation was gotten from FreePascal sources
/// </remarks>
class function Asr32(AValue: Int32; AShiftBits: Byte): Int32;
static; inline;
/// <summary>
/// Calculates Left Shift. This was implemented to circumvent an *issue*
/// in FPC ARM when performing Shift Left with <b>AShiftBits > 32 .</b><br />
/// </summary>
/// <param name="AValue">
/// Int32 value to compute 'LS' on.
/// </param>
/// <param name="AShiftBits">
/// Int32, number of bits to shift value to.
/// </param>
/// <returns>
/// Shifted value.
/// </returns>
class function LeftShift32(AValue: Int32; AShiftBits: Int32): Int32;
static; inline;
/// <summary>
/// Calculates Negative Left Shift. This was implemented to circumvent an
/// *issue* in FPC ARM when performing Shift Left on certain values with a
/// Negative Shift Bits. In some C Compilers, such operations are
/// "Undefined"
/// </summary>
/// <param name="AValue">
/// Int32 value to compute 'NLS' on.
/// </param>
/// <param name="AShiftBits">
/// Int32, number of bits to shift value to. This Number Must be Negative
/// </param>
/// <returns>
/// Shifted value.
/// </returns>
class function NegativeLeftShift32(AValue: Int32; AShiftBits: Int32): Int32;
static; inline;
end;
implementation
{ TBits }
class function TBits.Asr32(AValue: Int32; AShiftBits: Byte): Int32;
begin
{$IF DEFINED(FPC) AND (NOT DEFINED(CPUARM))}
Result := SarLongInt(AValue, AShiftBits);
{$ELSE}
Result := Int32(UInt32(UInt32(UInt32(AValue) shr (AShiftBits and 31)) or
(UInt32(Int32(UInt32(0 - UInt32(UInt32(AValue) shr 31)) and
UInt32(Int32(0 - (Ord((AShiftBits and 31) <> 0) { and 1 } )))))
shl (32 - (AShiftBits and 31)))));
{$IFEND}
end;
class function TBits.LeftShift32(AValue, AShiftBits: Int32): Int32;
begin
Result := AValue shl (AShiftBits and 31);
end;
class function TBits.NegativeLeftShift32(AValue, AShiftBits: Int32): Int32;
begin
{$IFDEF DEBUG}
System.Assert(AShiftBits < 0);
{$ENDIF DEBUG}
Result := AValue shl ((32 + AShiftBits) and 31);
end;
end.
|
unit fNetwork;
interface
uses SysUtils, ActiveX, ComObj, Variants;
function GetWin32_NetworkAdapterMACList: string;
implementation
function GetWin32_NetworkAdapterMACList: string;
const
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
s: string;
begin;
Result := '';
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM Win32_NetworkAdapterConfiguration','WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
while oEnum.Next(1, FWbemObject, iValue) = 0 do begin
if VarIsStr(FWbemObject.MACAddress) then
Result := Result + String(FWbemObject.MACAddress) + '|';
FWbemObject:=Unassigned;
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
// ****************************************************************************
// * Project : FWZip
// * Unit Name : FWZipModifier
// * Purpose : Класс для модификации созданного ранее ZIP архива
// * Author : Александр (Rouse_) Багель
// * Copyright : © Fangorn Wizards Lab 1998 - 2023.
// * Version : 2.0.1
// * Home Page : http://rouse.drkb.ru
// * Home Blog : http://alexander-bagel.blogspot.ru
// ****************************************************************************
// * Stable Release : http://rouse.drkb.ru/components.php#fwzip
// * Latest Source : https://github.com/AlexanderBagel/FWZip
// ****************************************************************************
//
// Используемые источники:
// ftp://ftp.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
// https://zlib.net/zlib-1.2.13.tar.gz
// http://www.base2ti.com/
//
unit FWZipModifier;
{$IFDEF FPC}
{$MODE Delphi}
{$H+}
{$ENDIF}
interface
uses
Classes,
SysUtils,
FWZipConsts,
FWZipReader,
FWZipWriter,
FWZipStream,
FWZipZLib;
type
TReaderIndex = Integer;
TFWZipModifierItem = class(TFWZipWriterItem)
private
FReaderIndex: TReaderIndex; // индекс TFWZipReader в массиве TFWZipModifier.FReaderList
FOriginalItemIndex: Integer; // оригинальный индекс элемента в изначальном архиве
protected
property ReaderIndex: TReaderIndex read FReaderIndex write FReaderIndex;
property OriginalItemIndex: Integer read FOriginalItemIndex write FOriginalItemIndex;
public
constructor Create(Owner: TFWZipWriter;
const InitFilePath: string;
InitAttributes: TFileAttributeData;
const InitFileName: string = ''); override;
end;
EFWZipModifier = class(Exception);
// Данная структура хранит все блоки ExData из подключаемых архивов
TExDataRecord = record
Index: Integer;
Tag: Word;
Stream: TMemoryStream;
end;
TExDataRecords = array of TExDataRecord;
// структура для хранения подключенного архива и его блоков ExData
TReaderOwnership = (roReference, roOwned);
TReaderData = record
Reader: TFWZipReader;
ExDataRecords: TExDataRecords;
Ownership: TReaderOwnership;
end;
TReaderList = array of TReaderData;
TFWZipModifier = class(TFWZipWriter)
private
FReaderList: TReaderList;
function CheckZipFileIndex(Value: TReaderIndex): TReaderIndex;
function AddItemFromZip(AReader: TFWZipReader;
ReaderIndex: TReaderIndex; ItemIndex: Integer): Integer;
function GetReader(Index: Integer): TFWZipReader;
protected
function GetItemClass: TFWZipWriterItemClass; override;
procedure FillItemCDFHeader(CurrentItem: TFWZipWriterItem;
var Value: TCentralDirectoryFileHeaderEx); override;
procedure CompressItem(CurrentItem: TFWZipWriterItem;
Index: Integer; StreamSizeBeforeCompress: Int64; Stream: TStream); override;
procedure FillExData(Stream: TStream; Index: Integer); override;
procedure OnLoadExData(Sender: TObject; ItemIndex: Integer;
Tag: Word; Data: TStream);
public
destructor Destroy; override;
function AddZipFile(const AReader: TFWZipReader;
AOwnership: TReaderOwnership = roReference): TReaderIndex; overload;
function AddZipFile(const FilePath: string; SFXOffset: Integer = -1;
ZipEndOffset: Integer = -1): TReaderIndex; overload;
function AddZipFile(FileStream: TStream; SFXOffset: Integer = -1;
ZipEndOffset: Integer = -1): TReaderIndex; overload;
function AddFromZip(ReaderIndex: TReaderIndex): Integer; overload;
function AddFromZip(ReaderIndex: TReaderIndex; const ItemPath: string): Integer; overload;
function AddFromZip(ReaderIndex: TReaderIndex; ItemsList: TStringList): Integer; overload;
function ReadersCount: Integer;
property Reader[Index: Integer]: TFWZipReader read GetReader;
end;
implementation
type
TFWZipReaderFriendly = class(TFWZipReader);
TFWZipReaderItemFriendly = class(TFWZipReaderItem);
{ TFWZipModifierItem }
//
// В конструкторе производим первичную инициализацию полей
// Сами поля ReaderIndex и OriginalItemIndex будут инициализироваться только
// при добавлении их посредством класса TFWZipModifier
// =============================================================================
constructor TFWZipModifierItem.Create(Owner: TFWZipWriter;
const InitFilePath: string; InitAttributes: TFileAttributeData;
const InitFileName: string);
begin
inherited Create(Owner, InitFilePath, InitAttributes, InitFileName);
FReaderIndex := -1;
FOriginalItemIndex := -1;
end;
{ TFWZipModifier }
//
// Функция переносит элемент в финальный архив из ранее добавленного архива.
// В качестве результата возвращает индекс элемента в списке.
// Параметры:
// ReaderIndex - индекс ранее добавленно функцией AddZipFile архива
// ItemPath - имя элемента, которое требуется добавить
// =============================================================================
function TFWZipModifier.AddFromZip(ReaderIndex: TReaderIndex;
const ItemPath: string): Integer;
var
Reader: TFWZipReader;
begin
CheckZipFileIndex(ReaderIndex);
Reader := FReaderList[ReaderIndex].Reader;
Result :=
AddItemFromZip(Reader, ReaderIndex, Reader.GetElementIndex(ItemPath));
end;
//
// Функция переносит все элементы из ранее добавленного архива в финальный архив.
// В качестве результата возвращает количество успешно добавленных элементов.
// Параметры:
// ReaderIndex - индекс ранее добавленно функцией AddZipFile архива
// =============================================================================
function TFWZipModifier.AddFromZip(ReaderIndex: TReaderIndex): Integer;
var
I: Integer;
Reader: TFWZipReader;
begin
CheckZipFileIndex(ReaderIndex);
Result := 0;
Reader := FReaderList[ReaderIndex].Reader;
for I := 0 to Reader.Count - 1 do
if AddItemFromZip(Reader, ReaderIndex, I) >= 0 then
Inc(Result);
end;
//
// Функция переносит все элементы из ранее добавленного архива
// по списку в финальный архив.
// В качестве результата возвращает количество успешно добавленных элементов.
// Параметры:
// ReaderIndex - индекс ранее добавленно функцией AddZipFile архива
// ItemsList - список элементов к добавлению
// =============================================================================
function TFWZipModifier.AddFromZip(ReaderIndex: TReaderIndex;
ItemsList: TStringList): Integer;
var
I: Integer;
Reader: TFWZipReader;
begin
CheckZipFileIndex(ReaderIndex);
Result := 0;
Reader := FReaderList[ReaderIndex].Reader;
for I := 0 to ItemsList.Count - 1 do
if AddItemFromZip(Reader, ReaderIndex,
Reader.GetElementIndex(ItemsList[I])) >= 0 then
Inc(Result);
end;
//
// Функция переносит элемент в финальный архив из ранее добавленного архива.
// В качестве результата возвращает индекс элемента в списке.
// =============================================================================
function TFWZipModifier.AddItemFromZip(AReader: TFWZipReader;
ReaderIndex: TReaderIndex; ItemIndex: Integer): Integer;
var
OldItem: TFWZipReaderItemFriendly;
NewItem: TFWZipModifierItem;
begin
Result := -1;
if ItemIndex < 0 then Exit;
// Получаем указатель на элемент из уже существующего архива
OldItem := TFWZipReaderItemFriendly(AReader.Item[ItemIndex]);
// создаем новый элемент, который будем добавлять к новому архиву
NewItem := TFWZipModifierItem(
GetItemClass.Create(Self, '', OldItem.Attributes, OldItem.FileName));
// переключаем его в режим получения данных вручную
NewItem.UseExternalData := True;
// инициализируем ему индексы, дабы потом понять, откуда брать о нем данные
NewItem.ReaderIndex := ReaderIndex;
NewItem.OriginalItemIndex := ItemIndex;
// инициализируем внешние и рассчитываемые поля
NewItem.Comment := OldItem.Comment;
NewItem.NeedDescriptor :=
OldItem.CentralDirFileHeader.GeneralPurposeBitFlag and PBF_DESCRIPTOR <> 0;
NewItem.UseUTF8String :=
OldItem.CentralDirFileHeader.GeneralPurposeBitFlag and PBF_UTF8 <> 0;
// добавляем
Result := AddNewItem(NewItem);
end;
//
// Функция добавляет новый архив из которого можно брать готовые данные.
// В качестве результата возвращает индекс архива в списке добавленных.
// Параметры:
// FileStream - поток с данными архива
// SFXOffset и ZipEndOffset - его границы
// =============================================================================
function TFWZipModifier.AddZipFile(FileStream: TStream; SFXOffset,
ZipEndOffset: Integer): TReaderIndex;
var
AReader: TFWZipReader;
begin
AReader := TFWZipReader.Create;
Result := AddZipFile(AReader, roOwned);
AReader.OnLoadExData := OnLoadExData;
AReader.LoadFromStream(FileStream, SFXOffset, ZipEndOffset);
end;
//
// Функция добавляет новный ридер в список доступных
// Загрузка данных не производится, поэтому данный вариант добавления
// ридера не позволит работать с блоком ExData если таковой присутствует.
// =============================================================================
function TFWZipModifier.AddZipFile(const AReader: TFWZipReader;
AOwnership: TReaderOwnership): TReaderIndex;
begin
Result := Length(FReaderList);
SetLength(FReaderList, Result + 1);
FReaderList[Result].Reader := AReader;
FReaderList[Result].Ownership := AOwnership;
end;
//
// Функция добавляет новый архив из которого можно брать готовые данные.
// В качестве результата возвращает индекс архива в списке добавленных.
// Параметры:
// FilePath - путь к добавляемому архиву
// SFXOffset и ZipEndOffset - его границы
// =============================================================================
function TFWZipModifier.AddZipFile(const FilePath: string;
SFXOffset, ZipEndOffset: Integer): TReaderIndex;
var
AReader: TFWZipReader;
begin
AReader := TFWZipReader.Create;
Result := AddZipFile(AReader, roOwned);
AReader.OnLoadExData := OnLoadExData;
AReader.LoadFromFile(FilePath, SFXOffset, ZipEndOffset);
end;
//
// Функция проверяет правильность переданного индекса архива в списке
// =============================================================================
function TFWZipModifier.CheckZipFileIndex(Value: TReaderIndex): TReaderIndex;
begin
Result := Value;
if (Value < 0) or (Value >= Length(FReaderList)) then
raise EFWZipModifier.CreateFmt('Invalid index value (%d).', [Value]);
end;
//
// Процедура перекрывает сжатие данных эелемента
// и берет эти данные из ранее сформированного архива.
// =============================================================================
procedure TFWZipModifier.CompressItem(CurrentItem: TFWZipWriterItem;
Index: Integer; StreamSizeBeforeCompress: Int64; Stream: TStream);
var
OldItem: TFWZipReaderItemFriendly;
NewItem: TFWZipModifierItem;
Reader: TFWZipReaderFriendly;
Offset: Int64;
begin
NewItem := TFWZipModifierItem(CurrentItem);
// проверка, работаем ли мы с элементом, данные которого заполняются вручную?
if not NewItem.UseExternalData then
begin
inherited;
Exit;
end;
// получаем указатель на класс, который держит добавленный ранее архив
Reader := TFWZipReaderFriendly(FReaderList[NewItem.ReaderIndex].Reader);
// получаем указатель на оригинальный элемент архива
OldItem := TFWZipReaderItemFriendly(Reader.Item[NewItem.OriginalItemIndex]);
// рассчитываем его позицию в архиве
if IsMultiPartZip(Reader.ZIPStream) then
begin
TFWAbstractMultiStream(Reader.ZIPStream).Seek(
OldItem.CentralDirFileHeader.DiskNumberStart,
OldItem.CentralDirFileHeader.RelativeOffsetOfLocalHeader);
Offset := Reader.ZIPStream.Position;
end
else
Offset := OldItem.CentralDirFileHeader.RelativeOffsetOfLocalHeader;
Inc(Offset, SizeOf(TLocalFileHeader));
Inc(Offset, OldItem.CentralDirFileHeader.FilenameLength);
if OldItem.CentralDirFileHeaderEx.UncompressedSize >= MAXDWORD then
Inc(Offset, SizeOf(TExDataInfo64));
Reader.ZIPStream.Position := Offset;
// копируем данные как есть, без перепаковки
Stream.CopyFrom(Reader.ZIPStream, OldItem.CentralDirFileHeaderEx.CompressedSize);
end;
//
// Modifier слегка не оптимально расходует память, поэтому подчищаем.
// =============================================================================
destructor TFWZipModifier.Destroy;
var
I, A: Integer;
begin
for I := 0 to Length(FReaderList) - 1 do
begin
if FReaderList[I].Ownership = roOwned then
FReaderList[I].Reader.Free;
for A := 0 to Length(FReaderList[I].ExDataRecords) - 1 do
FReaderList[I].ExDataRecords[A].Stream.Free;
end;
inherited;
end;
//
// Процедура перекрывает заполнение блоков ExData
// и берет эти данные из ранее сформированного архива.
// =============================================================================
procedure TFWZipModifier.FillExData(Stream: TStream; Index: Integer);
var
NewItem: TFWZipModifierItem;
ReaderIndex: TReaderIndex;
I: Integer;
{%H-}ExDataSize: Word;
ExDataRecord: TExDataRecord;
begin
NewItem := TFWZipModifierItem(Item[Index]);
// проверка, работаем ли мы с элементом, данные которого заполняются вручную?
if not NewItem.UseExternalData then
begin
inherited;
Exit;
end;
// проверяем привязку к архиву, с елементов которого мы будем добавлять блоки ExData
ReaderIndex := CheckZipFileIndex(NewItem.ReaderIndex);
for I := 0 to Length(FReaderList[ReaderIndex].ExDataRecords) - 1 do
if FReaderList[ReaderIndex].ExDataRecords[I].Index = NewItem.OriginalItemIndex then
begin
// блоков может быть несколько, поэтому добавляем их все
ExDataRecord := FReaderList[ReaderIndex].ExDataRecords[I];
Stream.WriteBuffer(ExDataRecord.Tag, 2);
ExDataSize := ExDataRecord.Stream.Size;
Stream.WriteBuffer(ExDataSize, 2);
Stream.CopyFrom(ExDataRecord.Stream, 0);
end;
end;
//
// Процедура перекрывает заполнение структуры TCentralDirectoryFileHeaderEx
// и берет эти данные из ранее сформированного архива.
// =============================================================================
procedure TFWZipModifier.FillItemCDFHeader(CurrentItem: TFWZipWriterItem;
var Value: TCentralDirectoryFileHeaderEx);
var
OldItem: TFWZipReaderItemFriendly;
NewItem: TFWZipModifierItem;
Reader: TFWZipReader;
begin
NewItem := TFWZipModifierItem(CurrentItem);
// проверка, работаем ли мы с элементом, данные которого заполняются вручную?
if not NewItem.UseExternalData then
begin
inherited;
Exit;
end;
Reader := FReaderList[NewItem.ReaderIndex].Reader;
OldItem := TFWZipReaderItemFriendly(Reader.Item[NewItem.OriginalItemIndex]);
// полностью перезаписываем все данные структуры
// исключением является поле RelativeOffsetOfLocalHeader
// но оно реинициализируется после вызова данного метода
Value := OldItem.CentralDirFileHeaderEx;
end;
//
// Расширяем коллекцию
// =============================================================================
function TFWZipModifier.GetItemClass: TFWZipWriterItemClass;
begin
Result := TFWZipModifierItem;
end;
//
// Возвращаем сылку на внутренний ридер
// =============================================================================
function TFWZipModifier.GetReader(Index: Integer): TFWZipReader;
begin
if (Index < 0) or (Index >= ReadersCount) then
raise EFWZipModifier.CreateFmt('Invalid reader index value (%d).', [Index]);
Result := FReaderList[Index].Reader;
end;
//
// Задача процедуры собрать все ExData в локальное хранилище,
// чтобы их можно было присоединить к структуре архива на этапе ребилда
// =============================================================================
procedure TFWZipModifier.OnLoadExData(Sender: TObject; ItemIndex: Integer;
Tag: Word; Data: TStream);
var
Index, ExDataCount: Integer;
ExData: TExDataRecord;
begin
Index := ReadersCount - 1;
if Index >= 0 then
begin
ExData.Index := ItemIndex;
ExData.Tag := Tag;
ExData.Stream := TMemoryStream.Create;
ExData.Stream.CopyFrom(Data, 0);
ExDataCount := Length(FReaderList[Index].ExDataRecords);
SetLength(FReaderList[Index].ExDataRecords, ExDataCount + 1);
FReaderList[Index].ExDataRecords[ExDataCount] := ExData;
end;
end;
//
// Возвращаем количество доступных ридеров
// =============================================================================
function TFWZipModifier.ReadersCount: Integer;
begin
Result := Length(FReaderList);
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.ServiceTypes;
interface
{$SCOPEDENUMS ON}
uses System.Generics.Collections, System.Classes, System.JSON,
REST.Backend.Providers, REST.Backend.MetaTypes, REST.Client, REST.Json, REST.Json.Types;
type
// Forward declaration of "TBackendObjectList__1" template
{$HPPEMIT OPENNAMESPACE}
{$HPPEMIT 'template<typename T> class DELPHICLASS TBackendObjectList__1;'}
{$HPPEMIT CLOSENAMESPACE}
IBackendGetMetaFactory = interface(IBackendService)
['{65BB9847-DF2D-4888-8B2F-36EDE51FE20A}']
function GetMetaFactory: IBackendMetaFactory;
end;
IBackendQueryApi = interface;
IBackendQueryService = interface(IBackendService)
['{3A22E6DA-7139-4163-B981-DEED365D92B3}']
function GetQueryAPI: IBackendQueryApi;
function CreateQueryApi: IBackendQueryApi;
property QueryAPI: IBackendQueryApi read GetQueryAPI;
end;
TBackendObjectList<T: class, constructor> = class;
TBackendQueryServiceNames = record
const
Storage = 'Storage';
Users = 'Users';
Installations = 'Installations';
Groups = 'Groups';
Modules = 'Edgemodules';
ModulesResources = 'Edgeresources';
Files = 'Files';
end;
// Implemented by a service
IBackendQueryApi = interface(IBackendGetMetaFactory)
['{1F54E3F6-693D-4A25-AC00-7CFFC99D6632}']
procedure Query(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray); overload;
procedure Query(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray; out AObjects: TArray<TBackendEntityValue>); overload;
procedure GetServiceNames(out ANames: TArray<string>);
end;
IBackendAuthenticationApi = interface;
TBackendAuthenticationApi = class
private
function GetAuthentication: TBackendAuthentication;
function GetDefaultAuthentication: TBackendDefaultAuthentication;
procedure SetAuthentication(const Value: TBackendAuthentication);
procedure SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
protected
function GetAuthenticationApi: IBackendAuthenticationApi; virtual; abstract;
public
procedure Login(const ALogin: TBackendEntityValue);
procedure Logout;
property Authentication: TBackendAuthentication read GetAuthentication write SetAuthentication;
property DefaultAuthentication: TBackendDefaultAuthentication read GetDefaultAuthentication write SetDefaultAuthentication;
property AuthenticationApi: IBackendAuthenticationApi read GetAuthenticationApi;
end;
// Wrapper
TBackendQueryApi = class(TBackendAuthenticationApi)
private
FServiceApi: IBackendQueryApi;
FService: IBackendQueryService;
function GetServiceAPI: IBackendQueryApi;
function CreateMetaDataType(const ADataType,
AClassName: string): TBackendMetaClass;
procedure Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>); overload;
procedure Query<T: class, constructor>(const ADataType: TBackendMetaClass;
const AQuery: array of string; const AResultList: TBackendObjectList<T>); overload;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AApi: IBackendQueryApi); overload;
constructor Create(const AService: IBackendQueryService); overload;
procedure GetServiceNames(out ANames: TArray<string>);
procedure Query(const ADataType, ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure Query(const ADataType, ABackendClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>); overload;
procedure Query<T: class, constructor>(const ADataType, ABackendClassName: string; const AQuery: array of string; const AResultList: TBackendObjectList<T>); overload;
property ProviderAPI: IBackendQueryApi read GetServiceAPI;
end;
IBackendStorageApi = interface;
IBackendStorageApi2 = interface;
IBackendStorageService = interface(IBackendService)
['{0B60B443-8D7F-4984-8DEA-B7057AD9ED7F}']
function GetStorageApi: IBackendStorageApi;
function CreateStorageApi: IBackendStorageApi;
property StorageAPI: IBackendStorageApi read GetStorageAPI;
end;
TFindObjectProc = reference to procedure(const AObject: TBackendEntityValue; const AJSON: TJSONObject);
TFindObjectProc<T: class> = reference to procedure(const AMetaObject: TBackendEntityValue; const AObject: T);
// Implemented by a service
IBackendStorageApi = interface(IBackendGetMetaFactory)
['{F4CBE0D9-5AAD-49EE-9D2E-3178E5DF2425}']
function GetMetaFactory: IBackendMetaFactory;
procedure CreateObject(const AClass: TBackendMetaClass; const AACL, AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteObject(const AObject: TBackendEntityValue): Boolean; overload;
function FindObject(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean;
procedure UpdateObject(const AObject: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue);
procedure QueryObjects(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray); overload;
procedure QueryObjects(const AClass: TBackendMetaClass; const AQuery: array of string;
const AJSONArray: TJSONArray; out AObjects: TArray<TBackendEntityValue>); overload;
end;
/// <summary>Extends IBackendStorageApi to provide custom Date Format objects</summary>
IBackendStorageApi2 = interface(IBackendGetMetaFactory)
['{912DE1A0-75D5-4F79-852C-160976C6A765}']
function GetJsonDateFormat : TJsonDateFormat;
end;
// Wrapper
TBackendStorageApi = class(TBackendAuthenticationApi)
private
FService: IBackendStorageService;
FServiceApi: IBackendStorageApi;
function CreateMetaClass(const AClassName: string): TBackendMetaClass;
function CreateMetaClassObject(const AClassName,
AObjectID: string): TBackendEntityValue;
procedure CreateObject(const AClass: TBackendMetaClass; const AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
procedure CreateObject(const AClass: TBackendMetaClass; const AACL, AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
procedure CreateObject<T: class, constructor>(const AClass: TBackendMetaClass; const AObject: T;
out ACreatedObject: TBackendEntityValue); overload;
function GetServiceAPI: IBackendStorageApi;
procedure QueryObjects<T: class, constructor>(const AClass: TBackendMetaClass;
const AQuery: array of string; const AResultList: TBackendObjectList<T>); overload;
procedure QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>); overload;
procedure QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray); overload;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AApi: IBackendStorageApi); overload;
constructor Create(const AService: IBackendStorageService); overload;
// JSON
procedure CreateObject(const AClassName: string; const AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
procedure CreateObject(const AClassName: string; const AACL, AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteObject(const AClassName, AObjectID: string): Boolean; overload;
function DeleteObject(const AObject: TBackendEntityValue): Boolean; overload;
function FindObject(const AMetaObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindObject(const AClassName, AObjectID: string; AProc: TFindObjectProc): Boolean; overload;
procedure QueryObjects(const AClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryObjects(const AClassName: string; const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>); overload;
procedure UpdateObject(const AObject: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue); overload;
procedure UpdateObject(const AClassName, AObjectID: string; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue); overload;
// <T: class>
procedure CreateObject<T: class, constructor>(const AClassName: string; const AObject: T;
out ACreatedObject: TBackendEntityValue); overload;
procedure CreateObject<T: class, constructor>(const AClassName: string; const AObject: T); overload;
function FindObject<T: class, constructor>(const AMetaObject: TBackendEntityValue; AProc: TFindObjectProc<T>): Boolean; overload;
procedure UpdateObject<T: class, constructor>(const AMetaObject: TBackendEntityValue; const AObject: T;
out AUpdatedObject: TBackendEntityValue); overload;
procedure QueryObjects<T: class, constructor>(const AClassName: string; const AQuery: array of string; const AResultList: TBackendObjectList<T>); overload;
/// <summary>Add date format to options set used in Json processing </summary>
function AddDateOption(ADateFormat: TJSONDateFormat; AOptions: TJSONOptions): TJSONOptions;
property ProviderAPI: IBackendStorageApi read GetServiceAPI;
end;
IBackendAuthenticationApi = interface
['{4C0D2ADD-B6B7-40ED-B6B5-5DB66B7ECE9D}']
procedure Login(const ALogin: TBackendEntityValue);
procedure Logout;
procedure SetDefaultAuthentication(ADefaultAuthentication: TBackendDefaultAuthentication);
function GetDefaultAuthentication: TBackendDefaultAuthentication;
procedure SetAuthentication(AAuthentication: TBackendAuthentication);
function GetAuthentication: TBackendAuthentication;
property Authentication: TBackendAuthentication read GetAuthentication write SetAuthentication;
property DefaultAuthentication: TBackendDefaultAuthentication read GetDefaultAuthentication write SetDefaultAuthentication;
end;
IBackendAuthApi = interface;
IBackendAuthService = interface(IBackendService)
['{DB06E5A1-7261-44A3-9C3E-9805744D53C9}']
function GetAuthAPI: IBackendAuthApi;
function CreateAuthApi: IBackendAuthApi;
property AuthAPI: IBackendAuthApi read GetAuthAPI;
end;
// Implemented by a service
IBackendAuthApi = interface(IBackendGetMetaFactory)
['{568A911A-B61B-45AA-8BD4-CFCAC0598CF6}']
procedure SignupUser(const AUserName, APassword: string; const AUserData: TJSONObject;
out ACreatedObject: TBackendEntityValue);
procedure LoginUser(const AUserName, APassword: string; AProc: TFindObjectProc); overload;
procedure LoginUser(const AUserName, APassword: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray); overload;
function FindCurrentUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindCurrentUser(const AObject: TBackendEntityValue; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
procedure UpdateUser(const AObject: TBackendEntityValue; const AUserData: TJSONObject;
out AUpdatedObject: TBackendEntityValue);
end;
// Wrapper
TBackendAuthApi = class(TBackendAuthenticationApi)
private
FService: IBackendAuthService;
FServiceApi: IBackendAuthApi;
function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
function GetServiceAPI: IBackendAuthApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
function GetAuthApi: IBackendAuthApi; virtual;
public
constructor Create(const AApi: IBackendAuthApi); overload;
constructor Create(const AService: IBackendAuthService); overload;
procedure SignupUser(const AUserName, APassword: string; const AUserData: TJSONObject;
out ACreatedObject: TBackendEntityValue);
procedure LoginUser(const AUserName, APassword: string; AProc: TFindObjectProc); overload;
procedure LoginUser(const AUserName, APassword: string; out ALogin: TBackendEntityValue; const AJSON: TJSONArray=nil); overload;
function FindCurrentUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean;
procedure UpdateUser(const AObject: TBackendEntityValue; const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue); overload;
property ProviderAPI: IBackendAuthApi read GetServiceAPI;
end;
TBackendAuthApiHelper = class helper for TBackendAuthApi
public
procedure LogoutUser;
end;
IBackendUsersApi = interface;
IBackendUsersService = interface(IBackendService)
['{B6A9B066-E6C0-4A01-B70B-5A5A19C816AF}']
function GetUsersAPI: IBackendUsersApi;
function CreateUsersApi: IBackendUsersApi;
property UsersAPI: IBackendUsersApi read GetUsersAPI;
end;
// Implemented by a service
IBackendUsersApi = interface(IBackendAuthApi)
['{FD6D169C-07E8-4738-9B9A-BB50E5D423FC}']
function DeleteUser(const AObject: TBackendEntityValue): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
function QueryUserName(const AUserName: string; AProc: TFindObjectProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean; overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>); overload;
end;
// Wrapper
TBackendUsersApi = class(TBackendAuthApi)
private
FService: IBackendUsersService;
FServiceApi: IBackendUsersApi;
function CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
function GetServiceAPI: IBackendUsersApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
function GetAuthApi: IBackendAuthApi; override;
public
constructor Create(const AApi: IBackendUsersApi); overload;
constructor Create(const AService: IBackendUsersService); overload;
function DeleteUser(const AObject: TBackendEntityValue): Boolean; overload;
function DeleteUser(const AObjectID: string): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindUser(const AObjectID: string; AProc: TFindObjectProc): Boolean; overload;
function FindUser(const AObject: TBackendEntityValue; out AUser: TBackendEntityValue; const AJSON: TJSONArray = nil): Boolean; overload;
function FindUser(const AObjectID: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray = nil): Boolean; overload;
procedure UpdateUser(const AObjectID: string; const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue); overload;
function QueryUserName(const AUserName: string; AProc: TFindObjectProc): Boolean; overload;
function QueryUserName(const AUserName: string; out AUser: TBackendEntityValue; const AJSON: TJSONArray = nil): Boolean; overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray); overload;
procedure QueryUsers(const AQuery: array of string; const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>); overload;
property ProviderAPI: IBackendUsersApi read GetServiceAPI;
end;
IBackendGroupsApi = interface;
IBackendGroupsService = interface(IBackendService)
['{D40C0565-5165-4280-9625-5593FB77FA36}']
function GetGroupsAPI: IBackendGroupsApi;
function CreateGroupsApi: IBackendGroupsApi;
property GroupsAPI: IBackendGroupsApi read GetGroupsAPI;
end;
// Implemented by a service
IBackendGroupsApi = interface(IBackendGetMetaFactory)
['{3FF2A6F6-490E-4896-B482-CD361A8C6705}']
procedure AddUsers(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue);
function RemoveUsers(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue): Boolean;
procedure CreateGroup(const AGroup: string; AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteGroup(const AObject: TBackendEntityValue): Boolean; overload;
function FindGroup(const AObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean;
procedure UpdateGroup(const AObject: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue);
end;
// Wrapper
TBackendGroupsApi = class(TBackendAuthenticationApi)
private
FService: IBackendGroupsService;
FServiceApi: IBackendGroupsApi;
function GetServiceAPI: IBackendGroupsApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
function CreateMetaGroupObject(const AGroupName: string): TBackendEntityValue;
constructor Create(const AApi: IBackendGroupsApi); overload;
constructor Create(const AService: IBackendGroupsService); overload;
procedure AddUsers(const AGroupName: string; const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue);
procedure AddUser(const AGroupName: string; const AUser: string; out AUpdatedObject: TBackendEntityValue);
function RemoveUser(const AGroupName, AUser: string; out AUpdatedObject: TBackendEntityValue): Boolean;
function RemoveUsers(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue): Boolean;
procedure CreateGroup(const AGroupName: string; const AJSON: TJSONObject;
out ACreatedObject: TBackendEntityValue); overload;
function DeleteGroup(const AGroupName: string): Boolean; overload;
function DeleteGroup(const AGroup: TBackendEntityValue): Boolean; overload;
function FindGroup(const AMetaObject: TBackendEntityValue; AProc: TFindObjectProc): Boolean; overload;
function FindGroup(const AGroupName: string; AProc: TFindObjectProc): Boolean; overload;
procedure UpdateGroup(const AGroup: TBackendEntityValue; const AJSONObject: TJSONObject;
out AUpdatedObject: TBackendEntityValue); overload;
property ProviderAPI: IBackendGroupsApi read GetServiceAPI;
end;
IBackendFilesApi = interface;
IBackendFilesService = interface(IBackendService)
['{A925E828-73A5-41C0-93A4-4E12BC7949FB}']
function GetFilesAPI: IBackendFilesApi;
function CreateFilesApi: IBackendFilesApi;
property FilesAPI: IBackendFilesApi read GetFilesAPI;
end;
// Files service must implement this
IBackendFilesApi = interface(IBackendGetMetaFactory)
['{271C2472-D957-47C5-BC10-F3A15FF5261C}']
procedure UploadFile(const AFileName: string; const AContentType: string; out AFile: TBackendEntityValue); overload;
procedure UploadFile(const AFileName: string; const AStream: TStream; const AContentType: string; out AFile: TBackendEntityValue); overload;
function DeleteFile(const AFile: TBackendEntityValue): Boolean; overload;
end;
// Files service wrapper
TBackendFilesApi = class(TBackendAuthenticationApi)
private
FService: IBackendFilesService;
FServiceApi: IBackendFilesApi;
function GetServiceAPI: IBackendFilesApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
function CreateMetaFileObject(const AFileID: string): TBackendEntityValue;
constructor Create(const AApi: IBackendFilesApi); overload;
constructor Create(const AService: IBackendFilesService); overload;
procedure UploadFile(const AFileName: string; const AContentType: string; out AFile: TBackendEntityValue); overload;
procedure UploadFile(const AFileName: string; const AStream: TStream; const AContentType: string; out AFile: TBackendEntityValue); overload;
function DeleteFile(const AFile: TBackendEntityValue): Boolean; overload;
function DeleteFile(const AFileID: string): Boolean; overload;
property ProviderAPI: IBackendFilesApi read GetServiceAPI;
end;
TBackendObjectList<T: class, constructor> = class
private type
TObjectPair = TPair<T, TBackendEntityValue>;
TObjectPairs = TArray<TObjectPair>;
TObjectList = TList<T>;
TObjectDictionary = TDictionary<T, TBackendEntityValue>;
public type
TEnumerator = class(TEnumerator<T>)
private
FList: TObjectList;
FIndex: Integer;
constructor Create(const AList: TObjectList);
protected
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
end;
private
FList: TObjectList;
FDictionary: TObjectDictionary;
function GetCount: Integer;
function GetItem(I: Integer): T;
procedure Clear;
function GetEntityValue(I: T): TBackendEntityValue;
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: TEnumerator<T>;
function Extract(const Value: T): T;
function ExtractArray: TArray<T>;
procedure Add(const AValue: T; const AMetaObject: TBackendEntityValue);
function IndexOf(I: T): Integer;
property Count: Integer read GetCount;
property Items[I: Integer]: T read GetItem; default;
property EntityValues[I: T]: TBackendEntityValue read GetEntityValue;
end;
IBackendCustomEndpointApi = interface;
IBackendCustomEndpointService = interface(IBackendService)
['{BF37269F-BBDE-4110-BAFA-A1CC725BC5D0}']
function GetCustomEndpointAPI: IBackendCustomEndpointApi;
function CreateCustomEndpointApi: IBackendCustomEndpointApi;
property CustomEndpointAPI: IBackendCustomEndpointApi read GetCustomEndpointAPI;
end;
// Implemented by a service
IBackendCustomEndpointApi = interface(IBackendService)
['{974BD7BB-C39C-4C75-8056-148026839A38}']
procedure PrepareClient(const AClient: TCustomRESTClient);
procedure PrepareRequest(const ARequest: TCustomRESTRequest);
procedure CheckForResponseErrors(const AResponse: TCustomRESTResponse; AValidStatusCodes: array of Integer);
end;
// Wrapper
TBackendCustomEndPointApi = class(TBackendAuthenticationApi)
private
FService: IBackendCustomEndpointService;
FServiceApi: IBackendCustomEndpointApi;
function GetServiceAPI: IBackendCustomEndpointApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AApi: IBackendCustomEndpointApi); overload;
constructor Create(const AService: IBackendCustomEndpointService); overload;
procedure PrepareClient(const AClient: TCustomRESTClient);
procedure PrepareRequest(const ARequest: TCustomRESTRequest);
procedure CheckForResponseErrors(const AResponse: TCustomRESTResponse; AValidStatusCodes: array of Integer);
property ProviderAPI: IBackendCustomEndpointApi read GetServiceAPI;
end;
TLogoutProc = reference to procedure(AServiceAPI: TObject);
procedure RegisterLogoutProc(const AServiceAPIClass: TClass; AProc: TLogoutProc);
procedure CallLogoutProc(const ABackendAuthApi: IBackendAuthApi);
implementation
uses System.SysUtils, REST.Backend.Consts, REST.Backend.Exception;
{ TBackendStorageApi }
function TBackendStorageApi.AddDateOption(ADateFormat: TJSONDateFormat; AOptions: TJSONOptions): TJSONOptions;
begin
case ADateFormat of
jdfISO8601 : Result := AOptions + [joDateFormatISO8601];
jdfUnix : Result := AOptions + [ joDateFormatUnix];
jdfMongo : Result := AOptions + [joDateFormatMongo];
jdfParse : Result := AOptions + [joDateFormatParse];
else
Assert(False);
Result := AOptions;
end;
end;
procedure TBackendStorageApi.CreateObject(const AClass: TBackendMetaClass;
const AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
begin
GetServiceApi.CreateObject(AClass, nil, AJSON, ACreatedObject);
end;
procedure TBackendStorageApi.CreateObject(const AClass: TBackendMetaClass;
const AACL, AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
begin
GetServiceApi.CreateObject(AClass, AACL, AJSON, ACreatedObject);
end;
procedure TBackendStorageApi.CreateObject<T>(const AClass: TBackendMetaClass;
const AObject: T; out ACreatedObject: TBackendEntityValue);
var
LJSON: TJSONObject;
LDateFormat: TJsonDateFormat;
LOptions: TJsonOptions;
LIntf: IBackendStorageAPI2;
begin
if Supports(GetServiceAPI, IBackendStorageAPI2, LIntf) then
LDateFormat := LIntf.GetJsonDateFormat
else
LDateFormat := jdfISO8601;
LOptions := AddDateOption(LDateFormat, [joIgnoreEmptyStrings, joIgnoreEmptyArrays]);
LJSON := TJSON.ObjectToJsonObject(AObject, LOptions);
try
CreateObject(AClass, LJSON, ACreatedObject);
finally
LJSON.Free;
end;
end;
procedure TBackendStorageApi.CreateObject(const AClassName: string;
const AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
var
LClass: TBackendMetaClass;
begin
LClass := CreateMetaClass(AClassName);
CreateObject(LClass, AJSON, ACreatedObject);
end;
procedure TBackendStorageApi.CreateObject(const AClassName: string;
const AACL, AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
var
LClass: TBackendMetaClass;
begin
LClass := CreateMetaClass(AClassName);
CreateObject(LClass, AACL, AJSON, ACreatedObject);
end;
procedure TBackendStorageApi.CreateObject<T>(const AClassName: string;
const AObject: T; out ACreatedObject: TBackendEntityValue);
var
LClass: TBackendMetaClass;
begin
LClass := CreateMetaClass(AClassName);
CreateObject<T>(LClass, AObject, ACreatedObject);
end;
procedure TBackendStorageApi.CreateObject<T>(const AClassName: string;
const AObject: T);
var
LCreatedObject: TBackendEntityValue;
begin
CreateObject<T>(AClassName, AObject, LCreatedObject);
end;
function TBackendStorageApi.DeleteObject(const AObject: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.DeleteObject(AObject);
end;
function TBackendStorageApi.DeleteObject(const AClassName,
AObjectID: string): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaClassObject(AClassName, AObjectID);
Result := DeleteObject(LObject);
end;
function TBackendStorageApi.FindObject(const AMetaObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
begin
Result := GetServiceAPI.FindObject(AMetaObject, AProc);
end;
function TBackendStorageApi.FindObject(const AClassName, AObjectID: string;
AProc: TFindObjectProc): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaClassObject(AClassName, AObjectID);
Result := FindObject(LObject, AProc);
end;
function TBackendStorageApi.FindObject<T>(const AMetaObject: TBackendEntityValue;
AProc: TFindObjectProc<T>): Boolean;
var
LJSON: TJSONObject;
LDateFormat: TJsonDateFormat;
LOptions: TJSONOptions;
LIntf: IBackendStorageAPI2;
begin
if Supports(GetServiceAPI, IBackendStorageAPI2, LIntf) then
LDateFormat := LIntf.GetJsonDateFormat
else
LDateFormat := jdfISO8601;
LOptions := AddDateOption(LDateFormat, []);
Result := GetServiceAPI.FindObject(AMetaObject,
procedure(const AInnerMetaObject: TBackendEntityValue; const AJSON: TJSONObject)
var
LObject: T;
begin
LObject := TJSON.JsonToObject<T>(AJSON, LOptions);
try
AProc(AInnerMetaObject, LObject);
finally
LObject.Free;
end;
end);
end;
function TBackendStorageApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendStorageApi.GetServiceAPI: IBackendStorageApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetStorageApi
end;
procedure TBackendStorageApi.QueryObjects(const AClassName: string;
const AQuery: array of string; const AJSONArray: TJSONArray);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaClass(AClassName);
QueryObjects(LMetaClass, AQuery, AJSONArray);
end;
procedure TBackendStorageApi.QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>);
begin
GetServiceApi.QueryObjects(AClass, AQuery, AJSONArray, AMetaArray);
end;
procedure TBackendStorageApi.QueryObjects(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
GetServiceApi.QueryObjects(AClass, AQuery, AJSONArray);
end;
procedure TBackendStorageApi.QueryObjects<T>(const AClass: TBackendMetaClass;
const AQuery: array of string; const AResultList: TBackendObjectList<T>);
var
LJSONArray: TJSONArray;
LJSONValue: TJSONValue;
LMetaArray: TArray<TBackendEntityValue>;
LObject: T;
LList: TList<T>;
I: Integer;
LDateFormat: TJsonDateFormat;
LOptions: TJSONOptions;
LIntf: IBackendStorageAPI2;
begin
if Supports(GetServiceAPI, IBackendStorageAPI2, LIntf) then
LDateFormat := LIntf.GetJsonDateFormat
else
LDateFormat := jdfISO8601;
LOptions := AddDateOption(LDateFormat, []);;
LJSONArray := TJSONArray.Create;
try
QueryObjects(AClass, AQuery, LJSONArray, LMetaArray);
I := 0;
try
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LObject := TJSON.JsonToObject<T>(TJSONObject(LJSONValue), LOptions);
AResultList.Add(LObject, LMetaArray[I]);
end
else
raise EBackendServiceError.Create(sJSONObjectExpected);
Inc(I);
end;
except
AResultList.Clear;
raise;
end;
finally
LJSONArray.Free;
end;
end;
procedure TBackendStorageApi.QueryObjects(const AClassName: string;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaClass(AClassName);
QueryObjects(LMetaClass, AQuery, AJSONArray, AMetaArray);
end;
procedure TBackendStorageApi.QueryObjects<T>(const AClassName: string;
const AQuery: array of string; const AResultList: TBackendObjectList<T>);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaClass(AClassName);
QueryObjects<T>(LMetaClass, AQuery, AResultList);
end;
procedure TBackendStorageApi.UpdateObject(const AObject: TBackendEntityValue;
const AJSONObject: TJSONObject; out AUpdatedObject: TBackendEntityValue);
begin
GetServiceAPI.UpdateObject(AObject, AJSONObject, AUpdatedObject);
end;
procedure TBackendStorageApi.UpdateObject(const AClassName, AObjectID: string;
const AJSONObject: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaClassObject(AClassName, AObjectID);
UpdateObject(LObject, AJSONObject, AUpdatedObject);
end;
procedure TBackendStorageApi.UpdateObject<T>(
const AMetaObject: TBackendEntityValue; const AObject: T;
out AUpdatedObject: TBackendEntityValue);
var
LJSON: TJSONObject;
LDateFormat: TJsonDateFormat;
LOptions: TJSONOptions;
LIntf: IBackendStorageAPI2;
begin
if Supports(GetServiceAPI, IBackendStorageAPI2, LIntf) then
LDateFormat := LIntf.GetJsonDateFormat
else
LDateFormat := jdfISO8601;
LOptions := AddDateOption(LDateFormat, [joIgnoreEmptyStrings, joIgnoreEmptyArrays]);
LJSON := TJSON.ObjectToJsonObject(AObject, LOptions);
try
UpdateObject(AMetaObject, LJSON, AUpdatedObject);
finally
LJSON.Free;
end;
end;
constructor TBackendStorageApi.Create(const AApi: IBackendStorageApi);
begin
FServiceApi := AApi;
//FHelper := TBackendQueryObjectsHelper.Create(AApi);
end;
constructor TBackendStorageApi.Create(const AService: IBackendStorageService);
begin
FService := AService;
end;
function TBackendStorageApi.CreateMetaClass(const AClassName: string): TBackendMetaClass;
var
LFactory: IBackendMetaClassFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaClassFactory, LFactory) then
Result := LFactory.CreateMetaClass(AClassName)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
function TBackendStorageApi.CreateMetaClassObject(const AClassName, AObjectID: string): TBackendEntityValue;
var
LFactory: IBackendMetaClassObjectFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaClassObjectFactory, LFactory) then
Result := LFactory.CreateMetaClassObject(AClassName, AObjectID)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
{ TBackendQueryApi }
constructor TBackendQueryApi.Create(const AApi: IBackendQueryApi);
begin
FServiceApi := AApi;
end;
constructor TBackendQueryApi.Create(const AService: IBackendQueryService);
begin
FService := AService;
end;
function TBackendQueryApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendQueryApi.GetServiceAPI: IBackendQueryApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetQueryApi
end;
procedure TBackendQueryApi.GetServiceNames(out ANames: TArray<string>);
begin
GetServiceAPI.GetServiceNames(ANames);
end;
procedure TBackendQueryApi.Query(const ADataType, ABackendClassName: string;
const AQuery: array of string; const AJSONArray: TJSONArray);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaDataType(ADataType, ABackendClassName);
Query(LMetaClass, AQuery, AJSONArray);
end;
procedure TBackendQueryApi.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray);
begin
GetServiceApi.Query(AClass, AQuery, AJSONArray);
end;
procedure TBackendQueryApi.Query(const AClass: TBackendMetaClass;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>);
begin
GetServiceApi.Query(AClass, AQuery, AJSONArray, AMetaArray);
end;
function TBackendQueryApi.CreateMetaDataType(
const ADataType, AClassName: string): TBackendMetaClass;
var
LFactory: IBackendMetaDataTypeFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaDataTypeFactory, LFactory) then
Result := LFactory.CreateMetaDataType(ADataType, AClassName)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
procedure TBackendQueryApi.Query(const ADataType, ABackendClassName: string;
const AQuery: array of string; const AJSONArray: TJSONArray;
out AMetaArray: TArray<TBackendEntityValue>);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaDataType(ADataType, ABackendClassName);
Assert(LMetaClass.BackendDataType = ADataType);
Query(LMetaClass, AQuery, AJSONArray, AMetaArray);
end;
procedure TBackendQueryApi.Query<T>(const ADataType, ABackendClassName: string;
const AQuery: array of string; const AResultList: TBackendObjectList<T>);
var
LMetaClass: TBackendMetaClass;
begin
LMetaClass := CreateMetaDataType(ADataType, ABackendClassName);
Query<T>(LMetaClass, AQuery, AResultList);
end;
procedure TBackendQueryApi.Query<T>(const ADataType: TBackendMetaClass;
const AQuery: array of string; const AResultList: TBackendObjectList<T>);
var
LJSONArray: TJSONArray;
LJSONValue: TJSONValue;
LMetaArray: TArray<TBackendEntityValue>;
LObject: T;
LList: TList<T>;
I: Integer;
begin
LJSONArray := TJSONArray.Create;
try
Query(ADataType, AQuery, LJSONArray, LMetaArray);
I := 0;
try
for LJSONValue in LJSONArray do
begin
if LJSONValue is TJSONObject then
begin
LObject := TJSON.JsonToObject<T>(TJSONObject(LJSONValue), []);
AResultList.Add(LObject, LMetaArray[I]);
end
else
raise EBackendServiceError.Create(sJSONObjectExpected);
Inc(I);
end;
except
AResultList.Clear;
raise;
end;
finally
LJSONArray.Free;
end;
end;
{ TBackendUsersApi }
constructor TBackendUsersApi.Create(const AApi: IBackendUsersApi);
begin
inherited Create(AApi);
FServiceApi := AApi;
end;
constructor TBackendUsersApi.Create(const AService: IBackendUsersService);
begin
FService := AService;
end;
function TBackendUsersApi.CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
var
LFactory: IBackendMetaUserFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaUserFactory, LFactory) then
Result := LFactory.CreateMetaUserObject(AObjectID)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
function TBackendFilesApi.CreateMetaFileObject(const AFileID: string): TBackendEntityValue;
var
LFactory: IBackendMetaFileFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaFileFactory, LFactory) then
Result := LFactory.CreateMetaFileObject(AFileID)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
function TBackendUsersApi.DeleteUser(
const AObject: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.DeleteUser(AObject);
end;
function TBackendUsersApi.FindUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
begin
Result := GetServiceApi.FindUser(AObject, AProc);
end;
function TBackendUsersApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendUsersApi.GetAuthApi: IBackendAuthApi;
begin
Result := GetServiceApi as IBackendAuthApi;
end;
function TBackendUsersApi.GetServiceAPI: IBackendUsersApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetUsersApi
end;
function TBackendUsersApi.DeleteUser(const AObjectID: string): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaUserObject(AObjectID);
Result := DeleteUser(LObject);
end;
function TBackendUsersApi.FindUser(const AObjectID: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaUserObject(AObjectID);
Result := GetServiceApi.FindUser(LObject, AUser, AJSON);
end;
function TBackendUsersApi.FindUser(const AObject: TBackendEntityValue;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
begin
Result := GetServiceApi.FindUser(AObject, AUser, AJSON);
end;
function TBackendUsersApi.FindUser(const AObjectID: string;
AProc: TFindObjectProc): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaUserObject(AObjectID);
Result := FindUser(LObject, AProc);
end;
function TBackendUsersApi.QueryUserName(const AUserName: string;
AProc: TFindObjectProc): Boolean;
begin
Result := GetServiceAPI.QueryUserName(AUserName, AProc);
end;
procedure TBackendUsersApi.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray);
begin
GetServiceApi.QueryUsers(AQuery, AJSONArray);
end;
function TBackendUsersApi.QueryUserName(const AUserName: string;
out AUser: TBackendEntityValue; const AJSON: TJSONArray): Boolean;
begin
Result := GetServiceApi.QueryUserName(AUserName, AUser, AJSON);
end;
procedure TBackendUsersApi.QueryUsers(const AQuery: array of string;
const AJSONArray: TJSONArray; out AMetaArray: TArray<TBackendEntityValue>);
begin
GetServiceApi.QueryUsers(AQuery, AJSONArray, AMetaArray);
end;
procedure TBackendUsersApi.UpdateUser(const AObjectID: string;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaUserObject(AObjectID);
UpdateUser(LObject, AUserData, AUpdatedObject);
end;
{ TBackendGroupsApi }
constructor TBackendGroupsApi.Create(const AApi: IBackendGroupsApi);
begin
FServiceApi := AApi;
end;
procedure TBackendGroupsApi.AddUser(const AGroupName, AUser: string; out AUpdatedObject: TBackendEntityValue);
begin
GetServiceApi.AddUsers(AGroupName, TArray<string>.Create(AUser), AUpdatedObject);
end;
function TBackendGroupsApi.RemoveUser(const AGroupName, AUser: string; out AUpdatedObject: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.RemoveUsers(AGroupName, TArray<string>.Create(AUser), AUpdatedObject);
end;
procedure TBackendGroupsApi.AddUsers(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue);
begin
GetServiceApi.AddUsers(AGroupName, AUsers, AUpdatedObject);
end;
function TBackendGroupsApi.RemoveUsers(const AGroupName: string;
const AUsers: TArray<string>; out AUpdatedObject: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.RemoveUsers(AGroupName, AUsers, AUpdatedObject);
end;
procedure TBackendGroupsApi.UpdateGroup(const AGroup: TBackendEntityValue;
const AJSONObject: TJSONObject; out AUpdatedObject: TBackendEntityValue);
begin
GetServiceApi.UpdateGroup(AGroup, AJSONObject, AUpdatedObject);
end;
constructor TBackendGroupsApi.Create(const AService: IBackendGroupsService);
begin
FService := AService;
end;
procedure TBackendGroupsApi.CreateGroup(const AGroupName: string;
const AJSON: TJSONObject; out ACreatedObject: TBackendEntityValue);
begin
GetServiceApi.CreateGroup(AGroupName, AJSON, ACreatedObject);
end;
function TBackendGroupsApi.CreateMetaGroupObject(const AGroupName: string): TBackendEntityValue;
var
LFactory: IBackendMetaGroupFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaGroupFactory, LFactory) then
Result := LFactory.CreateMetaGroupObject(AGroupName)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
function TBackendGroupsApi.DeleteGroup(
const AGroup: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.DeleteGroup(AGroup);
end;
function TBackendGroupsApi.DeleteGroup(const AGroupName: string): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaGroupObject(AGroupName);
Result := DeleteGroup(LObject);
end;
function TBackendGroupsApi.FindGroup(const AMetaObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
begin
Result := GetServiceApi.FindGroup(AMetaObject, AProc);
end;
function TBackendGroupsApi.FindGroup(const AGroupName: string;
AProc: TFindObjectProc): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaGroupObject(AGroupName);
Result := GetServiceApi.FindGroup(LObject, AProc);
end;
function TBackendGroupsApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendGroupsApi.GetServiceAPI: IBackendGroupsApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetGroupsAPI
end;
{ TBackendAuthApi }
var
FLogoutProcDict: TDictionary<TClass, TLogoutProc> = nil;
procedure RegisterLogoutProc(const AServiceAPIClass: TClass; AProc: TLogoutProc);
begin
if FLogoutProcDict = nil then
FLogoutProcDict := TDictionary<TClass, TLogoutProc>.Create;
FLogoutProcDict.AddOrSetValue(AServiceAPIClass, AProc);
end;
procedure CallLogoutProc(const ABackendAuthApi: IBackendAuthApi);
var
LApi: TObject;
LProc: TLogoutProc;
begin
if FLogoutProcDict = nil then
Exit;
LApi := ABackendAuthApi as TObject;
if FLogoutProcDict.TryGetValue(LApi.ClassType, LProc) then
LProc(LApi);
end;
constructor TBackendAuthApi.Create(const AApi: IBackendAuthApi);
begin
FServiceApi := AApi;
end;
constructor TBackendAuthApi.Create(const AService: IBackendAuthService);
begin
FService := AService;
end;
function TBackendAuthApi.CreateMetaUserObject(const AObjectID: string): TBackendEntityValue;
var
LFactory: IBackendMetaUserFactory;
begin
if Supports(GetServiceApi.GetMetaFactory, IBackendMetaUserFactory, LFactory) then
Result := LFactory.CreateMetaUserObject(AObjectID)
else
raise EBackendServiceError.Create(sNoMetaFactory);
end;
function TBackendAuthApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendAuthApi.GetServiceAPI: IBackendAuthApi;
begin
Result := GetAuthApi;
end;
function TBackendAuthApi.GetAuthAPI: IBackendAuthApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetAuthAPI
end;
function TBackendAuthApi.FindCurrentUser(const AObject: TBackendEntityValue;
AProc: TFindObjectProc): Boolean;
begin
Result := GetServiceApi.FindCurrentUser(AObject, AProc);
end;
procedure TBackendAuthApi.LoginUser(const AUserName, APassword: string;
out ALogin: TBackendEntityValue; const AJSON: TJSONArray);
begin
GetServiceApi.LoginUser(AUserName, APassword, ALogin, AJSON);
end;
procedure TBackendAuthApi.LoginUser(const AUserName, APassword: string;
AProc: TFindObjectProc);
begin
GetServiceApi.LoginUser(AUserName, APassword, Aproc);
end;
procedure TBackendAuthApiHelper.LogoutUser;
begin
CallLogoutProc(GetServiceApi);
end;
procedure TBackendAuthApi.SignupUser(const AUserName, APassword: string;
const AUserData: TJSONObject; out ACreatedObject: TBackendEntityValue);
begin
GetServiceApi.SignupUser(AUserName, APassword, AUserData, ACreatedObject);
end;
procedure TBackendAuthApi.UpdateUser(const AObject: TBackendEntityValue;
const AUserData: TJSONObject; out AUpdatedObject: TBackendEntityValue);
begin
GetServiceApi.UpdateUser(AObject, AUserData, AUpdatedObject);
end;
{ TBackendFilesApi }
constructor TBackendFilesApi.Create(const AApi: IBackendFilesApi);
begin
FServiceApi := AApi;
end;
constructor TBackendFilesApi.Create(const AService: IBackendFilesService);
begin
FService := AService;
end;
function TBackendFilesApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendFilesApi.GetServiceAPI: IBackendFilesApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetFilesApi
end;
procedure TBackendFilesApi.UploadFile(const AFileName, AContentType: string;
out AFile: TBackendEntityValue);
begin
GetServiceApi.UploadFile(AFileName, AContentType, AFile);
end;
function TBackendFilesApi.DeleteFile(const AFile: TBackendEntityValue): Boolean;
begin
Result := GetServiceApi.DeleteFile(AFile);
end;
function TBackendFilesApi.DeleteFile(const AFileID: string): Boolean;
var
LObject: TBackendEntityValue;
begin
LObject := CreateMetaFileObject(AFileID);
Result := DeleteFile(LObject);
end;
procedure TBackendFilesApi.UploadFile(const AFileName: string;
const AStream: TStream; const AContentType: string;
out AFile: TBackendEntityValue);
begin
GetServiceApi.UploadFile(AFileName, AStream, AContentType, AFile);
end;
{ TBackendObjectList<T> }
constructor TBackendObjectList<T>.Create;
begin
FDictionary := TObjectDictionary.Create;
FList := TList<T>.Create;
end;
destructor TBackendObjectList<T>.Destroy;
begin
Clear;
FDictionary.Free;
FList.Free;
inherited;
end;
function TBackendObjectList<T>.Extract(const Value: T): T;
var
I: Integer;
begin
I := FList.IndexOf(Value);
if I >= 0 then
begin
Result := FList[I];
FList.Delete(I);
FDictionary.Remove(Result);
end
else
raise EBackendServiceError.Create(sObjectNotFound);
end;
function TBackendObjectList<T>.ExtractArray: TArray<T>;
var
LPair: TObjectPair;
LList: TList<T>;
begin
LList := TList<T>.Create;
try
for LPair in FDictionary do
LList.Add(LPair.Key);
FDictionary.Clear; // Does not free objects
Result := LList.ToArray;
finally
LList.Free;
end;
end;
procedure TBackendObjectList<T>.Add(const AValue: T;
const AMetaObject: TBackendEntityValue);
begin
FDictionary.Add(AValue, AMetaObject);
FList.Add(AValue);
end;
procedure TBackendObjectList<T>.Clear;
var
LList: TList<T>;
begin
LList := TObjectList<T>.Create;
try
LList.AddRange(FList.ToArray);
FDictionary.Clear; // Does not free objects
FList.Clear;
finally
LList.Free; // Free objects
end;
end;
function TBackendObjectList<T>.GetCount: Integer;
begin
Result := FList.Count;
end;
function TBackendObjectList<T>.GetEnumerator: TEnumerator<T>;
begin
Result := TEnumerator.Create(FList);
end;
function TBackendObjectList<T>.GetItem(I: Integer): T;
begin
Result := FList[I];
end;
function TBackendObjectList<T>.IndexOf(I: T): Integer;
begin
Result := FList.IndexOf(I);
end;
function TBackendObjectList<T>.GetEntityValue(I: T): TBackendEntityValue;
begin
Result := FDictionary.Items[I];
end;
{ TBackendObjectList<T>.TEnumerator }
constructor TBackendObjectList<T>.TEnumerator.Create(const AList: TObjectList);
begin
FList := AList;
FIndex := -1;
end;
function TBackendObjectList<T>.TEnumerator.DoGetCurrent: T;
begin
if (FIndex < FList.Count) and (FIndex >= 0) then
Result := FList[FIndex]
else
Result := nil;
end;
function TBackendObjectList<T>.TEnumerator.DoMoveNext: Boolean;
begin
Inc(FIndex);
Result := FIndex < FList.Count;
end;
{ TBackendAuthenticationApi }
function TBackendAuthenticationApi.GetAuthentication: TBackendAuthentication;
begin
Result := GetAuthenticationApi.Authentication;
end;
function TBackendAuthenticationApi.GetDefaultAuthentication: TBackendDefaultAuthentication;
begin
Result := GetAuthenticationApi.DefaultAuthentication;
end;
procedure TBackendAuthenticationApi.Login(const ALogin: TBackendEntityValue);
begin
GetAuthenticationApi.Login(ALogin);
end;
procedure TBackendAuthenticationApi.Logout;
begin
GetAuthenticationApi.Logout;
end;
procedure TBackendAuthenticationApi.SetAuthentication(
const Value: TBackendAuthentication);
begin
GetAuthenticationApi.Authentication := Value;
end;
procedure TBackendAuthenticationApi.SetDefaultAuthentication(
const Value: TBackendDefaultAuthentication);
begin
GetAuthenticationApi.DefaultAuthentication := Value;
end;
{ TBackendCustomEndpointApi }
constructor TBackendCustomEndpointApi.Create(const AApi: IBackendCustomEndpointApi);
begin
FServiceApi := AApi;
end;
procedure TBackendCustomEndPointApi.CheckForResponseErrors(
const AResponse: TCustomRESTResponse; AValidStatusCodes: array of Integer);
begin
GetServiceApi.CheckForResponseErrors(AResponse, AValidStatusCodes);
end;
constructor TBackendCustomEndpointApi.Create(const AService: IBackendCustomEndpointService);
begin
FService := AService;
end;
function TBackendCustomEndpointApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendCustomEndpointApi.GetServiceAPI: IBackendCustomEndpointApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetCustomEndpointApi
end;
procedure TBackendCustomEndPointApi.PrepareClient(
const AClient: TCustomRESTClient);
begin
GetServiceApi.PrepareClient(AClient);
end;
procedure TBackendCustomEndPointApi.PrepareRequest(
const ARequest: TCustomRESTRequest);
begin
GetServiceApi.PrepareRequest(ARequest);
end;
initialization
finalization
FLogoutProcDict.Free;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGrids, SMDBGrid, Db, DBTables, ExtCtrls, StdCtrls;
type
TfrmMain = class(TForm)
Query1: TQuery;
DataSource1: TDataSource;
SMDBGrid1: TSMDBGrid;
Image1: TImage;
Query1CUSTNO: TFloatField;
Query1COUNTRY: TStringField;
Query1Flag: TFloatField;
lblDescription: TLabel;
lblURL: TLabel;
procedure SMDBGrid1Expression(Sender: TObject; Expression: String;
var Text: String; var Value: Boolean);
procedure SMDBGrid1DrawGroupingCell(Sender: TObject; ACanvas: TCanvas;
CellRect: TRect; Group: TSMGrouping; Text: String;
var DefaultDrawing: Boolean);
procedure lblURLClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.DFM}
uses ShellAPI;
procedure TfrmMain.SMDBGrid1Expression(Sender: TObject; Expression: String;
var Text: String; var Value: Boolean);
begin
if (Query1.FieldByName(Expression).AsInteger = 1) then
begin
Value := True;
Text := 'Customers from ' + Query1.FieldByName('Country').AsString
end;
end;
procedure TfrmMain.SMDBGrid1DrawGroupingCell(Sender: TObject;
ACanvas: TCanvas; CellRect: TRect; Group: TSMGrouping; Text: String;
var DefaultDrawing: Boolean);
begin
DefaultDrawing := False;
ACanvas.Brush.Color := Group.Color;
ACanvas.Font.Assign(Group.Font);
ACanvas.FillRect(CellRect);
ACanvas.Draw(CellRect.Left + 2, CellRect.Top + 2, Image1.Picture.Graphic);
CellRect.Left := CellRect.Left + Image1.Width + 5;
CellRect.Top := CellRect.Top + 2;
DrawText(ACanvas.Handle, PChar(Text), Length(Text), CellRect, DT_LEFT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX or DT_VCENTER)
end;
procedure TfrmMain.lblURLClick(Sender: TObject);
begin
ShellExecute(0, 'open', PChar((Sender as TLabel).Caption), nil, nil, SW_SHOWNORMAL);
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1997 Master-Bank }
{ }
{ Patched by Polaris Software }
{*******************************************************}
unit RXColors;
{$C PRELOAD}
{$I RX.INC}
interface
uses
Classes, Controls, Graphics, Forms, rxVCLUtils;
function RxIdentToColor(const Ident: string; var Color: Longint): Boolean;
function RxColorToString(Color: TColor): string;
function RxStringToColor(S: string): TColor;
procedure RxGetColorValues(Proc: TGetStrProc);
procedure RegisterRxColors;
implementation
uses
{$IFDEF RX_D5} Windows, {$ENDIF}
{$IFDEF RX_D6} DesignIntf, VCLEditors, Types,
{$ELSE} DsgnIntf, {$ENDIF} // Polaris
SysUtils;
type
TColorEntry = record
Value: TColor;
Name: PChar;
end;
const
clInfoBk16 = TColor($02E1FFFF);
clNone16 = TColor($02FFFFFF);
ColorCount = 3;
Colors: array[0..ColorCount - 1] of TColorEntry = (
(Value: clCream; Name: 'clCream'),
(Value: clMoneyGreen; Name: 'clMoneyGreen'),
(Value: clSkyBlue; Name: 'clSkyBlue'));
function RxColorToString(Color: TColor): string;
var
I: Integer;
begin
if not ColorToIdent(Color, Result) then begin
for I := Low(Colors) to High(Colors) do
if Colors[I].Value = Color then
begin
Result := StrPas(Colors[I].Name);
Exit;
end;
FmtStr(Result, '$%.8x', [Color]);
end;
end;
function RxIdentToColor(const Ident: string; var Color: Longint): Boolean;
var
I: Integer;
Text: array[0..63] of Char;
begin
StrPLCopy(Text, Ident, SizeOf(Text) - 1);
for I := Low(Colors) to High(Colors) do
if StrIComp(Colors[I].Name, Text) = 0 then begin
Color := Colors[I].Value;
Result := True;
Exit;
end;
Result := IdentToColor(Ident, Color);
end;
function RxStringToColor(S: string): TColor;
begin
if not RxIdentToColor(S, Longint(Result)) then
Result := StringToColor(S);
end;
procedure RxGetColorValues(Proc: TGetStrProc);
var
I: Integer;
begin
GetColorValues(Proc);
for I := Low(Colors) to High(Colors) do Proc(StrPas(Colors[I].Name));
end;
{ TRxColorProperty }
type
TRxColorProperty = class(TColorProperty)
public
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
{$IFDEF RX_D5}
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean); {$IFNDEF RX_D6}override;{$ENDIF} // Polaris
{$ENDIF}
end;
function TRxColorProperty.GetValue: string;
var
Color: TColor;
begin
Color := TColor(GetOrdValue);
{$IFDEF WIN32}
if Color = clNone16 then Color := clNone
else if Color = clInfoBk16 then Color := clInfoBk;
{$ENDIF}
Result := RxColorToString(Color);
end;
procedure TRxColorProperty.GetValues(Proc: TGetStrProc);
begin
RxGetColorValues(Proc);
end;
procedure TRxColorProperty.SetValue(const Value: string);
begin
SetOrdValue(RxStringToColor(Value));
end;
{$IFDEF RX_D5}
procedure TRxColorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
function ColorToBorderColor(AColor: TColor): TColor;
type
TColorQuad = record
Red, Green, Blue, Alpha: Byte;
end;
begin
if (TColorQuad(AColor).Red > 192) or (TColorQuad(AColor).Green > 192) or
(TColorQuad(AColor).Blue > 192) then
Result := clBlack
else if ASelected then
Result := clWhite
else
Result := AColor;
end;
var
vRight: Integer;
vOldPenColor, vOldBrushColor: TColor;
begin
vRight := (ARect.Bottom - ARect.Top) + ARect.Left;
with ACanvas do
try
vOldPenColor := Pen.Color;
vOldBrushColor := Brush.Color;
Pen.Color := Brush.Color;
Rectangle(ARect.Left, ARect.Top, vRight, ARect.Bottom);
Brush.Color := RxStringToColor(Value);
Pen.Color := ColorToBorderColor(ColorToRGB(Brush.Color));
Rectangle(ARect.Left + 1, ARect.Top + 1, vRight - 1, ARect.Bottom - 1);
Brush.Color := vOldBrushColor;
Pen.Color := vOldPenColor;
finally
ACanvas.TextRect(Rect(vRight, ARect.Top, ARect.Right, ARect.Bottom),
vRight + 1, ARect.Top + 1, Value);
end;
end;
{$ENDIF}
procedure RegisterRxColors;
begin
RegisterPropertyEditor(TypeInfo(TColor), TPersistent, '', TRxColorProperty);
end;
end. |
unit osExtenso;
interface
uses SysUtils;
function ValorPorExtenso(PValor : double) : string;
function MilharPorExtenso(PCentena : integer) : string;
const
Centena : array[1..9] of string =
('cento ',
'duzentos ',
'trezentos ',
'quatrocentos ',
'quinhentos ',
'seiscentos ',
'setecentos ',
'oitocentos ',
'novecentos '
);
Dezena : array[1..9] of string =
(
'dez ',
'vinte ',
'trinta ',
'quarenta ',
'cinquenta ',
'sessenta ',
'setenta ',
'oitenta ',
'noventa '
);
Vintena : array[1..9] of string =
('onze ',
'doze ',
'treze ',
'quatorze ',
'quinze ',
'dezesseis ',
'dezessete ',
'dezoito ',
'dezenove '
);
Unidade : array[1..9] of string =
(
'um ',
'dois ',
'tres ',
'quatro ',
'cinco ',
'seis ',
'sete ',
'oito ',
'nove '
);
Cifra : array[1..6, 1..2] of string =
( ('trilhão ', 'trilhões '),
('bilhão ', 'bilhões '),
('milhão ', 'milhões '),
('mil ', 'mil '),
('', ''),
('centavo ', 'centavos ')
);
Moeda = 'real ';
Moedas = 'reais ';
implementation
Function MilharPorExtenso(PCentena : integer): string;
var
sExtenso : string;
sValor : string;
iCentena : integer;
iDezena : integer;
iUnidade : integer;
begin
if (PCentena > 0) then
begin
if PCentena = 100 then begin
sExtenso := 'cem ';
end
else
begin
sValor := Format('%3.3d', [PCentena]);
iCentena := StrToInt(sValor[1]);
iDezena := StrToInt(sValor[2]);
iUnidade := StrToInt(sValor[3]);
if (iCentena > 0 ) then
begin
sExtenso := Centena[iCentena];
if (iDezena > 0) or (iUnidade > 0) then
sExtenso := sExtenso + 'e ';
end;
if (iDezena = 1) and (iUnidade > 0) then
begin
sExtenso := sExtenso + Vintena[iUnidade];
end
else
begin
if iDezena > 0 then
begin
sExtenso := sExtenso + Dezena[iDezena];
if iUnidade > 0 then
sExtenso := sExtenso + 'e ';
end;
if iUnidade > 0 then
sExtenso := sExtenso + Unidade[iUnidade];
end;
end;
end;
Result := sExtenso;
end;
Function ValorPorExtenso(PValor : double) : string;
var
sValor : string;
iCentavo : integer;
iMilhar : array [1..5] of integer;
sExtenso : string;
i : integer;
j : integer;
dValorInt : double;
begin
sExtenso := '';
if PValor > 0 then
begin
sValor := Format('%d', [Round(PValor * 100)]);
sValor := StringOfChar('0', 17 - Length(sValor)) + sValor;
iCentavo := StrToInt(Copy(sValor, 16, 2));
for i := 1 to 5 do
begin
iMilhar[i] := StrToInt(Copy(sValor, (i - 1) * 3 + 1, 3));
if iMilhar[i] > 0 then
begin
if sExtenso <> '' then
sExtenso := sExtenso + 'e ';
if iMilhar[i] = 1 then
j := 1 // singular
else
j := 2; // plural
sExtenso := sExtenso + MilharPorExtenso(iMilhar[i]) + Cifra[i, j];
end;
end;
dValorInt := Int(PValor);
if dValorInt > 0 then
begin
if Int(PValor) = 1 then
begin
sExtenso := sExtenso + Moeda;
end
else
begin
if (PValor >= 1000000) and (iMilhar[4] = 0) and(iMilhar[5] = 0) then
sExtenso := sExtenso + 'de ' + Moedas
else
sExtenso := sExtenso + Moedas;
end;
end;
if iCentavo > 0 then
begin
if sExtenso <> '' then
sExtenso := sExtenso + 'e ';
if iCentavo = 1 then
j := 1
else
j := 2;
sExtenso := sExtenso + MilharPorExtenso(iCentavo) + Cifra[6, j];
end;
if Copy(sExtenso, 1, 2) = 'um' then
Result := '' + sExtenso
else
Result := UpperCase(sExtenso[1]) + Copy(sExtenso, 2, 10000);
end
else
Result := ''; // Valor zero ou negativo
end;
end.
|
unit uUsuarioModel;
interface
uses
uEnumerado, FireDAC.Comp.Client, uPermissao;
type
TUsuarioModel = class
private
FAcao: TAcao;
FCpf: string;
FSenha: string;
FNome: string;
FSNome: string;
FPermissao: string;
procedure SetAcao(const Value: TAcao);
procedure SetCpf(const Value: string);
procedure SetSenha(const Value: string);
procedure SetNome(const Value: string);
procedure SetSobrenome(const Value: string);
procedure SetPermissao(const Value: string);
public
function Obter: TFDQuery;
function Buscar: TFDQuery;
function VerificaSenha(SenhaInserida: string): Boolean;
function VerificaPermissao(): TPermissao;
function Salvar: Boolean;
function ObterNome: String;
function ObterDados: TFDQuery;
property Cpf: string read FCpf write SetCpf;
property Senha: string read FSenha write SetSenha;
property Nome: string read FNome write SetNome;
property SNome: string read FSNome write SetSobrenome;
property Permissao: string read FPermissao write SetPermissao;
property Acao: TAcao read FAcao write SetAcao;
end;
implementation
{ TCliente }
uses uUsuarioDao;
function TUsuarioModel.Obter: TFDQuery;
var
Dao: TUsuarioDao;
begin
Dao := TUsuarioDao.Create;
try
Result := Dao.Obter;
finally
Dao.Free;
end;
end;
function TUsuarioModel.Salvar: Boolean;
var
VClienteDao: TUsuarioDao;
begin
Result := False;
VClienteDao := TUsuarioDao.Create;
try
case FAcao of
uEnumerado.tacIncluir:
Result := VClienteDao.Incluir(Self);
uEnumerado.tacAlterar:
Result := VClienteDao.Alterar(Self);
uEnumerado.tacExcluir:
Result := VClienteDao.Excluir(Self);
end;
finally
VClienteDao.Free;
end;
end;
procedure TUsuarioModel.SetAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TUsuarioModel.SetCpf(const Value: string);
begin
FCpf := Value;
end;
procedure TUsuarioModel.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TUsuarioModel.SetPermissao(const Value: string);
begin
FPermissao := Value;
end;
procedure TUsuarioModel.SetSenha(const Value: string);
begin
FSenha := Value;
end;
procedure TUsuarioModel.SetSobrenome(const Value: string);
begin
FSNome := Value;
end;
function TUsuarioModel.ObterNome(): String;
var
VQry: TFDQuery;
VUsuarioDao: TUsuarioDao;
begin
VUsuarioDao := TUsuarioDao.Create;
try
VQry := VUsuarioDao.ObterDados(Self);
Result := (VQry.FieldByName('FNome').AsString + ' ' + VQry.FieldByName('LNome').AsString);
finally
VUsuarioDao.Free;
end;
end;
function TUsuarioModel.VerificaSenha(SenhaInserida: string): Boolean;
var
VQry: TFDQuery;
VUsuarioDao: TUsuarioDao;
begin
VUsuarioDao := TUsuarioDao.Create;
try
VQry := VUsuarioDao.ObterDados(Self);
if VQry.FieldByName('Senha').AsString = SenhaInserida then
begin
Result := True;
end
else
begin
Result := False;
end;
finally
VUsuarioDao.Free;
end;
end;
function TUsuarioModel.Buscar(): TFDQuery;
var
Dao: TUsuarioDao;
begin
Dao := TUsuarioDao.Create;
try
Result := Dao.Buscar(Self);
finally
Dao.Free;
end;
end;
function TUsuarioModel.VerificaPermissao(): TPermissao;
var
VQry: TFDQuery;
VUsuarioDao: TUsuarioDao;
begin
VUsuarioDao := TUsuarioDao.Create;
try
VQry := VUsuarioDao.ObterDados(Self);
if VQry.FieldByName('Permissao').AsString = 'adm' then
Result := uPermissao.pAdmin;
if VQry.FieldByName('Permissao').AsString = 'usr' then
Result := uPermissao.pNormal;
finally
VUsuarioDao.Free;
end;
end;
function TUsuarioModel.ObterDados(): TFDQuery;
var
Dao: TUsuarioDao;
begin
Dao := TUsuarioDao.Create;
try
Result := Dao.ObterDados(Self);
finally
Dao.Free;
end;
end;
end.
|
unit PeMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, ExtCtrls, pegradpanl, peoutlookbtn, PeJeonLabel, StdCtrls, Db, DbTables,
Mask, pebtnedit, Grids, DBGrids, pedbgrid, DBCGrids, DBCtrls, pedbutil, hanapass,
pereg, jeonPan, NotesHana_TLB,OnInsaCommon, OnEditBaseCtrl,
OnEditStdCtrl, OnEditNumCtl, Tmax_DataSetText, Buttons, TmaxFunc;
type
TMainForm = class(TForm)
DBSet1: TTMaxDataSet;
P_Title: TPeJeonGrdPanel;
sGrid1: TStringGrid;
Bt_Srh: TPeJeonOutLookBtn;
Bt_Mod: TPeJeonOutLookBtn;
Bt_Exit: TPeJeonOutLookBtn;
Label5: TLabel;
St_Help: TStatusBar;
DBSet2: TTMaxDataSet;
Label1: TLabel;
Label2: TLabel;
ed_name: TOnEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Bt_ExitClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure sGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure sGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure sGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Bt_SrhClick(Sender: TObject);
procedure Bt_ModClick(Sender: TObject);
procedure ed_nameKeyPress(Sender: TObject; var Key: Char);
procedure sGrid1DblClick(Sender: TObject);
private
{ Private declarations }
Start : Boolean;
Inter : ILotusNotes_Hana;
pEmpno : string; // 로그인 사번
pKorname : string; // 로그인 성명
pPass : String;
pClass : string; // 로그인 등급
ComIp : string;
{
Lsysdate : string;
Lfordate : string;
Lwork : string; // 작업자 구분.
Le2empno : string; // 2차 평가자
Le1korname : string; // 1차 평가자 성명.
Le2korname : string; // 2차 평가자 성명.
Lebrempno : string; // 지점장
Lebrkorname : string; // 지점장 성명
grvalconyn ,
ge1valconyn ,
ge2valconyn ,
ge1valobjyn ,
ge2valobjyn : string;
}
gebrvalconyn ,
gebrvalobjyn : string;
iChkSenioryn : integer;
function GetBaseYear(gubun : integer) : string;
function Csel_gfd(p_loc: Integer): String;
public
gsLastConEv : String; //업무목표최종결재자 (1차 or 2차)
Lrabasdate : string; // 평가기준일.
// Le1empno : string; // 1차 평가자
// g_mainweight : string; // 전체 비중
// EvalYN : Boolean;
{ Public declarations }
end;
var
MainForm: TMainForm;
FSvr : OleVariant;
vOrgnum, vDeptcode : string;
ACol,ARow: Integer;
const
Msg = '목표 면담등록 서버가 다운된 것 같습니다.'+#13#13+'담당자에게 문의 하십시오'#13;
implementation
uses
Hinsa_TmaxDM, peDm, pea1060c1;//, pea1060a2, pea1060a3, pea1060b1;
{$R *.DFM}
procedure DrawCheck(ACanvas: TCanvas; ARect: TRect; AColor: TColor; EditStyle: word; Flag: string);
var iDR:integer;
begin
if Trim(Flag) = '' then Exit;
with ACanvas do
begin
case EditStyle of
1: begin //esCheckBox
case Flag[1] of
'1': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE;
'2': iDR:= DFCS_BUTTONCHECK or DFCS_CHECKED;
'3': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE or DFCS_INACTIVE;
'4': iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE or DFCS_INACTIVE or DFCS_CHECKED;
else iDR:= DFCS_BUTTONCHECK or DFCS_BUTTON3STATE;
end;
end;
2: begin //esRadioButton
case Flag[1] of
'1': iDR:= DFCS_BUTTONRADIO;
'2': iDR:= DFCS_BUTTONRADIO or DFCS_CHECKED;
'3': iDR:= DFCS_BUTTONRADIO or DFCS_INACTIVE;
'4': iDR:= DFCS_BUTTONRADIO or DFCS_CHECKED or DFCS_INACTIVE;
else iDR:= DFCS_BUTTONRADIO;
end;
end;
else Exit;
end;
ACanvas.Brush.Color:= AColor;
ACanvas.FillRect(ARect);
InflateRect(ARect,-((ARect.Right - ARect.Left -14) shr 1),-((ARect.Bottom - ARect.Top -14) shr 1)); //DFCS_MONO
DrawFrameControl(Handle, ARect, DFC_BUTTON, iDR);
end;
end;
//작업상 필요한 날짜 얻기
function TMainForm.GetBaseYear(gubun : integer) : string;
var
Sql : string;
begin
Result := '';
if gubun = 1 then //업적평가 기준일(Lrabasdate)
Sql := 'SELECT VALUE1 FROM PEHREBAS WHERE RABASDATE = ''00000000'' AND GUBUN = ''00'' AND SGUBUN = ''0001'' ';
if gubun = 2 then //하반기 업적평가 시작일(LFordate)
Sql := 'SELECT VALUE2 FROM PEHREBAS WHERE RABASDATE = ''00000000'' AND GUBUN = ''00'' AND SGUBUN = ''0003'' ';
if gubun = 3 then //시스템 시각(Lsysdate)
Sql := 'SELECT TO_CHAR(SYSDATE,''YYYYMMDDHH24MISSD'') FROM DUAL ';
if gubun = 4 then //
Sql := 'SELECT NVL(VALUE5,'' '') FROM PEHREBAS '+
' WHERE RABASDATE = ''' + Lrabasdate + ''' AND GUBUN = ''11'' AND SGUBUN = ''0003'' ';
if gubun = 5 then //
Sql := 'SELECT NVL(VALUE3,'' '') FROM PIMVARI '+
' WHERE GUBUN = ''00'' AND SGUBUN = ''0001'' ';
DataModule_Tmax.Csel_SQL := Sql;
DataModule_Tmax.Csel_Open4;
Result := DataModule_Tmax.Csel_gfd4(1);
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Inter := nil;
Action := caFree;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
sMsg : string;
begin
sMsg := DataModule_Tmax.Connect_Session;
if sMsg <> '' then
begin
Application.MessageBox(PChar(msg),'TMAX에러',mb_ok);
Application.Terminate;
Exit;
end;
Start := True;
//2013.11. Add 파라미터와 비교하여 암호 다르면 접속 막음.
FM_Tmax := TFM_Tmax.Create(Self);
FM_Tmax.T_Session := DataModule_Tmax.TMaxSession;
if FM_Tmax.PassWordChk(Hinsa_Param(cmdline,1), Hinsa_Param(cmdline,3)) = 0 then
Application.Terminate;
Inter := nil;
end;
procedure TMainForm.Bt_ExitClick(Sender: TObject);
begin
Close;
end;
function TMainForm.Csel_gfd(p_loc: Integer): String;
var
v_cnt, v_tmp: Integer;
v_data: String;
begin
Result := '';
v_data := DBSet1.FieldByName('SEL_DATA').AsString;
v_cnt := 1;
while v_cnt < p_loc do
begin
v_tmp := Pos(';',v_data);
if not(v_tmp > 0) then Exit;
v_cnt := v_cnt + 1;
Delete(v_data, 1, v_tmp);
end;
v_tmp := Pos(';',v_data) - 1;
if v_tmp < 0 then v_tmp := Length(v_data);
Result := Copy(v_data,1,v_tmp);
end;
procedure TMainForm.FormShow(Sender: TObject);
var SqlText : string;
begin
with sGrid1 do
begin
Cells[1,0] := '사번';
Cells[2,0] := '이름';
Cells[3,0] := '직책';
Cells[4,0] := '공동대상';
Cells[5,0] := '등록자';
end;
pEmpno := peParam(CmdLine,1);
pKorname := peParam(CmdLine,2);
pPass := peParam(CmdLine,3);
pClass := peParam(CmdLine,4);
ComIp := peParam(Cmdline,5);
ComIP := Copy(ComIP,2,Length(ComIP)-1);
Lrabasdate := GetBaseYear(1); //업적평가 기준일
ed_name.SetFocus;
{
//사번, 부터코드를 체크해야 한다.
SqlText := 'SELECT EMPNO ||'';''|| KORNAME ||'';''|| DEPTCODE ' +
' FROM PEHREMAS '+
' WHERE RABASDATE = ''' + Lrabasdate + ''' '+ // 평가기준일
' AND EMPNO = ''' + pEmpno + ''' '+ // 선택된사번
' AND RECONYN = ''Y'' '; // 목표등록대상여부
with DBSet1 do
begin
Close;
ServiceName := 'PEA1060A_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 300);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount > 0 then
begin
vDeptcode := Csel_gfd(3); //TASKCODE
end;
end;
memo1.text := sqltext;
}
//팀장여부를 체크한다.
//만일 팀장이 아니면 조회버튼 비활성화 , 반영버튼 비활성화 시킨다.
SqlText := ' select payra from PEHREAIM_COMBAS '+
' where rabasdate = ''' + Lrabasdate + ''' '+
' and empno = ''' + pEmpno + ''' '+
' and senioryn = ''Y'' '; //선임여부를 체크한다.
// ' and payra in (''2C'',''58'',''1B'',''16'') '; //팀장여부를 체크한다.
with DBSet2 do
begin
Close;
ServiceName := 'PEA1060A_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 300);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount < 1 then
begin
Bt_Srh.Enabled := false;
Bt_Mod.Enabled := false;
showmessage('망운용/망통제/지사 팀장만이 공동목표대상자를 선정할 수 있습니다.');
Bt_ExitClick(sender);
end;
close;
end;
Bt_SrhClick(sender);
end;
procedure TMainForm.sGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
begin
if (ACol = 4) and (ARow > 0) then
begin
if sGrid1.Cells[ACol,ARow] <> '' then //Check Box
with sGrid1 do DrawCheck(Canvas,Rect, Color,1, Cells[ACol, ARow]);
end;
if (ACol = 5) and (ARow > 0) then //Radio Button
with sGrid1 do DrawCheck(Canvas,Rect, Color,2, Cells[ACol, ARow]);
end;
procedure TMainForm.sGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
//showmessage('mousedown');
if Button = mbLeft Then
begin
//showmessage(sGrid1.Cells[ACol,ARow]);
sGrid1.MouseToCell(X, Y, ACol, ARow);
end;
end;
procedure TMainForm.sGrid1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var iCol,iRow, i: Integer;
SqlText : string;
begin
//showmessage('mouseup');
if Button = mbLeft then
begin
with sGrid1 do
begin
MouseToCell(X, Y, iCol, iRow);
if iRow = 0 then
exit;
SqlText := 'SELECT unionyn||'';''||payra FROM pehreaim_combas '+
'WHERE rabasdate = ''' + Lrabasdate + ''' '+
'AND empno = ''' + sGrid1.Cells[1,iRow] + ''' ';
with DBSet1 do
begin
Close;
ServiceName := 'PEA1060A_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 300);
ClearParamInfo;
SQL.Text := SqlText;
Open;
if RecordCount <= 0 then
begin
showmessage('등록된 사원이 아닙니다.');
Exit;
end;
{
if (Csel_gfd(1) = 'N') and (iCol = 4) then
begin
showmessage('일반목표 대상자를 공동목표 대상자로 변경할 수 없습니다!');
exit;
end;
}
end;
{2010.11.05 jissi 내가 귀찮아서.....
if (iCol = 4) and ((sGrid1.Cells[iCol,ARow]) = '1') and ((sGrid1.Cells[16,ARow]) = '1') then
begin
showmessage('일반목표 등록자를 공동목표 등록대상자로 변경할 수 없습니다.');
exit;
end;
}
if (ACol = 4) and (ARow > 0) and (ACol = iCol) and (ARow = iRow) and (sGrid1.Cells[ACol,ARow] <> '') then
Cells[ACol, ARow]:= IntToStr(StrToIntDef(Cells[ACol, ARow],0) mod 2 + 1);
if (ACol = 5) then
begin
if (ARow > 0) and (ACol = iCol) and (ARow = iRow) then
begin
for i := 1 to RowCount -1 do
Cells[5, i] := '1';
end;
Cells[ACol, ARow]:= IntToStr(StrToIntDef(Cells[ACol, ARow],0) mod 2 + 1);
end;
end;
end;
end;
procedure TMainForm.Bt_SrhClick(Sender: TObject);
var
SqlText : string;
i : integer;
sJOBDUTY : string;
begin
{
SqlText := ' SELECT NVL(A.RABASDATE,'''') ||'';''||NVL(A.EMPNO,'''')||'';''||NVL(A.KORNAME,'''')||'';''||B.CODENAME||'';''|| NVL(A.DEPTCODE,'''') ||'';''||'+
' DECODE(NVL(A.UNIONYN,''N''),''Y'',''2'',''1'')||'';''|| DECODE(NVL(A.SENIORYN,''N''),''Y'',''2'',''1'') ||'';''||'+
' A.JOBDUTY||'';''||A.PAYRA '+
' FROM PEHREAIM_COMBAS A, PYCCODE B '+
' WHERE A.RABASDATE = ''' + Lrabasdate + ''' AND A.KORNAME LIKE '''+trim(ed_name.text)+'%'''+
' AND SUBSTR(A.DEPTCODE,1,3) IN (SELECT SUBSTR(DEPTCODE,1,3) FROM PEHREAIM_COMBAS '+
' WHERE RABASDATE = ''' + Lrabasdate + ''' AND EMPNO = ''' + pEmpno + ''') AND A.PAYCL = B.CODENO '+
' AND B.CODEID = ''I112'' AND B.USEYN = ''Y'' ORDER BY A.PAYCL, A.PAYRA, A.EMPNO ';
}
//H10차에 의한 부서코드 변환 deptcode,1,3->deptcode,1,4 20051025JSH
SqlText := ' SELECT NVL(A.RABASDATE,'''') ||'';''||NVL(A.EMPNO,'''')||'';''||NVL(A.KORNAME,'''')||'';''||B.CODENAME||'';''|| NVL(A.DEPTCODE,'''') ||'';''||'+
' DECODE(NVL(A.UNIONYN,''N''),''Y'',''2'',''1'')||'';''|| DECODE(NVL(A.SENIORYN,''N''),''Y'',''2'',''1'') ||'';''||'+
' A.JOBDUTY||'';''||A.PAYRA ||'';''||nvl(C.FLAG,'''')||'';''||nvl(A.PAYCL,'''') '+
' ||'';''||DECODE(NVL(A.BFUNIONYN,''N''),''Y'',''2'',''1'') '+ #13 +
' FROM PEHREAIM_COMBAS A, PYCCODE B, '+ #13 +
'(select distinct empno, ''Y'' FLAG from PEHREAIM_COMDET '+ #13 +
' where RABASDATE = ''' + Lrabasdate + ''' '+ #13 +
' and substr(deptcode,1,4) in (SELECT SUBSTR(DEPTCODE,1,4) FROM PEHREAIM_COMBAS '+ #13 +
' WHERE RABASDATE = ''' + Lrabasdate + ''' AND EMPNO = ''' + pEmpno + ''') ) C '+ #13 +
' WHERE A.RABASDATE = ''' + Lrabasdate + ''' AND A.KORNAME LIKE '''+trim(ed_name.text)+'%'''+ #13 +
' AND SUBSTR(A.DEPTCODE,1,4) IN (SELECT SUBSTR(DEPTCODE,1,4) FROM PEHREAIM_COMBAS '+ #13 +
' WHERE RABASDATE = ''' + Lrabasdate + ''' AND EMPNO = ''' + pEmpno + ''') '+ #13 +
' AND A.PAYRA = B.CODENO AND B.CODEID = ''I113'' AND B.USEYN = ''Y'' AND A.EMPNO = C.EMPNO(+) '+ #13 +
' ORDER BY A.PAYCL, A.PAYRA, A.EMPNO ';
//Edit1.Text := SqlText;
with DBSet1 do
begin
Close;
ServiceName := 'PEA1060A_common';
ClearFieldInfo;
AddField('SEL_DATA', ftString, 300);
ClearParamInfo;
SQL.Text := SqlText;
Open;
//showmessage(inttostr(RecordCount));
if RecordCount > 0 then
begin
iChkSenioryn := -1;
sGrid1.RowCount := RecordCount +1;
for i := 1 to RecordCount do
begin
sGrid1.Cells[1,i] := Csel_gfd(2); //EMPNO
sGrid1.Cells[2,i] := Csel_gfd(3); //KORNAME
sGrid1.Cells[3,i] := Csel_gfd(4); //CODENAME
if GetBaseYear(5) <= GetBaseYear(3) then
begin
if ((Csel_gfd(9) <> 'C11') and (Csel_gfd(9) <> 'C15')) then
sGrid1.Cells[4,i] := Csel_gfd(6); //UNIONYN
end
else
begin
if ((Csel_gfd(9) <> '2C') and (Csel_gfd(9) <> '58')) then
sGrid1.Cells[4,i] := Csel_gfd(6); //UNIONYN
end;
sGrid1.Cells[5,i] := Csel_gfd(7); //SENIORYN
sGrid1.Cells[10,i]:= Csel_gfd(1); //RABASDATE
sGrid1.Cells[11,i]:= Csel_gfd(5); //DEPTCODE
sGrid1.Cells[12,i]:= sGrid1.Cells[4,i]; //UNIONYN
sGrid1.Cells[13,i]:= Csel_gfd(10); //flag
//직위,직종코드를 임시 저장함.
sGrid1.Cells[14,i]:= Csel_gfd(11); //PAYCL
sGrid1.Cells[15,i]:= Csel_gfd(9); //PAYRA
sGrid1.Cells[16,i]:= Csel_gfd(12); //BFUNIONYN
//선임이면...
if sGrid1.Cells[5,i] = '2' then
iChkSenioryn := i;
next;
end;
end;
close;
end;
end;
procedure TMainForm.Bt_ModClick(Sender: TObject);
var i : integer;
sqltext : string;
sChkYN : string;
begin
with sGrid1 do
begin
//선임자 변경여부 체크
for i := 1 to RowCount -1 do
begin
if Cells[5,i] = '2' then //선임자이면
begin
//선임자가 바뀌지 않았음
if i = iChkSenioryn then
break
//선임자가 바뀌었을 경우
else
begin
//선임자 변경처리를 한다.
//먼저 변경전 선임자를 선임자여부 N으로 변경처리한다.
if iChkSenioryn > 0 then
begin
SqlText := Format('UPDATE pehreaim_combas SET '+
' SENIORYN = ''N'' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' AND deptcode = ''%s'' ',
[trim(Cells[10,iChkSenioryn]), trim(Cells[1,iChkSenioryn]), trim(Cells[11,iChkSenioryn])]);
DataModule_Tmax.Cupd_SQL := Sqltext;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
end;
//선임자 설정한다.
SqlText := Format('UPDATE pehreaim_combas SET '+
' SENIORYN = ''Y'' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' AND deptcode = ''%s'' ',
[trim(Cells[10,i]), trim(Cells[1,i]), trim(Cells[11,i])]);
DataModule_Tmax.Cupd_SQL := Sqltext;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
end;
break;
end;
end;
//공동/일반여부를 수정한다.
for i := 1 to RowCount -1 do
begin
// Cells[7,i](변경전공동/일반구분)과 cells[3,i](변경후공동/일반구분)을 비교하여
// 서로다르면 cells[3,i](변경후공동/일반구분)으로 update처리 시킨다.
if trim(Cells[4,i]) <> trim(Cells[12,i]) then
begin
if trim(Cells[4,i]) = '2' then sChkYN := 'Y'
else sChkYN := 'N';
SqlText := Format(' UPDATE pehreaim_combas SET '+
' UNIONYN = '''+sChkYN+''' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' AND deptcode = ''%s'' ',
[trim(Cells[10,i]), trim(Cells[1,i]), trim(Cells[11,i])]);
DataModule_Tmax.Cupd_SQL := Sqltext;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
{
if sGrid1.Cells[13,i] <> '' then
begin
showmessage('공동목표 대상자이면서 개인목표등록을 한 대상자는 '+#13+
'변경할 수 없습니다. ');
end
else
begin
if trim(Cells[4,i]) = '2' then sChkYN := 'Y'
else sChkYN := 'N';
SqlText := Format(' UPDATE pehreaim_combas SET '+
' UNIONYN = '''+sChkYN+''' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' AND deptcode = ''%s'' ',
[trim(Cells[10,i]), trim(Cells[1,i]), trim(Cells[11,i])]);
DataModule_Tmax.Cupd_SQL := Sqltext;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
end;
}
{
if trim(Cells[4,i]) = '2' then sChkYN := 'Y'
else sChkYN := 'N';
SqlText := Format('UPDATE pehreaim_combas SET '+
' UNIONYN = '''+sChkYN+''' '+
' WHERE rabasdate = ''%s'' AND empno = ''%s'' AND deptcode = ''%s'' ',
[trim(Cells[10,i]), trim(Cells[1,i]), trim(Cells[11,i])]);
DataModule_Tmax.Cupd_SQL := Sqltext;
DataModule_Tmax.Cupd_Exec;
if not DataModule_Tmax.Cupd_ret then
begin
Messagedlg('APP-Server Error',mtError,[mbOK],0);
Exit;
end;
}
end;
end;
end;
showmessage('처리되었습니다.');
Bt_SrhClick(self);
end;
procedure TMainForm.ed_nameKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
Bt_SrhClick(self);
end;
procedure TMainForm.sGrid1DblClick(Sender: TObject);
begin
//직무코드와 직무내용을 보여줄수 있도록 한다.
//지금 등록중인 직무내용과 맞지 않아서 혼돈될 우려가 있어서 막음.
{ Fm_sub_Form1.Lempno := sGrid1.Cells[1,sGrid1.Row];
Fm_sub_Form1.Lpaycl := sGrid1.Cells[14,sGrid1.Row];
Fm_sub_Form1.Lpayra := sGrid1.Cells[15,sGrid1.Row];
Fm_sub_Form1.Pa_Title.Caption := trim(sGrid1.Cells[2,sGrid1.Row]) +' 직무내용';
Fm_sub_Form1.ShowModal;
}
end;
end.
|
Unit RemDriversInfo;
Interface
Uses
RemDiskDll;
Procedure RemInfoInit(Var AInfo:REM_DRIVERS_INFO);
Function RemInfoPlainRAMDisksSupported:Boolean;
Function RemInfoPlainFileDisksSupported:Boolean;
Function RemInfoEncryptedRAMDisksSupported:Boolean;
Function RemInfoEncryptedFileDisksSupported:Boolean;
Function RemInfoEFRAMDisksSupported:Boolean;
Function RemInfoEFFileDisksSupported:Boolean;
Implementation
Var
driversInfo : REM_DRIVERS_INFO;
Procedure RemInfoInit(Var AInfo:REM_DRIVERS_INFO);
begin
driversInfo := AInfo;
end;
Function RemInfoPlainRAMDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_PLAIN_RAM_DISKS) <> 0;
end;
Function RemInfoPlainFileDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_PLAIN_FILE_DISKS) <> 0;
end;
Function RemInfoEncryptedRAMDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_ENCRYPTED_RAM_DISKS) <> 0;
end;
Function RemInfoEncryptedFileDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_ENCRYPTED_FILE_DISKS) <> 0;
end;
Function RemInfoEFRAMDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_EF_RAM_DISKS) <> 0;
end;
Function RemInfoEFFileDisksSupported:Boolean;
begin
Result := (driversInfo.Flags And REMBUS_FLAG_SUPPORTS_EF_FILE_DISKS) <> 0;
end;
end.
|
{
Ultibo Binary to Type Tool.
Copyright (C) 2021 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
Binary to Type
==============
This tool takes any binary file and converts it to an array type and variable
that can be embedded into a Pascal project. You can optionally specify a starting
offset and length for the conversion (defaults to the entire file).
}
unit Main;
{$MODE Delphi}
interface
uses
LCLIntf,
LCLType,
LMessages,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls;
type
{ TfrmMain }
TfrmMain = class(TForm)
chkStandalone: TCheckBox;
cmdConvert: TButton;
cmdExit: TButton;
lblSource: TLabel;
txtSource: TEdit;
lblDest: TLabel;
txtDest: TEdit;
lblOffset: TLabel;
txtOffset: TEdit;
lblSize: TLabel;
txtSize: TEdit;
lblSize2: TLabel;
cmdSource: TButton;
cmdDest: TButton;
openMain: TOpenDialog;
saveMain: TSaveDialog;
lblName: TLabel;
txtName: TEdit;
procedure chkStandaloneClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormHide(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure txtSourceChange(Sender: TObject);
procedure cmdSourceClick(Sender: TObject);
procedure txtDestChange(Sender: TObject);
procedure cmdDestClick(Sender: TObject);
procedure txtOffsetChange(Sender: TObject);
procedure txtSizeChange(Sender: TObject);
procedure cmdConvertClick(Sender: TObject);
procedure cmdExitClick(Sender: TObject);
procedure txtNameChange(Sender: TObject);
private
{ Private declarations }
FSource:String;
FDest:String;
FStandalone:Boolean;
FName:String;
FOffset:LongWord;
FSize:LongWord;
public
{ Public declarations }
function Convert:Boolean;
procedure WriteBuffer(AStream:TStream;const ABuffer:String);
end;
const
DefaultName = 'BinaryData';
var
frmMain: TfrmMain;
implementation
{$R *.lfm}
{==============================================================================}
{==============================================================================}
function TfrmMain.Convert:Boolean;
var
ByteCount:LongWord;
LineCount:LongWord;
SourceFile:TFileStream;
DestFile:TFileStream;
WorkByte:Byte;
WorkBuffer:String;
ReadStart:LongWord;
ReadSize:LongWord;
begin
{}
Result:=False;
try
Screen.Cursor:=crHourGlass;
try
{Check Name}
if Length(FName) = 0 then FName:=DefaultName;
{Check Source}
if not FileExists(FSource) then Exit;
{Check Dest}
if FileExists(FDest) then
begin
if MessageDlg('Destination file already exists, overwrite ?',mtConfirmation,[mbYes,mbNo],0) <> mrYes then Exit;
FileSetAttr(FDest,0);
end;
{Open Source}
SourceFile:=TFileStream.Create(FSource,fmOpenRead or fmShareDenyNone);
try
{Open Dest}
DestFile:=TFileStream.Create(FDest,fmCreate or fmShareDenyWrite);
try
ReadStart:=FOffset;
if ReadStart > LongWord(SourceFile.Size - 1) then ReadStart:=(SourceFile.Size - 1);
ReadSize:=SourceFile.Size;
if FSize > 0 then ReadSize:=ReadStart + FSize;
if ReadSize > LongWord(SourceFile.Size) then ReadSize:=SourceFile.Size;
SourceFile.Position:=ReadStart;
DestFile.Position:=0;
if FStandalone then
begin
{Create Interface}
WorkBuffer:='unit ' + ChangeFileExt(ExtractFileName(FDest),'') + ';';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='interface';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
end;
{Create Type and Var}
WorkBuffer:='type';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:=' T' + FName + ' = array[0..' + IntToStr(ReadSize - 1) + '] of Byte;';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='var';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:=' ' + FName + ':T' + FName + ' = (';
WriteBuffer(DestFile,WorkBuffer);
LineCount:=1;
WorkBuffer:=' ';
for ByteCount:=ReadStart to ReadSize - 1 do
begin
SourceFile.ReadBuffer(WorkByte,1);
WorkBuffer:=WorkBuffer + '$' + IntToHex(WorkByte,2);
{Check for Last Byte}
if ByteCount < (ReadSize - 1) then
begin
WorkBuffer:=WorkBuffer + ',';
end;
Inc(LineCount);
if LineCount > 16 then
begin
{Move to Next Line}
WriteBuffer(DestFile,WorkBuffer);
LineCount:=1;
WorkBuffer:=' ';
end
else
begin
if ByteCount = (ReadSize - 1) then
begin
{Write Last Line}
WriteBuffer(DestFile,WorkBuffer);
end;
end;
end;
WorkBuffer:=' );';
WriteBuffer(DestFile,WorkBuffer);
if FStandalone then
begin
{Create Implementation}
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='implementation';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:=' // Nothing';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='';
WriteBuffer(DestFile,WorkBuffer);
WorkBuffer:='end.';
WriteBuffer(DestFile,WorkBuffer);
end;
Result:=True;
finally
DestFile.Free;
end;
finally
SourceFile.Free;
end;
finally
Screen.Cursor:=crDefault;
end;
except
{}
end;
end;
{==============================================================================}
procedure TfrmMain.WriteBuffer(AStream:TStream;const ABuffer:String);
var
WorkBuffer:String;
begin
{}
if AStream = nil then Exit;
WorkBuffer:=ABuffer + Chr(13) + Chr(10);
AStream.Seek(AStream.Size,soFromBeginning);
AStream.WriteBuffer(WorkBuffer[1],Length(WorkBuffer));
end;
{==============================================================================}
{==============================================================================}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
{}
FSource:='';
FDest:='';
FStandalone:=False;
FName:=DefaultName;
FOffset:=0;
FSize:=0;
end;
{==============================================================================}
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
{}
end;
{==============================================================================}
procedure TfrmMain.FormShow(Sender: TObject);
var
Scale:Double;
begin
{}
txtSource.Text:=FSource;
txtDest.Text:=FDest;
chkStandalone.Checked:=FStandalone;
txtName.Text:=FName;
txtOffset.Text:=IntToStr(FOffset);
txtSize.Text:=IntToStr(FSize);
{Adjust Labels}
lblSource.Top:=txtSource.Top + ((txtSource.Height - lblSource.Height) div 2);
lblDest.Top:=txtDest.Top + ((txtDest.Height - lblDest.Height) div 2);
lblName.Top:=txtName.Top + ((txtName.Height - lblName.Height) div 2);
lblOffset.Top:=txtOffset.Top + ((txtOffset.Height - lblOffset.Height) div 2);
lblSize.Top:=txtSize.Top + ((txtSize.Height - lblSize.Height) div 2);
lblSize2.Top:=txtSize.Top + ((txtSize.Height - lblSize2.Height) div 2);
{Adjust Buttons}
if txtSource.Height > cmdSource.Height then
begin
cmdSource.Height:=txtSource.Height;
cmdSource.Width:=txtSource.Height;
cmdSource.Top:=txtSource.Top + ((txtSource.Height - cmdSource.Height) div 2);
end
else
begin
cmdSource.Height:=txtSource.Height + 2;
cmdSource.Width:=txtSource.Height + 2;
cmdSource.Top:=txtSource.Top - 1;
end;
if txtDest.Height > cmdDest.Height then
begin
cmdDest.Height:=txtDest.Height;
cmdDest.Width:=txtDest.Height;
cmdDest.Top:=txtDest.Top + ((txtDest.Height - cmdDest.Height) div 2);
end
else
begin
cmdDest.Height:=txtDest.Height + 2;
cmdDest.Width:=txtDest.Height + 2;
cmdDest.Top:=txtDest.Top - 1;
end;
if cmdSource.Height > cmdConvert.Height then
begin
cmdConvert.Height:=cmdSource.Height;
cmdExit.Height:=cmdSource.Height;
end;
{Check PixelsPerInch}
if PixelsPerInch > 96 then
begin
{Calculate Scale}
Scale:=(PixelsPerInch / 96);
{Disable Anchors (Not required for dialogs)}
{txtSource.Anchors:=[akLeft,akTop];
cmdSource.Anchors:=[akLeft,akTop];
txtDest.Anchors:=[akLeft,akTop];
cmdDest.Anchors:=[akLeft,akTop];
txtName.Anchors:=[akLeft,akTop];
cmdConvert.Anchors:=[akLeft,akTop];
cmdExit.Anchors:=[akLeft,akTop];}
{Resize Form (Not required for dialogs)}
{Width:=Trunc(Width * Scale);
Height:=Trunc(Height * Scale);}
{Adjust Buttons}
{cmdSource.Top:=txtSource.Top;
cmdSource.Height:=txtSource.Height;
cmdSource.Width:=cmdSource.Height;
cmdDest.Top:=txtDest.Top;
cmdDest.Height:=txtDest.Height;
cmdDest.Width:=cmdDest.Height;}
{Enable Anchors (Not required for dialogs)}
{txtSource.Anchors:=[akLeft,akTop,akRight];
cmdSource.Anchors:=[akTop,akRight];
txtDest.Anchors:=[akLeft,akTop,akRight];
cmdDest.Anchors:=[akTop,akRight];
txtName.Anchors:=[akLeft,akTop,akRight];
cmdConvert.Anchors:=[akRight,akBottom];
cmdExit.Anchors:=[akRight,akBottom];}
end;
end;
{==============================================================================}
procedure TfrmMain.FormHide(Sender: TObject);
begin
{}
end;
{==============================================================================}
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{}
end;
{==============================================================================}
{==============================================================================}
procedure TfrmMain.txtSourceChange(Sender: TObject);
begin
{}
FSource:=txtSource.Text;
end;
{==============================================================================}
procedure TfrmMain.cmdSourceClick(Sender: TObject);
begin
{}
openMain.FileName:=FSource;
openMain.InitialDir:=ExtractFileDir(Application.ExeName);
{$IFDEF WINDOWS}
openMain.Filter:='All Files (*.*)|*.*';
{$ENDIF}
{$IFDEF LINUX}
openMain.Filter:='All Files (*.*)|*';
{$ENDIF}
if openMain.Execute then
begin
txtSource.Text:=openMain.FileName;
end;
end;
{==============================================================================}
procedure TfrmMain.txtDestChange(Sender: TObject);
begin
{}
FDest:=txtDest.Text;
end;
{==============================================================================}
procedure TfrmMain.cmdDestClick(Sender: TObject);
begin
{}
saveMain.FileName:=FDest;
saveMain.InitialDir:=ExtractFileDir(Application.ExeName);
{$IFDEF WINDOWS}
saveMain.Filter:='All Files (*.*)|*.*';
{$ENDIF}
{$IFDEF LINUX}
saveMain.Filter:='All Files (*.*)|*';
{$ENDIF}
if saveMain.Execute then
begin
txtDest.Text:=saveMain.FileName;
end;
end;
{==============================================================================}
procedure TfrmMain.chkStandaloneClick(Sender: TObject);
begin
{}
FStandalone:=chkStandalone.Checked;
end;
{==============================================================================}
procedure TfrmMain.txtNameChange(Sender: TObject);
begin
{}
FName:=txtName.Text;
end;
{==============================================================================}
procedure TfrmMain.txtOffsetChange(Sender: TObject);
begin
{}
try
FOffset:=StrToInt(txtOffset.Text);
except
txtOffset.Text:=IntToStr(FOffset);
end;
end;
{==============================================================================}
procedure TfrmMain.txtSizeChange(Sender: TObject);
begin
{}
try
FSize:=StrToInt(txtSize.Text);
except
txtSize.Text:=IntToStr(FSize);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdConvertClick(Sender: TObject);
begin
{}
if Convert then
begin
MessageDlg('Conversion Successful',mtInformation,[mbOk],0);
end
else
begin
MessageDlg('Conversion Failed',mtInformation,[mbOk],0);
end;
end;
{==============================================================================}
procedure TfrmMain.cmdExitClick(Sender: TObject);
begin
{}
Application.Terminate;
end;
{==============================================================================}
{==============================================================================}
end.
|
unit Loader;
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, Buttons,
UniDacVcl, Variants,
{$IFDEF FPC}
LResources,
{$ENDIF}
DB, UniLoader, UniScript, DBAccess, Uni, Fetch, DALoader, DemoFrame,
UniDacDemoForm, DAScript, {$IFNDEF FPC}MemDS{$ELSE}MemDataSet{$ENDIF};
type
TLoaderFrame = class(TDemoFrame)
DBGrid: TDBGrid;
DataSource: TDataSource;
ToolBar: TPanel;
btOpen: TSpeedButton;
DBNavigator: TDBNavigator;
btClose: TSpeedButton;
Query: TUniQuery;
btLoad: TSpeedButton;
UniLoader: TUniLoader;
btDeleteAll: TSpeedButton;
Panel1: TPanel;
rgEvent: TRadioGroup;
edRows: TEdit;
Label1: TLabel;
Panel2: TPanel;
procedure btOpenClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure btLoadClick(Sender: TObject);
procedure GetColumnData(Sender: TObject; Column: TDAColumn;
Row: Integer; var Value: Variant; var EOF: Boolean);
procedure btDeleteAllClick(Sender: TObject);
procedure QueryAfterOpen(DataSet: TDataSet);
procedure QueryBeforeClose(DataSet: TDataSet);
procedure PutData(Sender: TDALoader);
procedure rgEventClick(Sender: TObject);
procedure QueryBeforeFetch(DataSet: TCustomDADataSet;
var Cancel: Boolean);
procedure QueryAfterFetch(DataSet: TCustomDADataSet);
private
{ Private declarations }
public
procedure Initialize; override;
procedure SetDebug(Value: boolean); override;
destructor Destroy; override;
end;
implementation
{$IFNDEF FPC}
{$IFDEF CLR}
{$R *.nfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{$ENDIF}
destructor TLoaderFrame.Destroy;
begin
inherited;
FreeAndNil(FetchForm);
end;
procedure TLoaderFrame.btOpenClick(Sender: TObject);
begin
Query.Open;
end;
procedure TLoaderFrame.btCloseClick(Sender: TObject);
begin
Query.Close;
end;
procedure TLoaderFrame.btLoadClick(Sender: TObject);
{$IFNDEF LINUX}
var
Start, Finish: Int64;
{$ENDIF}
begin
{$IFNDEF LINUX}
Start := GetTickCount;
{$ENDIF}
UniLoader.Load; // loading rows
{$IFNDEF LINUX}
Finish := GetTickCount;
UniDacForm.StatusBar.Panels[2].Text := 'Time: ' + FloatToStr((Finish - Start) / 1000) + ' sec.';
{$ENDIF}
if Query.Active then
Query.Refresh;
end;
procedure TLoaderFrame.GetColumnData(Sender: TObject;
Column: TDAColumn; Row: Integer; var Value: Variant; var EOF: Boolean);
begin
case Column.Index of
0: Value := Row;
1: Value := Random*100;
2: Value := 'abc01234567890123456789';
3: Value := Date;
else
Value := Null;
end;
EOF := Row > StrToInt(edRows.Text);
end;
procedure TLoaderFrame.PutData(Sender: TDALoader);
var
Count: integer;
i: integer;
begin
Count := StrToInt(edRows.Text);
for i := 1 to Count do begin
Sender.PutColumnData(0, i, i);
Sender.PutColumnData('DBL', i, Random*100);
//Sender.PutColumnData(1, i, Random*100);
Sender.PutColumnData(2, i, 'abc01234567890123456789');
Sender.PutColumnData(3, i, Date);
end;
end;
procedure TLoaderFrame.btDeleteAllClick(Sender: TObject);
begin
Query.Connection.ExecSQL('DELETE FROM UniDAC_Loaded', []);
if Query.Active then
Query.Refresh;
end;
procedure TLoaderFrame.QueryAfterOpen(DataSet: TDataSet);
begin
UniDacForm.StatusBar.Panels[1].Text := 'RecordCount: ' + IntToStr(DataSet.RecordCount);
end;
procedure TLoaderFrame.QueryBeforeClose(DataSet: TDataSet);
begin
UniDacForm.StatusBar.Panels[1].Text := '';
end;
procedure TLoaderFrame.Initialize;
begin
inherited;
Query.Connection := Connection as TUniConnection;
rgEvent.ItemIndex := 1;
if FetchForm = nil then
FetchForm := TFetchForm.Create(UniDacForm);
end;
procedure TLoaderFrame.rgEventClick(Sender: TObject);
begin
if rgEvent.ItemIndex = 0 then begin
UniLoader.OnGetColumnData := GetColumnData;
UniLoader.OnPutData := nil;
end
else begin
UniLoader.OnGetColumnData := nil;
UniLoader.OnPutData := PutData;
end
end;
procedure TLoaderFrame.QueryBeforeFetch(DataSet: TCustomDADataSet;
var Cancel: Boolean);
begin
if DataSet.FetchingAll then begin
FetchForm.Show;
Application.ProcessMessages;
Cancel := not FetchForm.Visible;
if Cancel then
UniDacForm.StatusBar.Panels[1].Text := 'RecordCount: ' + IntToStr(DataSet.RecordCount);
end;
end;
procedure TLoaderFrame.QueryAfterFetch(DataSet: TCustomDADataSet);
begin
if not DataSet.FetchingAll then begin
FetchForm.Close;
Application.ProcessMessages;
UniDacForm.StatusBar.Panels[1].Text := 'RecordCount: ' + IntToStr(DataSet.RecordCount);
end;
end;
procedure TLoaderFrame.SetDebug(Value: boolean);
begin
Query.Debug := Value;
end;
initialization
{$IFDEF FPC}
{$I Loader.lrs}
{$ENDIF}
end.
|
{: GLUserShader<p>
A shader that passes control of the DoApply and DoUnApply
methods through published events. This component is
designed to make it a little easier to implement a
customized shader. Be sure to keep the shader balanced
by returning the OpenGL state to how you found it.<p>
<b>History : </b><font size=-1><ul>
<li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>05/08/03 - SG - Creation
</ul></font>
}
unit GLUserShader;
interface
uses
Classes, GLMaterial, GLRenderContextInfo;
type
TOnDoApplyEvent = procedure (Sender : TObject; var rci : TRenderContextInfo) of Object;
TOnDoUnApplyEvent = procedure (Sender : TObject; Pass:Integer; var rci : TRenderContextInfo; var Continue : Boolean) of Object;
TGLUserShader = class(TGLShader)
private
FPass : Integer;
FOnDoApply : TOnDoApplyEvent;
FOnDoUnApply : TOnDoUnApplyEvent;
protected
procedure DoApply(var rci : TRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci : TRenderContextInfo) : Boolean; override;
published
property OnDoApply : TOnDoApplyEvent read FOnDoApply write FOnDoApply;
property OnDoUnApply : TOnDoUnApplyEvent read FOnDoUnApply write FOnDoUnApply;
property ShaderStyle;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLUserShader ------------------
// ------------------
// DoApply
//
procedure TGLUserShader.DoApply(var rci: TRenderContextInfo; Sender : TObject);
begin
FPass:=1;
if Assigned(FOnDoApply) and (not (csDesigning in ComponentState)) then
FOnDoApply(Self,rci);
end;
// DoUnApply
//
function TGLUserShader.DoUnApply(var rci: TRenderContextInfo): Boolean;
begin
Result:=False;
if Assigned(FOnDoUnApply) and (not (csDesigning in ComponentState)) then begin
FOnDoUnApply(Self,FPass,rci,Result);
Inc(FPass);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX_Types3D;
{$I FMX_Defines.inc}
interface
uses
Classes, Types, UITypes, FMX_Types;
{$SCOPEDENUMS ON}
const
MaxBitmapSize: Integer = 2048;
MaxLights: Integer = 8;
DefaultAmbient: TAlphaColor = $FF202020;
DefaultDiffuse: TAlphaColor = $FFFFFFFF;
DefaultSpecular: TAlphaColor = $FF606060;
DefaultShininess = 30;
{ Points and rects }
type
TPoint3D = record
X: Single;
Y: Single;
Z: Single;
end;
PPoint3D = ^TPoint3D;
TBox = record
Left, Top, Near, Right, Bottom, Far: Single;
end;
TVector3DType = array [0..3] of Single;
PVector3D = ^TVector3D;
TVector3D = record
case Integer of
0: (V: TVector3DType;);
1: (X: Single;
Y: Single;
Z: Single;
W: Single;);
end;
PVector3DArray = ^TVector3DArray;
TVector3DArray = array [0 .. 0 shr 2] of TVector3D;
TMatrix3DType = array [0..3] of TVector3D;
TMatrix3D = record
case Integer of
0: (M: TMatrix3DType;);
1: (m11, m12, m13, m14: Single;
m21, m22, m23, m24: Single;
m31, m32, m33, m34: Single;
m41, m42, m43, m44: Single);
end;
PQuaternion3D = ^TQuaternion3D;
TQuaternion3D = record
ImagPart: TVector3D;
RealPart: Single;
end;
TMatrix3DDynArray = array of TMatrix3D;
TPoint3DDynArray = array of TPoint3D;
TPointFDynArray = array of TPointF;
const
IdentityQuaternion: TQuaternion3D = (ImagPart: (X: 0; Y: 0; Z: 0; W: 0); RealPart: 1);
IdentityMatrix3D: TMatrix3D = (m11: 1.0; m12: 0.0; m13: 0.0; m14: 0.0; m21: 0.0; m22: 1.0;
m23: 0.0; m24: 0.0; m31: 0.0; m32: 0.0; m33: 1.0; m34: 0.0; m41: 0.0; m42: 0.0; m43: 0.0; m44: 1.0;);
XHmgVector: TVector3D = (X: 1; Y: 0; Z: 0; W: 0);
YHmgVector: TVector3D = (X: 0; Y: 1; Z: 0; W: 0);
ZHmgVector: TVector3D = (X: 0; Y: 0; Z: 1; W: 0);
WHmgVector: TVector3D = (X: 0; Y: 0; Z: 0; W: 1);
XYHmgVector: TVector3D = (X: 1; Y: 1; Z: 0; W: 0);
XYZHmgVector: TVector3D = (X: 1; Y: 1; Z: 1; W: 0);
XYZWHmgVector: TVector3D = (X: 1; Y: 1; Z: 1; W: 1);
NullVector3D: TVector3D = (X: 0; Y: 0; Z: 0; W: 1);
NullPoint3D: TPoint3D = (X: 0; Y: 0; Z: 0);
type
TContext3D = class;
TViewport3D = class;
TControl3D = class;
TCamera = class;
TLight = class;
TDummy = class;
TVertexBuffer = class;
TIndexBuffer = class;
IViewport3D = interface
['{EF9EE200-8CF4-438E-A598-5601083E6EA2}']
function GetObject: TFmxObject;
function GetContext: TContext3D;
function GetScene: IScene;
function GetDesignCamera: TCamera;
procedure SetDesignCamera(const ACamera: TCamera);
function ScreenToLocal(P: TPointF): TPointF;
function LocalToScreen(P: TPointF): TPointF;
procedure NeedRender;
{ access }
property DesignCamera: TCamera read GetDesignCamera write SetDesignCamera;
property Scene: IScene read GetScene;
property Context: TContext3D read GetContext;
end;
{ TPosition3D }
TPosition3D = class(TPersistent)
private
FOnChange: TNotifyEvent;
FSave: TVector3D;
FY: Single;
FX: Single;
FZ: Single;
FDefaultValue: TPoint3D;
FOnChangeY: TNotifyEvent;
FOnChangeX: TNotifyEvent;
FOnChangeZ: TNotifyEvent;
procedure SetPoint3D(const Value: TPoint3D);
procedure SetX(const Value: Single);
procedure SetY(const Value: Single);
procedure SetZ(const Value: Single);
function GetPoint3D: TPoint3D;
function GetVector: TVector3D;
procedure SetVector(const Value: TVector3D);
protected
procedure DefineProperties(Filer: TFiler); override;
procedure ReadPoint(Reader: TReader);
procedure WritePoint(Writer: TWriter);
public
constructor Create(const ADefaultValue: TPoint3D); virtual;
procedure Assign(Source: TPersistent); override;
procedure SetPoint3DNoChange(const P: TPoint3D);
procedure SetVectorNoChange(const P: TVector3D);
function Empty: Boolean;
property Point: TPoint3D read GetPoint3D write SetPoint3D;
property Vector: TVector3D read GetVector write SetVector;
property DefaultValue: TPoint3D read FDefaultValue write FDefaultValue;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChangeX: TNotifyEvent read FOnChangeX write FOnChangeX;
property OnChangeY: TNotifyEvent read FOnChangeY write FOnChangeY;
property OnChangeZ: TNotifyEvent read FOnChangeZ write FOnChangeZ;
published
property X: Single read FX write SetX stored False;
property Y: Single read FY write SetY stored False;
property Z: Single read FZ write SetZ stored False;
end;
{ TMeshData }
TMeshVertex = packed record
x, y, z: single;
nx, ny, nz: single;
tu, tv: single;
end;
TMeshData = class(TPersistent)
private
FVertexBuffer: TVertexBuffer;
FIndexBuffer: TIndexBuffer;
FOnChanged: TNotifyEvent;
FRecalcBounds: Boolean;
FSize: TPoint3D;
function GetNormals: AnsiString;
function GetPoint3Ds: AnsiString;
function GetTexCoordinates: AnsiString;
procedure SetNormals(const Value: AnsiString);
procedure SetPoint3Ds(const Value: AnsiString);
procedure SetTexCoordinates(const Value: AnsiString);
function GetTriangleIndices: AnsiString;
procedure SetTriangleIndices(const Value: AnsiString);
protected
procedure Assign(Source: TPersistent); override;
procedure DefineProperties(Filer: TFiler); override;
procedure ReadMesh(Stream: TStream);
procedure WriteMesh(Stream: TStream);
public
constructor Create; virtual;
procedure AssignFromMeshVertex(const Vertices: array of TMeshVertex; const Indices: array of Word);
destructor Destroy; override;
procedure Clear;
procedure CalcNormals;
function RayCastIntersect(const Width, Height, Depth: single; const RayPos, RayDir: TVector3D;
var Intersection: TVector3D): Boolean;
property VertexBuffer: TVertexBuffer read FVertexBuffer;
property IndexBuffer: TIndexBuffer read FIndexBuffer;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
published
property Normals: AnsiString read GetNormals write SetNormals stored False;
property Points: AnsiString read GetPoint3Ds write SetPoint3Ds stored False;
property TexCoordinates: AnsiString read GetTexCoordinates write SetTexCoordinates stored False;
property TriangleIndices: AnsiString read GetTriangleIndices write SetTriangleIndices stored False;
end;
{ TMaterial }
TTextureMode = (tmModulate, tmReplace);
TTextureFiltering = (tfNearest, tfLinear);
TShadeMode = (smFlat, smGouraud);
TFillMode = (fmSolid, fmWireframe);
TMaterial = class(TPersistent)
private
FOnChanged: TNotifyEvent;
FDiffuse: TAlphaColor;
FAmbient: TAlphaColor;
FModulation: TTextureMode;
FLighting: Boolean;
FShadeMode: TShadeMode;
FFillMode: TFillMode;
FSpecular: TAlphaColor;
FEmissive: TAlphaColor;
FTexture: TBitmap;
FShininess: Integer;
FTextureFiltering: TTextureFiltering;
procedure SetDiffuse(const Value: TAlphaColor);
procedure SetAmbient(const Value: TAlphaColor);
procedure SetModulation(const Value: TTextureMode);
procedure SetLighting(const Value: Boolean);
procedure SetShadeMode(const Value: TShadeMode);
procedure SetFillMode(const Value: TFillMode);
procedure SetSpecular(const Value: TAlphaColor);
procedure SetEmissive(const Value: TAlphaColor);
function IsAmbientStored: Boolean;
function IsDiffuseStored: Boolean;
function IsEmissiveStored: Boolean;
function IsSpecularStored: Boolean;
procedure SetTexture(const Value: TBitmap);
procedure DoTextureChanged(Sender: TObject);
procedure SetShininess(const Value: Integer);
procedure SetTextureFiltering(const Value: TTextureFiltering);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
published
property Diffuse: TAlphaColor read FDiffuse write SetDiffuse stored IsDiffuseStored;
property Ambient: TAlphaColor read FAmbient write SetAmbient stored IsAmbientStored;
property Emissive: TAlphaColor read FEmissive write SetEmissive stored IsEmissiveStored;
property Specular: TAlphaColor read FSpecular write SetSpecular stored IsSpecularStored;
property Lighting: Boolean read FLighting write SetLighting default True;
property FillMode: TFillMode read FFillMode write SetFillMode default TFillMode.fmSolid;
property Modulation: TTextureMode read FModulation write SetModulation default TTextureMode.tmModulate;
property Texture: TBitmap read FTexture write SetTexture;
property TextureFiltering: TTextureFiltering read FTextureFiltering write SetTextureFiltering default TTextureFiltering.tfLinear;
property ShadeMode: TShadeMode read FShadeMode write SetShadeMode default TShadeMode.smGouraud;
property Shininess: Integer read FShininess write SetShininess default DefaultShininess;
end;
{ TVertexBuffer }
TVertexFormat = (
vfVertex,
vfNormal,
vfDiffuse,
vfSpecular,
vfTexCoord0,
vfTexCoord1,
vfTexCoord2,
vfTexCoord3
);
TVertexFormats = set of TVertexFormat;
TVertexBuffer = class(TPersistent)
private
FBuffer: Pointer;
FFormat: TVertexFormats;
FLength: Integer;
FSize: Integer;
FVertexSize: Integer;
FTexCoord0: Integer;
FTexCoord1: Integer;
FTexCoord2: Integer;
FTexCoord3: Integer;
FDiffuse: Integer;
FSpecular: Integer;
FNormal: Integer;
function GetVertices(AIndex: Integer): TPoint3D;
function GetTexCoord0(AIndex: Integer): TPointF;
function GetDiffuse(AIndex: Integer): TAlphaColor;
function GetNormals(AIndex: Integer): TPoint3D;
function GetSpecular(AIndex: Integer): TAlphaColor;
function GetTexCoord1(AIndex: Integer): TPointF;
function GetTexCoord2(AIndex: Integer): TPointF;
function GetTexCoord3(AIndex: Integer): TPointF;
procedure SetVertices(AIndex: Integer; const Value: TPoint3D); inline;
procedure SetDiffuse(AIndex: Integer; const Value: TAlphaColor); inline;
procedure SetNormals(AIndex: Integer; const Value: TPoint3D); inline;
procedure SetSpecular(AIndex: Integer; const Value: TAlphaColor); inline;
procedure SetTexCoord0(AIndex: Integer; const Value: TPointF); inline;
procedure SetTexCoord1(AIndex: Integer; const Value: TPointF); inline;
procedure SetTexCoord2(AIndex: Integer; const Value: TPointF); inline;
procedure SetTexCoord3(AIndex: Integer; const Value: TPointF); inline;
procedure SetLength(const Value: Integer);
protected
procedure Assign(Source: TPersistent); override;
public
constructor Create(const AFormat: TVertexFormats; const ALength: Integer); virtual;
destructor Destroy; override;
property Buffer: Pointer read FBuffer;
property Size: Integer read FSize;
property VertexSize: Integer read FVertexSize;
property Length: Integer read FLength write SetLength;
property Format: TVertexFormats read FFormat;
{ items access }
property Vertices[AIndex: Integer]: TPoint3D read GetVertices write SetVertices;
property Normals[AIndex: Integer]: TPoint3D read GetNormals write SetNormals;
property Diffuse[AIndex: Integer]: TAlphaColor read GetDiffuse write SetDiffuse;
property Specular[AIndex: Integer]: TAlphaColor read GetSpecular write SetSpecular;
property TexCoord0[AIndex: Integer]: TPointF read GetTexCoord0 write SetTexCoord0;
property TexCoord1[AIndex: Integer]: TPointF read GetTexCoord1 write SetTexCoord1;
property TexCoord2[AIndex: Integer]: TPointF read GetTexCoord2 write SetTexCoord2;
property TexCoord3[AIndex: Integer]: TPointF read GetTexCoord3 write SetTexCoord3;
end;
{ TIndexBuffer }
TIndexBuffer = class(TPersistent)
private
FBuffer: Pointer;
FLength: Integer;
FSize: Integer;
function GetIndices(AIndex: Integer): Integer; inline;
procedure SetIndices(AIndex: Integer; const Value: Integer); inline;
procedure SetLength(const Value: Integer);
protected
procedure Assign(Source: TPersistent); override;
public
constructor Create(const ALength: Integer); virtual;
destructor Destroy; override;
property Buffer: Pointer read FBuffer;
property Size: Integer read FSize;
property Length: Integer read FLength write SetLength;
{ items access }
property Indices[AIndex: Integer]: Integer read GetIndices write SetIndices; default;
end;
TProjection = (pjCamera, pjScreen);
TMultisample = (msNone, ms2Samples, ms4Samples);
TClearTarget = (ctColor, ctDepth, ctStencil);
TClearTargets = set of TClearTarget;
TStencilOp = (
soKeep,
soZero,
soReplace,
soIncrease,
soDecrease,
soInvert
);
TStencilFunc = (
sfNever,
sfLess,
sfLequal,
sfGreater,
fsGequal,
sfEqual,
sfNotEqual,
sfAlways
);
TMaterialColor = (
mcDiffuse,
mcAmbient,
mcSpecular,
mcEmissive
);
{ TContext3D }
TContextState = (
// 2D screen matrix
cs2DScene,
// 3D camera matrix
cs3DScene,
// Lights
csLightOn, csLightOff,
// Depth
csZTestOn, csZTestOff,
csZWriteOn, csZWriteOff,
// Alpha Blending
csAlphaTestOn, csAlphaTestOff,
csAlphaBlendOn, csAlphaBlendOff,
// Stencil
csStencilOn, csStencilOff,
// Color
csColorWriteOn, csColorWriteOff,
// Faces
csFrontFace, csBackFace, csAllFace,
// Blending mode
csBlendAdditive, csBlendNormal,
// Tex stretch
csTexNearest, csTexLinear,
// Tex modulation
csTexDisable, csTexReplace, csTexModulate,
// fill mode
csFrame, csSolid,
// shade mode
csFlat, csGouraud
);
TContextShader = type THandle;
TContext3D = class(TInterfacedPersistent, IFreeNotification)
private
FBeginSceneCount: integer;
protected
FParent: TFmxHandle;
FWidth, FHeight: Integer;
FBitmap: TBitmap;
FViewport: TViewport3D;
FBitmaps: TList;
{ buffer }
FBuffered: Boolean;
FBufferBits: Pointer;
FBufferHandle: THandle;
{ style }
FMultisample: TMultisample;
FDepthStencil: Boolean;
{ lights }
FLights: TList;
{ states }
FCurrentStates: array [TContextState] of Boolean;
FCurrentCamera: TCamera;
FCurrentCameraMatrix: TMatrix3D;
FCurrentCameraInvMatrix: TMatrix3D;
FCurrentMatrix: TMatrix3D;
FCurrentDiffuse: TAlphaColor;
FCurrentSpecular: TAlphaColor;
FCurrentAmbient: TAlphaColor;
FCurrentEmissive: TAlphaColor;
FCurrentOpacity: Single;
FCurrentShininess: Integer;
FCurrentColoredVertices: Boolean;
FCurrentVS: TContextShader;
FCurrentPS: TContextShader;
{ paintto }
FPaintToMatrix: TMatrix3D;
{ default shaders }
FDefaultVS_NoLight: TContextShader;
FDefaultVS_1Light: TContextShader;
FDefaultVS_2Light: TContextShader;
FDefaultVS_3Light: TContextShader;
FDefaultVS_4Light: TContextShader;
FDefaultVS_Full: TContextShader;
FDefaultPS: TContextShader;
procedure ApplyContextState(AState: TContextState); virtual; abstract;
function GetProjectionMatrix: TMatrix3D; virtual;
function GetScreenMatrix: TMatrix3D; virtual;
function GetPixelToPixelPolygonOffset: TPointF; virtual;
{ TPersistent }
procedure AssignTo(Dest: TPersistent); override;
procedure AssignToBitmap(Dest: TBitmap); virtual; abstract;
{ IFreeNotification }
procedure FreeNotification(AObject: TObject);
{ Bitmap }
procedure UpdateBitmapHandle(ABitmap: TBitmap); virtual; abstract;
procedure DestroyBitmapHandle(ABitmap: TBitmap); virtual; abstract;
{ validation }
function GetValid: Boolean; virtual; abstract;
{ shader params }
procedure SetParams;
procedure CreateDefaultShaders;
procedure FreeDefaultShaders;
function DoBeginScene: Boolean; virtual;
procedure DoEndScene(const CopyTarget: Boolean = True); virtual;
public
{ Don't call contructor directly from TContext3D - only using DefaultContextClass variable }
constructor CreateFromWindow(const AParent: TFmxHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean); virtual;
constructor CreateFromBitmap(const ABitmap: TBitmap; const AMultisample: TMultisample;
const ADepthStencil: Boolean); virtual;
destructor Destroy; override;
procedure SetMultisample(const Multisample: TMultisample); virtual;
procedure SetSize(const AWidth, AHeight: Integer);
{ buffer }
procedure FreeBuffer; virtual;
procedure Resize; virtual; abstract;
procedure CreateBuffer; virtual;
{ lights }
procedure AddLight(const ALight: TLight);
procedure DeleteLight(const ALight: TLight);
{ rendering }
procedure ResetScene; // default settings
function BeginScene: Boolean;
procedure EndScene(const CopyTarget: Boolean = True);
property BeginSceneCount: integer read FBeginSceneCount;
{ low-level - must be overrided }
procedure Clear(const ATarget: TClearTargets; const AColor: TAlphaColor; const ADepth: single; const AStencil: Cardinal); virtual; abstract;
procedure SetCamera(const Camera: TCamera); virtual;
procedure SetColor(const AMaterialColor: TMaterialColor; AColor: TAlphaColor); virtual;
procedure SetMatrix(const M: TMatrix3D); virtual;
procedure SetContextState(const State: TContextState); virtual;
procedure SetStencilOp(const Fail, ZFail, ZPass: TStencilOp); virtual; abstract;
procedure SetStencilFunc(const Func: TStencilfunc; Ref, Mask: cardinal); virtual; abstract;
procedure SetTextureMatrix(const AUnit: Integer; const AMatrix: TMatrix); virtual; abstract;
procedure SetTextureUnit(const AUnit: Integer; const ABitmap: TBitmap); virtual; abstract;
procedure SetTextureUnitFromContext(const AUnit: Integer; const ARect: PRectF = nil); virtual; abstract;
procedure DrawTrianglesList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
procedure DrawTrianglesStrip(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
procedure DrawTrianglesFan(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
procedure DrawLinesList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
procedure DrawLinesStrip(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
procedure DrawPointsList(const Vertices: TVertexBuffer; const Indices: TIndexBuffer; const Opacity: Single); virtual; abstract;
{ vertex shaders }
function CreateVertexShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader; virtual; abstract;
procedure DestroyVertexShader(const Shader: TContextShader); virtual; abstract;
procedure SetVertexShader(const Shader: TContextShader); virtual; abstract;
procedure SetVertexShaderVector(Index: Integer; const V: TVector3D); virtual; abstract;
procedure SetVertexShaderMatrix(Index: Integer; const M: TMatrix3D); virtual; abstract;
{ pixel shaders }
function CreatePixelShader(DXCode, ARBCode, GLSLCode: Pointer): TContextShader; virtual; abstract;
procedure DestroyPixelShader(const Shader: TContextShader); virtual; abstract;
procedure SetPixelShader(const Shader: TContextShader); virtual; abstract;
procedure SetPixelShaderVector(Index: Integer; const V: TVector3D); virtual; abstract;
procedure SetPixelShaderMatrix(Index: Integer; const M: TMatrix3D); virtual; abstract;
{ pick }
procedure Pick(X, Y: Single; const AProj: TProjection; var RayPos, RayDir: TVector3D);
function WorldToScreen(const AProj: TProjection; const P: TPoint3D): TPoint3D;
{ high-level - implemented in TContext3D }
{ drawing }
procedure SetMaterial(const AMaterial: TMaterial);
procedure DrawLine(const StartPoint, EndPoint: TVector3D; const Opacity: Single);
procedure DrawCube(const Center, Size: TVector3D; const Opacity: Single);
procedure FillCube(const Center, Size: TVector3D; const Opacity: Single);
procedure FillMesh(const Center, Size: TVector3D; const MeshData: TMeshData; const Opacity: Single);
{ pseudo 2D }
procedure FillPolygon(const Center, Size: TVector3D; const Rect: TRectF; const Points: TPolygon;
const Opacity: Single; Front: Boolean = True; Back: Boolean = True; Left: Boolean = True);
procedure FillRect(const Rect: TRectF; const Depth, Opacity: Single);
{ acces }
property CurrentMatrix: TMatrix3D read FCurrentMatrix;
property CurrentCamera: TCamera read FCurrentCamera;
property CurrentCameraMatrix: TMatrix3D read FCurrentCameraMatrix;
property CurrentCameraInvMatrix: TMatrix3D read FCurrentCameraInvMatrix;
property CurrentPojectionMatrix: TMatrix3D read GetProjectionMatrix;
property CurrentScreenMatrix: TMatrix3D read GetScreenMatrix;
property PixelToPixelPolygonOffset: TPointF read GetPixelToPixelPolygonOffset;
property Height: Integer read FHeight;
property Width: Integer read FWidth;
{ internal usage }
// Window handle ( for example HWnd )
property Parent: TFmxHandle read FParent write FParent;
// Buffer if exists
property Buffered: Boolean read FBuffered;
property BufferBits: Pointer read FBufferBits;
property BufferHandle: THandle read FBufferHandle; // HDC
{ Is this a valid/active context? }
property Valid: Boolean read GetValid;
end;
{ TControl3D }
TContext3DClass = class of TContext3D;
TMouseEvent3D = procedure(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single;
RayPos, RayDir: TVector3D) of object;
TMouseMoveEvent3D = procedure(Sender: TObject; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D) of object;
TRenderEvent = procedure(Sender: TObject; Context: TContext3D) of object;
TDragEnterEvent3D = procedure(Sender: TObject; const Data: TDragObject; const Point: TPoint3D) of object;
TDragOverEvent3D = procedure(Sender: TObject; const Data: TDragObject; const Point: TPoint3D; var Accept: Boolean)
of object;
TDragDropEvent3D = procedure(Sender: TObject; const Data: TDragObject; const Point: TPoint3D) of object;
PObjectAtPointData = ^TObjectAtPointData;
TObjectAtPointData = record
Distance: single;
Projection: TProjection;
end;
TControl3D = class(TFmxObject, IControl)
private
FVisible: Boolean;
FOnMouseUp: TMouseEvent3D;
FOnMouseDown: TMouseEvent3D;
FOnMouseMove: TMouseMoveEvent3D;
FOnMouseWheel: TMouseWheelEvent;
FOnClick: TNotifyEvent;
FOnDblClick: TNotifyEvent;
FMouseInObject: Boolean;
FHitTest: Boolean;
FClipChildren: Boolean;
FAutoCapture: Boolean;
FLocked: Boolean;
FTempContext: TContext3D;
FPosition: TPosition3D;
FQuaternion: TQuaternion3D;
FRotationAngle: TPosition3D;
FScale: TPosition3D;
FSkew: TPosition3D;
FCanFocus: Boolean;
FIsMouseOver: Boolean;
FIsFocused: Boolean;
FRotationCenter: TPosition3D;
FOnKeyUp: TKeyEvent;
FOnKeyDown: TKeyEvent;
FOnRender: TRenderEvent;
FDesignVisible: Boolean;
FTwoSide: Boolean;
FDragMode: TDragMode;
FDisableDragHighlight: Boolean;
FOnDragEnter: TDragEnterEvent3D;
FOnDragDrop: TDragDropEvent3D;
FOnDragEnd: TNotifyEvent;
FOnDragLeave: TNotifyEvent;
FOnDragOver: TDragOverEvent3D;
FIsDragOver: Boolean;
FShowHint: Boolean;
FHint: WideString;
FPopupMenu: TPopup;
FPressed, FDoubleClick: Boolean;
FCursor: TCursor;
FShowContextMenu: Boolean;
FTabOrder: TTabOrder;
FAcceptsControls: boolean;
FOnMouseEnter: TNotifyEvent;
FOnMouseLeave: TNotifyEvent;
function GetInvertAbsoluteMatrix: TMatrix3D;
procedure SetHitTest(const Value: Boolean);
procedure SetClipChildren(const Value: Boolean);
function GetContext: TContext3D;
procedure SetLocked(const Value: Boolean);
procedure SetTempContext(const Value: TContext3D);
procedure SetOpacity(const Value: Single);
function IsOpacityStored: Boolean;
function GetAbsolutePosition: TVector3D;
function GetAbsoluteUp: TVector3D;
function GetAbsoluteDirection: TVector3D;
function GetAbsoluteLeft: TVector3D;
procedure SetAbsolutePosition(Value: TVector3D);
function GetScreenBounds: TRectF;
procedure ReadQuaternion(Reader: TReader);
procedure WriteQuaternion(Writer: TWriter);
procedure SetZWrite(const Value: Boolean);
procedure SetDesignVisible(const Value: Boolean);
procedure SetTabOrder(const Value: TTabOrder);
function GetTabOrder: TTabOrder;
function GetCursor: TCursor;
protected
FZWrite: Boolean;
FProjection: TProjection;
FViewport: IViewport3D;
FHeight, FLastHeight: Single;
FWidth, FLastWidth: Single;
FDepth, FLastDepth: Single;
FLocalMatrix: TMatrix3D;
FAbsoluteMatrix: TMatrix3D;
FInvAbsoluteMatrix: TMatrix3D;
FRecalcAbsolute: Boolean;
FDisableAlign: Boolean;
FCanResize, FCanRotate: Boolean;
FBody: Integer;
FDesignInteract: Boolean;
FDesignLocked: Boolean;
FOpacity, FAbsoluteOpacity: Single;
FRecalcOpacity: Boolean;
procedure Loaded; override;
procedure DefineProperties(Filer: TFiler); override;
function CheckHitTest(const AHitTest: Boolean): Boolean;
{ props }
procedure SetVisible(const Value: Boolean); virtual;
procedure SetHeight(const Value: Single); virtual;
procedure SetWidth(const Value: Single); virtual;
procedure SetDepth(const Value: Single); virtual;
procedure SetProjection(const Value: TProjection); virtual;
{ matrix }
function GetAbsoluteMatrix: TMatrix3D; virtual;
{ opacity }
function GetAbsoluteOpacity: Single; virtual;
procedure RecalcOpacity; virtual;
{ design }
procedure DesignSelect; virtual;
procedure DesignClick; virtual;
{ events }
procedure Capture;
procedure ReleaseCapture;
procedure MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); virtual;
procedure MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); virtual;
procedure MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D); virtual;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); virtual;
procedure KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); virtual;
procedure KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState); virtual;
procedure DialogKey(var Key: Word; Shift: TShiftState); virtual;
procedure Click; virtual;
procedure DblClick; virtual;
procedure ContextMenu(const ScreenPosition: TPoint3D); virtual;
procedure DragEnter(const Data: TDragObject; const Point: TPointF); virtual;
procedure DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean); virtual;
procedure DragDrop(const Data: TDragObject; const Point: TPointF); virtual;
procedure DragLeave; virtual;
procedure DragEnd; virtual;
{ IControl }
procedure DoMouseEnter; virtual;
procedure DoMouseLeave; virtual;
procedure DoEnter; virtual;
procedure DoExit; virtual;
function ObjectAtPoint(P: TPointF): IControl; virtual;
function GetObject: TFmxObject;
function GetVisible: Boolean;
function GetDesignInteractive: Boolean;
function AbsoluteToLocal(P: TPointF): TPointF;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure MouseMove(Shift: TShiftState; X, Y: Single);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
function GetTabOrderValue: TTabOrder;
procedure UpdateTabOrder(Value: TTabOrder);
function CheckForAllowFocus: Boolean;
function ScreenToLocal(P: TPointF): TPointF;
function LocalToScreen(P: TPointF): TPointF;
procedure BeginAutoDrag;
function GetDragMode: TDragMode;
procedure SetDragMode(const ADragMode: TDragMode);
function GetParent: TFmxObject;
function GetLocked: Boolean;
function GetHitTest: Boolean;
function GetAcceptsControls: boolean;
procedure SetAcceptsControls(const Value: boolean);
function FindTarget(P: TPointF; const Data: TDragObject): IControl; virtual;
{ paint }
procedure Apply; virtual;
procedure Render; virtual;
procedure RenderChildren; virtual;
procedure UnApply; virtual;
{ alignment }
procedure Resize3D; virtual;
{ changes }
procedure MatrixChanged(Sender: TObject); virtual;
procedure RotateXChanged(Sender: TObject); virtual;
procedure RotateYChanged(Sender: TObject); virtual;
procedure RotateZChanged(Sender: TObject); virtual;
{ props }
property MouseInObject: Boolean read FMouseInObject write FMouseInObject;
property Skew: TPosition3D read FSkew write FSkew;
property TempContext: TContext3D read FTempContext write SetTempContext;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddObject(AObject: TFmxObject); override;
procedure RemoveObject(AObject: TFmxObject); override;
procedure SetNewViewport(AViewport: IViewport3D); virtual;
{ Calculate best fit size using AWidth and AHeight, create TBitmap object and render to this bitmap. }
procedure PaintToBitmap(ABitmap: TBitmap; AWidth, AHeight: Integer; ClearColor: TAlphaColor;
AutoFit: Boolean = False; const AMultisample: TMultisample = TMultisample.msNone);
{ Create SuperSampled object's snapshot using tile-rendering and interpolation. Multisample can be 1..16 }
procedure CreateHighMultisampleSnapshot(ABitmap: TBitmap; AWidth, AHeight: Integer; ClearColor: TAlphaColor;
Multisample: Integer);
{ Create tile-part of snaphot. Tiles can be merge. }
procedure CreateTileSnapshot(ABitmap: TBitmap; AWidth, AHeight, OffsetX, OffsetY: Integer;
Scale: Single; ClearColor: TAlphaColor);
procedure CopyRotationFrom(const AObject: TControl3D);
procedure RecalcAbsolute; virtual;
function AbsoluteToLocal3D(P: TPoint3D): TPoint3D; virtual;
function LocalToAbsolute3D(P: TPoint3D): TPoint3D; virtual;
function AbsoluteToLocalVector(P: TVector3D): TVector3D; virtual;
function LocalToAbsoluteVector(P: TVector3D): TVector3D; virtual;
procedure SetSize(const AWidth, AHeight, ADepth: single);
function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; virtual;
procedure ResetRotationAngle;
procedure SetFocus;
procedure Repaint;
procedure Lock;
procedure DoRender;
property AbsoluteMatrix: TMatrix3D read GetAbsoluteMatrix;
property LocalMatrix: TMatrix3D read FLocalMatrix;
property AbsolutePosition: TVector3D read GetAbsolutePosition write SetAbsolutePosition;
property AbsoluteUp: TVector3D read GetAbsoluteUp;
property AbsoluteDirection: TVector3D read GetAbsoluteDirection;
property AbsoluteLeft: TVector3D read GetAbsoluteLeft;
property AbsoluteOpacity: Single read GetAbsoluteOpacity;
property InvertAbsoluteMatrix: TMatrix3D read GetInvertAbsoluteMatrix;
property Context: TContext3D read GetContext;
property DesignInteract: Boolean read FDesignInteract;
property AutoCapture: Boolean read FAutoCapture write FAutoCapture default False;
property RotationCenter: TPosition3D read FRotationCenter write FRotationCenter;
property ScreenBounds: TRectF read GetScreenBounds;
property CanFocus: Boolean read FCanFocus write FCanFocus;
property TabOrder: TTabOrder read GetTabOrder write SetTabOrder;
property DesignLocked: Boolean read FDesignLocked write FDesignLocked;
property DisableDragHighlight: Boolean read FDisableDragHighlight write FDisableDragHighlight default False;
property Hint: WideString read FHint write FHint;
property ShowHint: Boolean read FShowHint write FShowHint default False;
published
{ triggers }
property IsDragOver: Boolean read FIsDragOver;
property IsMouseOver: Boolean read FIsMouseOver;
property IsFocused: Boolean read FIsFocused;
property IsVisible: Boolean read FVisible;
{ props }
property Cursor: TCursor read GetCursor write FCursor default crDefault;
property DragMode: TDragMode read GetDragMode write SetDragMode default TDragMode.dmManual;
property DesignVisible: Boolean read FDesignVisible write SetDesignVisible default True;
property Position: TPosition3D read FPosition write FPosition;
property Scale: TPosition3D read FScale write FScale;
property RotationAngle: TPosition3D read FRotationAngle write FRotationAngle;
property Locked: Boolean read FLocked write SetLocked default False;
property Width: Single read FWidth write SetWidth;
property Height: Single read FHeight write SetHeight;
property Depth: Single read FDepth write SetDepth;
property Opacity: Single read FOpacity write SetOpacity stored IsOpacityStored;
property Projection: TProjection read FProjection write SetProjection default TProjection.pjCamera;
property HitTest: Boolean read FHitTest write SetHitTest default True;
// property Hint: WideString read FHint write FHint;
// property ShowHint: Boolean read FShowHint write FShowHint default False;
property ShowContextMenu: Boolean read FShowContextMenu write FShowContextMenu default True;
property TwoSide: Boolean read FTwoSide write FTwoSide default False;
property Visible: Boolean read FVisible write SetVisible default True;
property ZWrite: Boolean read FZWrite write SetZWrite default True;
property OnDragEnter: TDragEnterEvent3D read FOnDragEnter write FOnDragEnter;
property OnDragLeave: TNotifyEvent read FOnDragLeave write FOnDragLeave;
property OnDragOver: TDragOverEvent3D read FOnDragOver write FOnDragOver;
property OnDragDrop: TDragDropEvent3D read FOnDragDrop write FOnDragDrop;
property OnDragEnd: TNotifyEvent read FOnDragEnd write FOnDragEnd;
property OnClick: TNotifyEvent read FOnClick write FOnClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
property OnMouseDown: TMouseEvent3D read FOnMouseDown write FOnMouseDown;
property OnMouseMove: TMouseMoveEvent3D read FOnMouseMove write FOnMouseMove;
property OnMouseUp: TMouseEvent3D read FOnMouseUp write FOnMouseUp;
property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown;
property OnKeyUp: TKeyEvent read FOnKeyUp write FOnKeyUp;
property OnRender: TRenderEvent read FOnRender write FOnRender;
end;
{ TCamera }
TCamera = class(TControl3D)
private
FSaveCamera: TCamera;
FTarget: TControl3D;
procedure SetTarget(const Value: TControl3D);
protected
procedure Render; override;
procedure DesignClick; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override;
published
property HitTest default False;
property Target: TControl3D read FTarget write SetTarget;
end;
{ TLight }
TLightType = (ltDirectional, ltPoint, ltSpot);
TLight = class(TControl3D)
private
FEnabled: Boolean;
FLightType: TLightType;
FConstantAttenuation: Single;
FQuadraticAttenuation: Single;
FLinearAttenuation: Single;
FSpotCutOff: Single;
FSpotExponent: Single;
FDiffuse: TAlphaColor;
FSpecular: TAlphaColor;
FAmbient: TAlphaColor;
procedure SetLightType(const Value: TLightType);
procedure SetEnabled(const Value: Boolean);
procedure SetConstantAttenuation(const Value: Single);
procedure SetLinearAttenuation(const Value: Single);
procedure SetQuadraticAttenuation(const Value: Single);
procedure SetSpotCutOff(const Value: Single);
procedure SetSpotExponent(const Value: Single);
procedure SetDiffuse(const Value: TAlphaColor);
procedure SetSpecular(const Value: TAlphaColor);
procedure SetAmbient(const Value: TAlphaColor);
protected
procedure Render; override;
procedure SetNewViewport(AViewport: IViewport3D); override;
procedure SetHeight(const Value: Single); override;
procedure SetWidth(const Value: Single); override;
procedure SetDepth(const Value: Single); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override;
published
property Ambient: TAlphaColor read FAmbient write SetAmbient;
property HitTest default False;
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Diffuse: TAlphaColor read FDiffuse write SetDiffuse;
property ConstantAttenuation: Single read FConstantAttenuation write SetConstantAttenuation;
property LinearAttenuation: Single read FLinearAttenuation write SetLinearAttenuation;
property LightType: TLightType read FLightType write SetLightType;
property QuadraticAttenuation: Single read FQuadraticAttenuation write SetQuadraticAttenuation;
property Specular: TAlphaColor read FSpecular write SetSpecular;
property SpotCutOff: Single read FSpotCutOff write SetSpotCutOff;
property SpotExponent: Single read FSpotExponent write SetSpotExponent;
end;
{ TDummy }
TDummy = class(TControl3D)
protected
procedure Render; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override;
published
property HitTest default False;
end;
{ TProxyObject }
TProxyObject = class(TControl3D)
private
FSourceObject: TControl3D;
procedure SetSourceObject(const Value: TControl3D);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Render; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean; override;
published
property SourceObject: TControl3D read FSourceObject write SetSourceObject;
end;
{ TViewport3D }
TViewport3D = class(TControl, IViewport3D)
private
FBuffer: TBitmap;
FContext: TContext3D;
FCamera: TCamera;
FLights: TList;
FDesignGrid: TControl3D;
FDesignCamera: TCamera;
FDesignCameraZ: TDummy;
FDesignCameraX: TDummy;
FFill: TAlphaColor;
FMultisample: TMultisample;
FUsingDesignCamera: Boolean;
FDrawing: Boolean;
FLastWidth, FLastHeight: single;
FDisableAlign: Boolean;
procedure SetFill(const Value: TAlphaColor);
procedure SetMultisample(const Value: TMultisample);
function GetFill: TAlphaColor;
protected
procedure Paint; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function FindTarget(P: TPointF; const Data: TDragObject): IControl; override;
function ObjectAtPoint(P: TPointF): IControl; override;
{ IViewport3D }
function GetObject: TFmxObject;
function GetContext: TContext3D;
function GetScene: IScene;
function GetDesignCamera: TCamera;
procedure SetDesignCamera(const ACamera: TCamera);
procedure NeedRender;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Realign; override;
property Context: TContext3D read FContext write FContext;
{ children }
procedure AddObject(AObject: TFmxObject); override;
procedure RemoveObject(AObject: TFmxObject); override;
published
property Multisample: TMultisample read FMultisample write SetMultisample default TMultisample.ms4Samples;
property Color: TAlphaColor read GetFill write SetFill default TAlphaColors.White;
property Camera: TCamera read FCamera write FCamera;
property UsingDesignCamera: Boolean read FUsingDesignCamera write FUsingDesignCamera default True;
end;
var
DefaultContextClass: TContext3DClass = nil;
{ Utils }
function Point3D(X, Y, Z: Single): TPoint3D; overload;
function Point3D(const P: TVector3D): TPoint3D; overload;
function Point3DToString(R: TPoint3D): AnsiString;
function StringToPoint3D(S: AnsiString): TPoint3D;
function ColorToVector3D(AColor: TAlphaColor): TVector3D;
function VertexSize(const AFormat: TVertexFormats): Integer;
function GetVertexOffset(const APosition: TVertexFormat; const AFormat: TVertexFormats): Integer;
function Vector3D(const X, Y, Z: Single; const W: Single = 1.0): TVector3D; overload;
function Vector3D(const Point: TPoint3D; const W: Single = 1.0): TVector3D; overload;
function MidPoint(const p1, p2: TVector3D): TVector3D;
procedure SetVector3D(var V: TVector3D; const X, Y, Z: Single; const W: Single = 1.0);
function Vector3DNorm(const V: TVector3D): Single;
procedure NormalizeVector3D(var V: TVector3D);
function Vector3DNormalize(const V: TVector3D): TVector3D;
function Vector3DAdd(const v1: TVector3D; const v2: TVector3D): TVector3D;
procedure AddVector3D(var v1: TVector3D; const v2: TVector3D);
procedure CombineVector3D(var v1: TVector3D; const v2: TVector3D; f: Single);
function Vector3DReflect(const V, N: TVector3D): TVector3D;
function Vector3DAddScale(const v1: TVector3D; const v2: Single): TVector3D;
function Vector3DSubtract(const v1: TVector3D; const v2: TVector3D): TVector3D;
function Vector3DScale(const V: TVector3D; factor: Single): TVector3D;
function PointProject(const P, Origin, Direction: TVector3D): Single;
function Vector3DToColor(const AColor: TVector3D): TAlphaColor;
function Point3DToVector3D(const APoint:TPoint3D):TVector3D;
function Vector3DToPoint3D(const AVector:TVector3D):TPoint3D;
function VectorDistance2(const v1, v2: TVector3D): Single;
function Vector3DLength(const V: TVector3D): Single;
function Matrix3DMultiply(const M1, M2: TMatrix3D): TMatrix3D;
function Matrix3DDeterminant(const M: TMatrix3D): Single;
procedure AdjointMatrix3D(var M: TMatrix3D);
procedure ScaleMatrix3D(var M: TMatrix3D; const factor: Single);
procedure InvertMatrix(var M: TMatrix3D);
procedure TransposeMatrix3D(var M: TMatrix3D);
function Vector3DCrossProduct(const v1, v2: TVector3D): TVector3D;
function Vector3DDotProduct(const v1, v2: TVector3D): Single;
function Vector3DAngleCosine(const v1, v2: TVector3D): Single;
function Vector3DTransform(const V: TVector3D; const M: TMatrix3D): TVector3D;
function CalcPlaneNormal(const p1, p2, p3: TVector3D): TVector3D;
procedure RotateVector(var Vector: TVector3D; const axis: TVector3D; angle: Single);
function CreateRotationMatrix3D(const AnAxis: TVector3D; Angle: Single): TMatrix3D; overload;
function CreateRotationMatrix3D(const Y, P, R: Single): TMatrix3D; overload;
function CreateYawPitchRollMatrix3D(const Y, P, R: Single): TMatrix3D;
function CreateScaleMatrix3D(const AScale: TVector3D): TMatrix3D;
function CreateTranslateMatrix3D(const ATranslate: TVector3D): TMatrix3D;
function AxisRotationToMatrix3D(AAxis: TVector3D; AAngle: Single) : TMatrix3D;
{ Matrix }
function Matrix3D(const m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33,
m34, m41, m42, m43, m44:Single): TMatrix3D; overload;
function Matrix3D(const LArr: TSingleDynArray):TMatrix3D; overload;
function MatrixOrthoLH(W, h, zn, zf: Single): TMatrix3D;
function MatrixOrthoOffCenterLH(l, R, b, t, zn, zf: Single): TMatrix3D;
function MatrixOrthoOffCenterRH(l, R, b, t, zn, zf: Single): TMatrix3D;
function MatrixPerspectiveFovRH(flovy, aspect, zn, zf: Single): TMatrix3D;
function MatrixPerspectiveFovLH(flovy, aspect, zn, zf: Single): TMatrix3D;
function MatrixPerspectiveOffCenterLH(l, R, b, t, zn, zf: Single): TMatrix3D;
function MatrixLookAtRH(const Eye, At, Up: TVector3D): TMatrix3D;
function MatrixLookAtLH(const Eye, At, Up: TVector3D): TMatrix3D;
function MatrixLookAtDirRH(const Pos, Dir, Up: TVector3D): TMatrix3D;
function MatrixLookAtDirLH(const Pos, Dir, Up: TVector3D): TMatrix3D;
{ Quaternion }
procedure NormalizeQuaternion(var q: TQuaternion3D);
function QuaternionToMatrix(Quaternion: TQuaternion3D): TMatrix3D;
function QuaternionMultiply(const qL, qR: TQuaternion3D): TQuaternion3D;
function QuaternionFromAngleAxis(const angle: Single; const axis: TVector3D): TQuaternion3D;
function QuaternionFromMatrix(const Matrix: TMatrix3D): TQuaternion3D;
function RSqrt(V: Single): Single;
function ISqrt(i: Integer): Integer;
{ Intersection }
function RayCastPlaneIntersect(const RayPos, RayDir: TVector3D; const PlanePoint, PlaneNormal: TVector3D;
var Intersection: TVector3D): Boolean;
function RayCastSphereIntersect(const RayPos, RayDir: TVector3D; const SphereCenter: TVector3D;
const SphereRadius: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
function RayCastEllipsoidIntersect(const RayPos, RayDir: TVector3D; const EllipsoidCenter: TVector3D;
const XRadius, YRadius, ZRadius: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
function RayCastCuboidIntersect(const RayPos, RayDir: TVector3D; const CuboidCenter: TVector3D;
const Width, Height, Depth: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
function RayCastTriangleIntersect(const RayPos, RayDir: TVector3D; const Vertex1, Vertex2, Vertex3: TVector3D;
var Intersection: TVector3D): Boolean;
{ Used for correct Pick }
var
GlobalDistance: Single = 0;
GlobalProjection: TProjection;
implementation
uses
SysUtils, Math, TypInfo, FMX_Objects3D;
type
TOpenObject = class(TFmxObject);
{ Utils }
const
// to be used as descriptive indices
X = 0;
Y = 1;
Z = 2;
W = 3;
cZero: Single = 0.0;
cOne: Single = 1.0;
cOneDotFive: Single = 0.5;
function Point3D(X, Y, Z: Single): TPoint3D;
begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
end;
function Point3D(const P: TVector3D): TPoint3D;
begin
Result.X := P.X;
Result.Y := P.Y;
Result.Z := P.Z;
end;
function Point3DToString(R: TPoint3D): AnsiString;
begin
Result := '(' + FloatToStr(R.X, USFormatSettings) + ',' + FloatToStr(R.Y, USFormatSettings) + ',' +
FloatToStr(R.Z, USFormatSettings) + ')';
end;
function StringToPoint3D(S: AnsiString): TPoint3D;
begin
try
GetToken(S, ',()');
Result.X := StrToFloat(GetToken(S, ',()'), USFormatSettings);
Result.Y := StrToFloat(GetToken(S, ',()'), USFormatSettings);
Result.Z := StrToFloat(GetToken(S, ',()'), USFormatSettings);
except
Result := Point3D(0, 0, 0);
end;
end;
function ColorToVector3D(AColor: TAlphaColor): TVector3D;
begin
Result.X := TAlphaColorRec(AColor).R / $FF;
Result.Y := TAlphaColorRec(AColor).G / $FF;
Result.Z := TAlphaColorRec(AColor).B / $FF;
Result.W := TAlphaColorRec(AColor).A / $FF;
end;
{ Vertices }
function VertexSize(const AFormat: TVertexFormats): Integer;
begin
Result := 0;
if TVertexFormat.vfVertex in AFormat then
Result := Result + SizeOf(Single) * 3;
if TVertexFormat.vfNormal in AFormat then
Result := Result + SizeOf(Single) * 3;
if TVertexFormat.vfDiffuse in AFormat then
Result := Result + SizeOf(Cardinal);
if TVertexFormat.vfSpecular in AFormat then
Result := Result + SizeOf(Cardinal);
if TVertexFormat.vfTexCoord0 in AFormat then
Result := Result + SizeOf(Single) * 2;
if TVertexFormat.vfTexCoord1 in AFormat then
Result := Result + SizeOf(Single) * 2;
if TVertexFormat.vfTexCoord2 in AFormat then
Result := Result + SizeOf(Single) * 2;
if TVertexFormat.vfTexCoord3 in AFormat then
Result := Result + SizeOf(Single) * 2;
end;
function GetVertexOffset(const APosition: TVertexFormat; const AFormat: TVertexFormats): Integer;
begin
Result := 0;
if TVertexFormat.vfVertex in AFormat then
Result := Result + SizeOf(Single) * 3;
if APosition = TVertexFormat.vfNormal then Exit;
if TVertexFormat.vfNormal in AFormat then
Result := Result + SizeOf(Single) * 3;
if APosition = TVertexFormat.vfDiffuse then Exit;
if TVertexFormat.vfDiffuse in AFormat then
Result := Result + SizeOf(Cardinal);
if APosition = TVertexFormat.vfSpecular then Exit;
if TVertexFormat.vfSpecular in AFormat then
Result := Result + SizeOf(Cardinal);
if APosition = TVertexFormat.vfTexCoord0 then Exit;
if TVertexFormat.vfTexCoord0 in AFormat then
Result := Result + SizeOf(Single) * 2;
if APosition = TVertexFormat.vfTexCoord1 then Exit;
if TVertexFormat.vfTexCoord1 in AFormat then
Result := Result + SizeOf(Single) * 2;
if APosition = TVertexFormat.vfTexCoord2 then Exit;
if TVertexFormat.vfTexCoord2 in AFormat then
Result := Result + SizeOf(Single) * 2;
if APosition = TVertexFormat.vfTexCoord3 then Exit;
if TVertexFormat.vfTexCoord3 in AFormat then
Result := Result + SizeOf(Single) * 2;
end;
function Vector3D(const X, Y, Z: Single; const W: Single = 1.0): TVector3D;
begin
Result.X := X;
Result.Y := Y;
Result.Z := Z;
Result.W := W;
end;
function Vector3D(const Point: TPoint3D; const W: Single = 1.0): TVector3D;
begin
Result.X := Point.X;
Result.Y := Point.Y;
Result.Z := Point.Z;
Result.W := W;
end;
function MidPoint(const p1, p2: TVector3D): TVector3D;
begin
Result.X := (p1.X + p2.X) / 2;
Result.Y := (p1.Y + p2.Y) / 2;
Result.Z := (p1.Z + p2.Z) / 2;
Result.W := 1;
end;
procedure NormalizePlane(var Plane: TVector3D);
var
N: Single;
begin
N := RSqrt(abs(Plane.X * Plane.X + Plane.Y * Plane.Y + Plane.Z * Plane.Z));
Plane.X := Plane.X * N;
Plane.Y := Plane.Y * N;
Plane.Z := Plane.Z * N;
Plane.W := 1.0;
end;
function PlaneEvaluatePoint(const Plane: TVector3D; const Point: TVector3D): Single;
begin
Result := Plane.X * Point.X + Plane.Y * Point.Y + Plane.Z * Point.Z + Plane.W;
end;
procedure SetVector3D(var V: TVector3D; const X, Y, Z: Single; const W: Single = 1.0);
begin
V := Vector3D(X, Y, Z, W);
end;
function Vector3DNorm(const V: TVector3D): Single;
begin
Result := (V.X * V.X) + (V.Y * V.Y) + (V.Z * V.Z);
end;
procedure NormalizeVector3D(var V: TVector3D);
var
invLen: Single;
begin
invLen := RSqrt(abs(Vector3DNorm(V)));
V.X := V.X * invLen;
V.Y := V.Y * invLen;
V.Z := V.Z * invLen;
V.W := 0.0;
end;
function Vector3DNormalize(const V: TVector3D): TVector3D;
var
invLen: Single;
begin
invLen := RSqrt(abs(Vector3DNorm(V)));
Result.X := V.X * invLen;
Result.Y := V.Y * invLen;
Result.Z := V.Z * invLen;
Result.W := 0.0;
end;
function Vector3DAdd(const v1: TVector3D; const v2: TVector3D): TVector3D;
begin
Result.X := v1.X + v2.X;
Result.Y := v1.Y + v2.Y;
Result.Z := v1.Z + v2.Z;
Result.W := 1.0;
end;
procedure Vector3DCombine(const Vector1, Vector2: TVector3D; const F: Single; var VectorResult: TVector3D); overload;
begin
VectorResult.X := Vector1.X + (F * Vector2.X);
VectorResult.Y := Vector1.Y + (F * Vector2.Y);
VectorResult.Z := Vector1.Z + (F * Vector2.Z);
VectorResult.W := 1.0;
end;
function Vector3DCombine(const Vector1, Vector2: TVector3D; const F1, F2: Single): TVector3D; overload;
begin
Result.X := (F1 * Vector1.X) + (F2 * Vector2.X);
Result.Y := (F1 * Vector1.Y) + (F2 * Vector2.Y);
Result.Z := (F1 * Vector1.Z) + (F2 * Vector2.Z);
Result.W := 1.0;
end;
function Vector3DReflect(const V, N: TVector3D): TVector3D;
begin
Result := Vector3DCombine(V, N, 1, -2 * Vector3DDotProduct(V, N));
end;
function Vector3DAddScale(const v1: TVector3D; const v2: Single): TVector3D;
begin
Result.X := v1.X + v2;
Result.Y := v1.Y + v2;
Result.Z := v1.Z + v2;
Result.W := 1.0;
end;
procedure AddVector3D(var v1: TVector3D; const v2: TVector3D);
begin
v1 := Vector3DAdd(v1, v2);
end;
procedure CombineVector3D(var v1: TVector3D; const v2: TVector3D; f: Single);
begin
v1.X := v1.X + v2.X * f;
v1.Y := v1.Y + v2.Y * f;
v1.Z := v1.Z + v2.Z * f;
v1.W := 1.0;
end;
function Vector3DSubtract(const v1: TVector3D; const v2: TVector3D): TVector3D;
begin
Result.X := v1.X - v2.X;
Result.Y := v1.Y - v2.Y;
Result.Z := v1.Z - v2.Z;
Result.W := 1.0;
end;
function Vector3DLength(const V: TVector3D): Single;
begin
Result := Sqrt(Vector3DNorm(V));
end;
function Vector3DScale(const V: TVector3D; factor: Single): TVector3D;
begin
Result.X := V.X * factor;
Result.Y := V.Y * factor;
Result.Z := V.Z * factor;
Result.W := 1;
end;
function Vector3DToColor(const AColor: TVector3D): TAlphaColor;
begin
Result := MakeColor(Trunc(AColor.x * $FF),
Trunc(AColor.y * $FF),
Trunc(AColor.z * $FF), $FF);
end;
function Point3DToVector3D(const APoint:TPoint3D):TVector3D;
begin
result.X := APoint.X;
result.Y := APoint.Y;
result.Z := APoint.Z;
result.W := 1;
end;
function Vector3DToPoint3D(const AVector:TVector3D):TPoint3D;
begin
result.X := AVector.X;
result.Y := AVector.Y;
result.Z := AVector.Z;
end;
function PointProject(const P, Origin, Direction: TVector3D): Single;
begin
Result := Direction.X * (P.X - Origin.X) + Direction.Y * (P.Y - Origin.Y) + Direction.Z * (P.Z - Origin.Z);
end;
function VectorDistance2(const v1, v2: TVector3D): Single;
begin
Result := Sqr(v2.X - v1.X) + Sqr(v2.Y - v1.Y) + Sqr(v2.Z - v1.Z);
end;
function Matrix3DMultiply(const M1, M2: TMatrix3D): TMatrix3D;
begin
Result.M[X].V[X] := M1.M[X].V[X] * M2.M[X].V[X] + M1.M[X].V[Y] * M2.M[Y].V[X] + M1.M[X].V[Z] * M2.M[Z].V[X] +
M1.M[X].V[W] * M2.M[W].V[X];
Result.M[X].V[Y] := M1.M[X].V[X] * M2.M[X].V[Y] + M1.M[X].V[Y] * M2.M[Y].V[Y] + M1.M[X].V[Z] * M2.M[Z].V[Y] +
M1.M[X].V[W] * M2.M[W].V[Y];
Result.M[X].V[Z] := M1.M[X].V[X] * M2.M[X].V[Z] + M1.M[X].V[Y] * M2.M[Y].V[Z] + M1.M[X].V[Z] * M2.M[Z].V[Z] +
M1.M[X].V[W] * M2.M[W].V[Z];
Result.M[X].V[W] := M1.M[X].V[X] * M2.M[X].V[W] + M1.M[X].V[Y] * M2.M[Y].V[W] + M1.M[X].V[Z] * M2.M[Z].V[W] +
M1.M[X].V[W] * M2.M[W].V[W];
Result.M[Y].V[X] := M1.M[Y].V[X] * M2.M[X].V[X] + M1.M[Y].V[Y] * M2.M[Y].V[X] + M1.M[Y].V[Z] * M2.M[Z].V[X] +
M1.M[Y].V[W] * M2.M[W].V[X];
Result.M[Y].V[Y] := M1.M[Y].V[X] * M2.M[X].V[Y] + M1.M[Y].V[Y] * M2.M[Y].V[Y] + M1.M[Y].V[Z] * M2.M[Z].V[Y] +
M1.M[Y].V[W] * M2.M[W].V[Y];
Result.M[Y].V[Z] := M1.M[Y].V[X] * M2.M[X].V[Z] + M1.M[Y].V[Y] * M2.M[Y].V[Z] + M1.M[Y].V[Z] * M2.M[Z].V[Z] +
M1.M[Y].V[W] * M2.M[W].V[Z];
Result.M[Y].V[W] := M1.M[Y].V[X] * M2.M[X].V[W] + M1.M[Y].V[Y] * M2.M[Y].V[W] + M1.M[Y].V[Z] * M2.M[Z].V[W] +
M1.M[Y].V[W] * M2.M[W].V[W];
Result.M[Z].V[X] := M1.M[Z].V[X] * M2.M[X].V[X] + M1.M[Z].V[Y] * M2.M[Y].V[X] + M1.M[Z].V[Z] * M2.M[Z].V[X] +
M1.M[Z].V[W] * M2.M[W].V[X];
Result.M[Z].V[Y] := M1.M[Z].V[X] * M2.M[X].V[Y] + M1.M[Z].V[Y] * M2.M[Y].V[Y] + M1.M[Z].V[Z] * M2.M[Z].V[Y] +
M1.M[Z].V[W] * M2.M[W].V[Y];
Result.M[Z].V[Z] := M1.M[Z].V[X] * M2.M[X].V[Z] + M1.M[Z].V[Y] * M2.M[Y].V[Z] + M1.M[Z].V[Z] * M2.M[Z].V[Z] +
M1.M[Z].V[W] * M2.M[W].V[Z];
Result.M[Z].V[W] := M1.M[Z].V[X] * M2.M[X].V[W] + M1.M[Z].V[Y] * M2.M[Y].V[W] + M1.M[Z].V[Z] * M2.M[Z].V[W] +
M1.M[Z].V[W] * M2.M[W].V[W];
Result.M[W].V[X] := M1.M[W].V[X] * M2.M[X].V[X] + M1.M[W].V[Y] * M2.M[Y].V[X] + M1.M[W].V[Z] * M2.M[Z].V[X] +
M1.M[W].V[W] * M2.M[W].V[X];
Result.M[W].V[Y] := M1.M[W].V[X] * M2.M[X].V[Y] + M1.M[W].V[Y] * M2.M[Y].V[Y] + M1.M[W].V[Z] * M2.M[Z].V[Y] +
M1.M[W].V[W] * M2.M[W].V[Y];
Result.M[W].V[Z] := M1.M[W].V[X] * M2.M[X].V[Z] + M1.M[W].V[Y] * M2.M[Y].V[Z] + M1.M[W].V[Z] * M2.M[Z].V[Z] +
M1.M[W].V[W] * M2.M[W].V[Z];
Result.M[W].V[W] := M1.M[W].V[X] * M2.M[X].V[W] + M1.M[W].V[Y] * M2.M[Y].V[W] + M1.M[W].V[Z] * M2.M[Z].V[W] +
M1.M[W].V[W] * M2.M[W].V[W];
end;
function Vector3DCrossProduct(const v1, v2: TVector3D): TVector3D;
begin
Result.X := v1.Y * v2.Z - v1.Z * v2.Y;
Result.Y := v1.Z * v2.X - v1.X * v2.Z;
Result.Z := v1.X * v2.Y - v1.Y * v2.X;
Result.W := 1.0;
end;
function Vector3DDotProduct(const v1, v2: TVector3D): Single;
begin
Result := v1.X * v2.X + v1.Y * v2.Y + v1.Z * v2.Z;
end;
function CalcPlaneNormal(const p1, p2, p3: TVector3D): TVector3D;
var
v1, v2: TVector3D;
begin
v1 := Vector3DSubtract(p2, p1);
v2 := Vector3DSubtract(p3, p1);
Result := Vector3DCrossProduct(v1, v2);
Result := Vector3DNormalize(Result);
end;
function Vector3DAngleCosine(const v1, v2: TVector3D): Single;
begin
Result := Vector3DLength(v1) * Vector3DLength(v2);
if abs(Result) > Epsilon then
Result := Vector3DDotProduct(v1, v2) / Result
else
Result := Vector3DDotProduct(v1, v2) / Epsilon;
end;
function Vector3DTransform(const V: TVector3D; const M: TMatrix3D): TVector3D;
begin
Result.V[X] := V.V[X] * M.M[X].V[X] + V.V[Y] * M.M[Y].V[X] + V.V[Z] * M.M[Z].V[X] + V.V[W] * M.M[W].V[X];
Result.V[Y] := V.V[X] * M.M[X].V[Y] + V.V[Y] * M.M[Y].V[Y] + V.V[Z] * M.M[Z].V[Y] + V.V[W] * M.M[W].V[Y];
Result.V[Z] := V.V[X] * M.M[X].V[Z] + V.V[Y] * M.M[Y].V[Z] + V.V[Z] * M.M[Z].V[Z] + V.V[W] * M.M[W].V[Z];
Result.V[W] := 1;
end;
procedure RotateVector(var Vector: TVector3D; const axis: TVector3D; angle: Single);
var
rotMatrix: TMatrix3D;
begin
rotMatrix := CreateRotationMatrix3D(axis, angle);
Vector := Vector3DTransform(Vector, rotMatrix);
end;
function MatrixDetInternal(const a1, a2, a3, b1, b2, b3, c1, c2, c3: Single): Single; inline;
begin
Result := a1 * (b2 * c3 - b3 * c2) - b1 * (a2 * c3 - a3 * c2) + c1 * (a2 * b3 - a3 * b2);
end;
function Matrix3DDeterminant(const M: TMatrix3D): Single;
begin
Result :=
M.M[X].V[X] * MatrixDetInternal(M.M[Y].V[Y], M.M[Z].V[Y], M.M[W].V[Y], M.M[Y].V[Z],
M.M[Z].V[Z], M.M[W].V[Z], M.M[Y].V[W], M.M[Z].V[W], M.M[W].V[W]) -
M.M[X].V[Y] * MatrixDetInternal(M.M[Y].V[X], M.M[Z].V[X], M.M[W].V[X], M.M[Y].V[Z],
M.M[Z].V[Z], M.M[W].V[Z], M.M[Y].V[W], M.M[Z].V[W], M.M[W].V[W]) +
M.M[X].V[Z] * MatrixDetInternal(M.M[Y].V[X], M.M[Z].V[X], M.M[W].V[X], M.M[Y].V[Y],
M.M[Z].V[Y], M.M[W].V[Y], M.M[Y].V[W], M.M[Z].V[W], M.M[W].V[W]) -
M.M[X].V[W] * MatrixDetInternal(M.M[Y].V[X], M.M[Z].V[X], M.M[W].V[X], M.M[Y].V[Y],
M.M[Z].V[Y], M.M[W].V[Y], M.M[Y].V[Z], M.M[Z].V[Z], M.M[W].V[Z]);
end;
procedure AdjointMatrix3D(var M: TMatrix3D);
var
a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4: Single;
begin
a1 := M.M[X].V[X];
b1 := M.M[X].V[Y];
c1 := M.M[X].V[Z];
d1 := M.M[X].V[W];
a2 := M.M[Y].V[X];
b2 := M.M[Y].V[Y];
c2 := M.M[Y].V[Z];
d2 := M.M[Y].V[W];
a3 := M.M[Z].V[X];
b3 := M.M[Z].V[Y];
c3 := M.M[Z].V[Z];
d3 := M.M[Z].V[W];
a4 := M.M[W].V[X];
b4 := M.M[W].V[Y];
c4 := M.M[W].V[Z];
d4 := M.M[W].V[W];
// row column labeling reversed since we transpose rows & columns
M.M[X].V[X] := MatrixDetInternal(b2, b3, b4, c2, c3, c4, d2, d3, d4);
M.M[Y].V[X] := -MatrixDetInternal(a2, a3, a4, c2, c3, c4, d2, d3, d4);
M.M[Z].V[X] := MatrixDetInternal(a2, a3, a4, b2, b3, b4, d2, d3, d4);
M.M[W].V[X] := -MatrixDetInternal(a2, a3, a4, b2, b3, b4, c2, c3, c4);
M.M[X].V[Y] := -MatrixDetInternal(b1, b3, b4, c1, c3, c4, d1, d3, d4);
M.M[Y].V[Y] := MatrixDetInternal(a1, a3, a4, c1, c3, c4, d1, d3, d4);
M.M[Z].V[Y] := -MatrixDetInternal(a1, a3, a4, b1, b3, b4, d1, d3, d4);
M.M[W].V[Y] := MatrixDetInternal(a1, a3, a4, b1, b3, b4, c1, c3, c4);
M.M[X].V[Z] := MatrixDetInternal(b1, b2, b4, c1, c2, c4, d1, d2, d4);
M.M[Y].V[Z] := -MatrixDetInternal(a1, a2, a4, c1, c2, c4, d1, d2, d4);
M.M[Z].V[Z] := MatrixDetInternal(a1, a2, a4, b1, b2, b4, d1, d2, d4);
M.M[W].V[Z] := -MatrixDetInternal(a1, a2, a4, b1, b2, b4, c1, c2, c4);
M.M[X].V[W] := -MatrixDetInternal(b1, b2, b3, c1, c2, c3, d1, d2, d3);
M.M[Y].V[W] := MatrixDetInternal(a1, a2, a3, c1, c2, c3, d1, d2, d3);
M.M[Z].V[W] := -MatrixDetInternal(a1, a2, a3, b1, b2, b3, d1, d2, d3);
M.M[W].V[W] := MatrixDetInternal(a1, a2, a3, b1, b2, b3, c1, c2, c3);
end;
procedure ScaleMatrix3D(var M: TMatrix3D; const factor: Single);
var
i: Integer;
begin
for i := 0 to 3 do
begin
M.M[i].V[0] := M.M[i].V[0] * factor;
M.M[i].V[1] := M.M[i].V[1] * factor;
M.M[i].V[2] := M.M[i].V[2] * factor;
M.M[i].V[3] := M.M[i].V[3] * factor;
end;
end;
procedure TransposeMatrix3D(var M: TMatrix3D);
var
f: Single;
begin
f := M.M[0].V[1];
M.M[0].V[1] := M.M[1].V[0];
M.M[1].V[0] := f;
f := M.M[0].V[2];
M.M[0].V[2] := M.M[2].V[0];
M.M[2].V[0] := f;
f := M.M[0].V[3];
M.M[0].V[3] := M.M[3].V[0];
M.M[3].V[0] := f;
f := M.M[1].V[2];
M.M[1].V[2] := M.M[2].V[1];
M.M[2].V[1] := f;
f := M.M[1].V[3];
M.M[1].V[3] := M.M[3].V[1];
M.M[3].V[1] := f;
f := M.M[2].V[3];
M.M[2].V[3] := M.M[3].V[2];
M.M[3].V[2] := f;
end;
procedure InvertMatrix(var M: TMatrix3D);
var
det: Single;
begin
det := Matrix3DDeterminant(M);
if abs(det) < Epsilon then
M := IdentityMatrix3D
else
begin
AdjointMatrix3D(M);
ScaleMatrix3D(M, 1 / det);
end;
end;
function CreateRotationMatrix3D(const AnAxis: TVector3D; Angle: Single): TMatrix3D;
var
Axis: TVector3D;
Cos, Sin, OneMinusCos: Extended;
begin
SinCos(NormalizeAngle(Angle), Sin, Cos);
OneMinusCos := 1 - Cos;
Axis := Vector3DNormalize(AnAxis);
FillChar(Result, SizeOf(Result), 0);
Result.M[X].V[X] := (OneMinusCos * Axis.V[0] * Axis.V[0]) + Cos;
Result.M[X].V[Y] := (OneMinusCos * Axis.V[0] * Axis.V[1]) - (Axis.V[2] * Sin);
Result.M[X].V[Z] := (OneMinusCos * Axis.V[2] * Axis.V[0]) + (Axis.V[1] * Sin);
Result.M[Y].V[X] := (OneMinusCos * Axis.V[0] * Axis.V[1]) + (Axis.V[2] * Sin);
Result.M[Y].V[Y] := (OneMinusCos * Axis.V[1] * Axis.V[1]) + Cos;
Result.M[Y].V[Z] := (OneMinusCos * Axis.V[1] * Axis.V[2]) - (Axis.V[0] * Sin);
Result.M[Z].V[X] := (OneMinusCos * Axis.V[2] * Axis.V[0]) - (Axis.V[1] * Sin);
Result.M[Z].V[Y] := (OneMinusCos * Axis.V[1] * Axis.V[2]) + (Axis.V[0] * Sin);
Result.M[Z].V[Z] := (OneMinusCos * Axis.V[2] * Axis.V[2]) + Cos;
Result.M[W].V[W] := 1;
end;
function QuaternionRot(const R, P, Y: Single): TQuaternion3D;
var
qp, qy, qR: TQuaternion3D;
begin
qR := QuaternionFromAngleAxis(R, Vector3D(0, 0, 1));
qp := QuaternionFromAngleAxis(P, Vector3D(0, 1, 0));
qy := QuaternionFromAngleAxis(Y, Vector3D(1, 0, 0));
Result := QuaternionMultiply(qR, QuaternionMultiply(qp, qy));
end;
function CreateRotationMatrix3D(const Y, P, R: Single): TMatrix3D;
var
q: TQuaternion3D;
begin
q := QuaternionRot(R, P, Y);
Result := QuaternionToMatrix(q);
end;
function Matrix3D(const
m11, m12, m13, m14,
m21, m22, m23, m24,
m31, m32, m33, m34,
m41, m42, m43, m44 : Single): TMatrix3D; overload;
begin
Result.m11 := m11; Result.m12 := m12; Result.m13 := m13; Result.m14 := m14;
Result.m21 := m21; Result.m22 := m22; Result.m23 := m23; Result.m24 := m24;
Result.m31 := m31; Result.m32 := m32; Result.m33 := m33; Result.m34 := m34;
Result.m41 := m41; Result.m42 := m42; Result.m43 := m43; Result.m44 := m44;
end;
function Matrix3D(const LArr: TSingleDynArray):TMatrix3d; overload;
begin
result := Matrix3D(
LArr[0],LArr[4],LArr[8],LArr[12],
LArr[1],LArr[5],LArr[9],LArr[13],
LArr[2],LArr[6],LArr[10],LArr[14],
LArr[3],LArr[7],LArr[11],LArr[15]);
end;
function MatrixOrthoLH(W, h, zn, zf: Single): TMatrix3D;
begin
Result := IdentityMatrix3D;
Result.m11 := 2 / W;
Result.m22 := 2 / h;
Result.m33 := 1 / (zf - zn);
Result.m42 := zn / (zn - zf);
end;
function MatrixOrthoOffCenterLH(l, R, b, t, zn, zf: Single): TMatrix3D;
begin
Result := IdentityMatrix3D;
Result.m11 := 2 / (R - l);
Result.m22 := 2 / (t - b);
Result.m33 := 1 / (zf - zn);
Result.m41 := (l + R) / (l - R);
Result.m42 := (t + b) / (b - t);
Result.m43 := zn / (zn - zf);
end;
function MatrixOrthoOffCenterRH(l, R, b, t, zn, zf: Single): TMatrix3D;
begin
Result := IdentityMatrix3D;
Result.m11 := 2 / (R - l);
Result.m22 := 2 / (t - b);
Result.m33 := 1 / (zn - zf);
Result.m41 := (l + R) / (l - R);
Result.m42 := (t + b) / (b - t);
Result.m43 := zn / (zn - zf);
end;
function MatrixPerspectiveOffCenterLH(l, R, b, t, zn, zf: Single): TMatrix3D;
begin
Result := IdentityMatrix3D;
Result.m11 := (2 * zn) / (R - l);
Result.m22 := (2 * zn) / (t - b);
{ Result.m31 := (l + r) / (r - l);
Result.m32 := (t + b) / (t - b); }
Result.m34 := -1;
Result.m33 := 1;
Result.m43 := 0; // (zn * zf) / (zn - zf);
end;
{$EXCESSPRECISION OFF}
function MatrixPerspectiveFovRH(flovy, aspect, zn, zf: Single): TMatrix3D;
var
yScale, xScale, h, W: Single;
begin
yScale := cot(flovy / 2.0);
xScale := yScale / aspect;
h := cos(flovy / 2) / sin(flovy / 2);
W := h / aspect;
Result := IdentityMatrix3D;
Result.m11 := xScale;
Result.m22 := yScale;
Result.m33 := (zf / (zn - zf));
Result.m34 := -1;
Result.m43 := zn * zf / (zn - zf);
Result.m44 := 0;
end;
function MatrixPerspectiveFovLH(flovy, aspect, zn, zf: Single): TMatrix3D;
var
yScale, xScale, h, W: Single;
begin
yScale := cot(flovy / 2);
xScale := yScale / aspect;
h := cos(flovy / 2) / sin(flovy / 2);
W := h / aspect;
Result := IdentityMatrix3D;
Result.m11 := xScale;
Result.m22 := yScale;
Result.m33 := (zf / (zf - zn));
Result.m34 := 1;
Result.m43 := -zn * zf / (zf - zn);
Result.m44 := 0;
end;
function MatrixLookAtRH(const Eye, At, Up: TVector3D): TMatrix3D;
var
zaxis, xaxis, yaxis: TVector3D;
begin
zaxis := Vector3DNormalize(Vector3DSubtract(Eye, At));
zaxis.V[3] := 0;
xaxis := Vector3DNormalize(Vector3DCrossProduct(Up, zaxis));
xaxis.V[3] := 0;
yaxis := Vector3DCrossProduct(zaxis, xaxis);
yaxis.V[3] := 0;
Result := IdentityMatrix3D;
Result.m11 := xaxis.X;
Result.m12 := yaxis.X;
Result.m13 := zaxis.X;
Result.m21 := xaxis.Y;
Result.m22 := yaxis.Y;
Result.m23 := zaxis.Y;
Result.m31 := xaxis.Z;
Result.m32 := yaxis.Z;
Result.m33 := zaxis.Z;
Result.m41 := -Vector3DDotProduct(xaxis, Eye);
Result.m42 := -Vector3DDotProduct(yaxis, Eye);
Result.m43 := -Vector3DDotProduct(zaxis, Eye);
end;
function MatrixLookAtLH(const Eye, At, Up: TVector3D): TMatrix3D;
var
zaxis, xaxis, yaxis: TVector3D;
begin
zaxis := Vector3DNormalize(Vector3DSubtract(At, Eye));
zaxis.V[3] := 0;
xaxis := Vector3DNormalize(Vector3DCrossProduct(Up, zaxis));
xaxis.V[3] := 0;
yaxis := Vector3DCrossProduct(zaxis, xaxis);
yaxis.V[3] := 0;
Result := IdentityMatrix3D;
Result.m11 := xaxis.X;
Result.m12 := yaxis.X;
Result.m13 := zaxis.X;
Result.m21 := xaxis.Y;
Result.m22 := yaxis.Y;
Result.m23 := zaxis.Y;
Result.m31 := xaxis.Z;
Result.m32 := yaxis.Z;
Result.m33 := zaxis.Z;
Result.m41 := -Vector3DDotProduct(xaxis, Eye);
Result.m42 := -Vector3DDotProduct(yaxis, Eye);
Result.m43 := -Vector3DDotProduct(zaxis, Eye);
end;
function MatrixLookAtDirRH(const Pos, Dir, Up: TVector3D): TMatrix3D;
var
zaxis, xaxis, yaxis: TVector3D;
begin
zaxis := Vector3DNormalize(Dir);
zaxis.V[3] := 0;
xaxis := Vector3DNormalize(Vector3DCrossProduct(Up, zaxis));
xaxis.V[3] := 0;
yaxis := Vector3DCrossProduct(zaxis, xaxis);
yaxis.V[3] := 0;
Result := IdentityMatrix3D;
Result.m11 := xaxis.X;
Result.m12 := yaxis.X;
Result.m13 := zaxis.X;
Result.m21 := xaxis.Y;
Result.m22 := yaxis.Y;
Result.m23 := zaxis.Y;
Result.m31 := xaxis.Z;
Result.m32 := yaxis.Z;
Result.m33 := zaxis.Z;
Result.m41 := -Vector3DDotProduct(xaxis, Pos);
Result.m42 := -Vector3DDotProduct(yaxis, Pos);
Result.m43 := -Vector3DDotProduct(zaxis, Pos);
end;
function MatrixLookAtDirLH(const Pos, Dir, Up: TVector3D): TMatrix3D;
var
zaxis, xaxis, yaxis: TVector3D;
begin
zaxis := Vector3DNormalize(Vector3DScale(Dir, -1));
zaxis.V[3] := 0;
xaxis := Vector3DNormalize(Vector3DCrossProduct(Up, zaxis));
xaxis.V[3] := 0;
yaxis := Vector3DCrossProduct(zaxis, xaxis);
yaxis.V[3] := 0;
Result := IdentityMatrix3D;
Result.m11 := xaxis.X;
Result.m12 := yaxis.X;
Result.m13 := zaxis.X;
Result.m21 := xaxis.Y;
Result.m22 := yaxis.Y;
Result.m23 := zaxis.Y;
Result.m31 := xaxis.Z;
Result.m32 := yaxis.Z;
Result.m33 := zaxis.Z;
Result.m41 := -Vector3DDotProduct(xaxis, Pos);
Result.m42 := -Vector3DDotProduct(yaxis, Pos);
Result.m43 := -Vector3DDotProduct(zaxis, Pos);
end;
function RSqrt(V: Single): Single;
var
R: double;
begin
R := abs(V);
if R > 0 then
Result := 1 / Sqrt(R)
else
Result := 1;
end;
function ISqrt(i: Integer): Integer;
begin
{$HINTS OFF}
i := abs(i);
if i > 0 then
Result := Round(Sqrt(i))
else
Result := 1;
{$HINTS ON}
end;
function IsEssentiallyZero(const Value: Single): Boolean;
begin
Result := ((Value < Epsilon2) and (Value > -Epsilon2));
end;
function IsNotEssentiallyZero(const Value: Single): Boolean;
begin
Result := ((Value > Epsilon2) or (Value < -Epsilon2));
end;
{
See: http://en.wikipedia.org/wiki/Line–sphere_intersection
See: http://www.ccs.neu.edu/home/fell/CSU540/programs/RayTracingFormulas.htm
}
function RayCastSphereIntersect(const RayPos, RayDir: TVector3D; const SphereCenter: TVector3D;
const SphereRadius: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
var
A, B, C, B2, FourAC, Discriminant, LRoot, TwoA, LFactor: Single;
LTempVec: TVector3D;
begin
A := RayDir.X * RayDir.X + RayDir.Y * RayDir.Y + RayDir.Z * RayDir.Z;
b := 2 * (
RayDir.X * (RayPos.X - SphereCenter.X)
+ RayDir.Y * (RayPos.Y - SphereCenter.Y)
+ RayDir.Z * (RayPos.Z - SphereCenter.Z)
);
C := SphereCenter.X * SphereCenter.X + SphereCenter.Y * SphereCenter.Y + SphereCenter.Z * SphereCenter.Z
+ RayPos.X * RayPos.X + RayPos.Y * RayPos.Y + RayPos.Z * RayPos.Z
- 2 * (SphereCenter.X * RayPos.X + SphereCenter.Y * RayPos.Y + SphereCenter.Z * RayPos.Z) - SphereRadius * SphereRadius;
B2 := B * B;
FourAC := 4 * A * C;
discriminant := b2 - fourac;
if (discriminant < 0) then
begin
Result := 0;
end
else if (discriminant = 0) then
begin
Result := 1;
LFactor := -B / (2 * A); // we already know the descriminant is 0
IntersectionNear := Vector3DAdd(RayPos, Vector3DScale(RayDir, LFactor));
IntersectionFar := IntersectionNear;
end
else
begin
Result := 2;
LRoot := Sqrt(B2 - FourAC);
TwoA := 2 * A;
LFactor := (-B - LRoot)/TwoA;
IntersectionNear := Vector3DAdd(RayPos, Vector3DScale(RayDir, LFactor));
LFactor := (-B + LRoot)/TwoA;
IntersectionFar := Vector3DAdd(RayPos, Vector3DScale(RayDir, LFactor));
if VectorDistance2(RayPos, IntersectionNear) > VectorDistance2(RayPos, IntersectionFar) then
begin
LTempVec := IntersectionNear;
IntersectionNear := IntersectionFar;
IntersectionFar := LTempVec;
end;
end;
end;
{
We can use the Sphere Intersect algorithm if we distort space so we have a single common radius
}
function RayCastEllipsoidIntersect(const RayPos, RayDir: TVector3D; const EllipsoidCenter: TVector3D;
const XRadius, YRadius, ZRadius: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
var
LCommonRadius, LFactorX, LFactorY, LFactorZ: Single;
LRayPos, LRayDir, LSphereCenter: TVector3D;
begin
// avoid degenerate cases (where ellipsoid is a plane or line)
if IsNotEssentiallyZero(XRadius) and IsNotEssentiallyZero(YRadius) and IsNotEssentiallyZero(ZRadius) then
begin
LCommonRadius := XRadius;
LCommonRadius := Max(LCommonRadius, YRadius);
LCommonRadius := Max(LCommonRadius, ZRadius);
LFactorX := LCommonRadius/XRadius;
LFactorY := LCommonRadius/YRadius;
LFactorZ := LCommonRadius/ZRadius;
LRayPos := Vector3D(RayPos.X * LFactorX, RayPos.Y * LFactorY, RayPos.Z * LFactorZ);
LRayDir := Vector3D(RayDir.X * LFactorX, RayDir.Y * LFactorY, RayDir.Z * LFactorZ);
LSphereCenter := Vector3D(EllipsoidCenter.X * LFactorX, EllipsoidCenter.Y * LFactorY, EllipsoidCenter.Z * LFactorZ);
Result := RayCastSphereIntersect(LRayPos, LRayDir, LSphereCenter, LCommonRadius, IntersectionNear, IntersectionFar);
// adjust intersection points as needed
if Result > 0 then
begin
IntersectionNear.X := IntersectionNear.X / LFactorX;
IntersectionNear.Y := IntersectionNear.Y / LFactorY;
IntersectionNear.Z := IntersectionNear.Z / LFactorZ;
IntersectionFar.X := IntersectionFar.X / LFactorX;
IntersectionFar.Y := IntersectionFar.Y / LFactorY;
IntersectionFar.Z := IntersectionFar.Z / LFactorZ;
end;
end
else
Result := 0;
end;
function RayCastCuboidIntersect(const RayPos, RayDir: TVector3D; const CuboidCenter: TVector3D;
const Width, Height, Depth: Single; var IntersectionNear, IntersectionFar: TVector3D): Integer;
var
LWidth, LHeight, LDepth: Single;
LContinueSearch: Boolean;
A, B, C: Single;
LIntercepts: array [0..1] of TVector3D;
LDimensionVec, LThicknessVec: TVector3D;
I: Integer;
const
Root3Over2: Single = 0.866025404;
function TryEllipsoidShortcut(const W, H, D: Single): Boolean;
var
LMax, LMin: Single;
begin
LMin := W;
LMin := Min(LMin, H);
LMin := Min(LMin, D);
LMax := W;
LMax := Max(LMax, H);
LMax := Max(LMax, D);
Result := (LMin/LMax) > 0.1;
end;
function Inside(const Value: TVector3D): Boolean;
begin
Result := (Abs(Value.X - CuboidCenter.X) <= (0.501 * LWidth))
and (Abs(Value.Y - CuboidCenter.Y) <= (0.501 * LHeight))
and (Abs(Value.Z - CuboidCenter.Z) <= (0.501 * LDepth));
end;
// FireMonkey layers (which are basically 2D) have a hard coded thickness of 0.01
function IsThickerThan2DLayer(const Value: Single): Boolean;
begin
Result := (Value > 0.01) or (Value < -0.01);
end;
begin
LWidth := Abs(Width);
LHeight := Abs(Height);
LDepth := Abs(Depth);
if (LWidth = 0) or (LHeight = 0) or (LDepth = 0) then
begin
Result := 0;
Exit;
end;
// To find the real answer, we need to see how the ray intersects with the faces of the cuboid.
// As a shortcut, we can see if there is intersection with an ellipsoid that encompasses the
// entirety of the cuboid. Don't bother if the aspect ratio is too large.
if TryEllipsoidShortcut(LWidth, LHeight, LDepth) then
begin
// Derivation:
//
// Equation of ellipsoid (http://en.wikipedia.org/wiki/Ellipsoid):
//
// (x^2)/(a^2) + (y^2)/(b^2) + (z^2)/(c^2) = 1
//
// We also know that for the ellipsoid inscribed INSIDE the cuboid:
//
// a' = Width/2
// b' = Height/2
// c' = Depth/2
//
// To find the ellipsoid which encloses the cuboid, we need to simply scale
// up the ellipsoid which is inscribed within. Thus:
//
// a = factor * a' = factor * Width/2
// b = factor * b' = factor * Height/2
// c = factor * c' = factor * Depth/2
//
// We know one solution for the equation of the ellipsoid which encloses the
// cuboid is found when:
//
// x = Width/2
// y = Height/2
// z = Depth/2
//
// thus:
//
// ((Width/2)^2)/(a^2) + ((Height/2)^2)/(b^2)) + ((Depth/2)^2)/(c^2) = 1
//
// substitute a, b, c and simplify:
//
// 1/factor^2 + 1/factor^2 + 1/factor^2 = 1
//
// 3/factor^2 = 1
//
// factor = SquareRoot(3)
//
// yielding:
//
// a = SquareRoot(3) * Width/2
// b = SquareRoot(3) * Height/2
// c = SquareRoot(3) * Depth/2
A := Root3Over2 * LWidth;
B := Root3Over2 * LHeight;
C := Root3Over2 * LDepth;
LContinueSearch := RayCastEllipsoidIntersect(RayPos, RayDir, CuboidCenter, A, B, C, LIntercepts[0], LIntercepts[1]) > 0;
end
else
LContinueSearch := True;
if LContinueSearch then
begin
// We failed the ellipsoid check, now we need to do the hard work and check each face
Result := 0;
// store these in a vector so we can iterate over them
LDimensionVec := Vector3D(LWidth/2, LHeight/2, LDepth/2);
LThicknessVec := Vector3D(Min(LHeight, LDepth), Min(LWidth, LDepth), Min(LWidth, LHeight));
for I := 0 to 2 do
begin
if (Result < 2) and IsNotEssentiallyZero(RayDir.V[I])
and IsThickerThan2DLayer(LThicknessVec.V[I]) then
begin
LIntercepts[Result] := Vector3DAdd(RayPos, Vector3DScale(RayDir,
(CuboidCenter.V[I] - LDimensionVec.V[I] - RayPos.V[I]) / RayDir.V[I]));
if Inside(LIntercepts[Result]) then
Inc(Result);
if (Result < 2) then
begin
LIntercepts[Result] := Vector3DAdd(RayPos, Vector3DScale(RayDir,
(CuboidCenter.V[I] + LDimensionVec.V[I] - RayPos.V[I]) / RayDir.V[I]));
if Inside(LIntercepts[Result]) then
Inc(Result);
end;
end;
end;
if Result = 1 then
begin
IntersectionNear := LIntercepts[0];
IntersectionFar := LIntercepts[0];
end
else if Result = 2 then
begin
if VectorDistance2(RayPos, LIntercepts[0]) < VectorDistance2(RayPos, LIntercepts[1]) then
begin
IntersectionNear := LIntercepts[0];
IntersectionFar := LIntercepts[1];
end
else
begin
IntersectionNear := LIntercepts[1];
IntersectionFar := LIntercepts[0];
end;
end;
end
else
Result := 0;
end;
{
See: http://en.wikipedia.org/wiki/Line-plane_intersection
See: http://paulbourke.net/geometry/planeline/
}
function RayCastPlaneIntersect(const RayPos, RayDir: TVector3D; const PlanePoint, PlaneNormal: TVector3D;
var Intersection: TVector3D): Boolean;
var
LDotProd, LFactor: Single;
begin
// Is the Ray parallel to the plane?
LDotProd := Vector3DDotProduct(RayDir, PlaneNormal);
if IsNotEssentiallyZero(LDotProd) then
begin
LFactor := Vector3DDotProduct(Vector3DSubtract(PlanePoint, RayPos), PlaneNormal) / LDotProd;
if LFactor > 0 then
begin
Result := True;
Intersection := Vector3DAdd(RayPos, Vector3DScale(RayDir, LFactor));
end
else
Result := False; // The Ray points away from the plane
end
else
Result := False;
end;
{
See: http://en.wikipedia.org/wiki/Barycentric_coordinate_system_(mathematics)#Determining_if_a_point_is_inside_a_triangle
See: http://mathworld.wolfram.com/BarycentricCoordinates.html
See: http://www.blackpawn.com/texts/pointinpoly/default.html
}
function SameSide(const P1, P2: TVector3D; A, B: TVector3D): Boolean;
var
CP1, CP2: TVector3D;
begin
CP1 := Vector3DCrossProduct(Vector3DSubtract(B, A), Vector3DSubtract(P1, A));
CP2 := Vector3DCrossProduct(Vector3DSubtract(B, A), Vector3DSubtract(P2, A));
if Vector3DDotProduct(CP1, CP2) >= 0 then
Result := True
else
Result := False;
end;
function RayCastTriangleIntersect(const RayPos, RayDir: TVector3D; const Vertex1, Vertex2, Vertex3: TVector3D;
var Intersection: TVector3D): Boolean;
var
N, P, A, B, C: TVector3D;
begin
A := Vector3DSubtract(Vertex1, Vertex2);
B := Vector3DSubtract(Vertex2, Vertex3);
C := Vector3DSubtract(Vertex3, Vertex1);
N := Vector3DCrossProduct(A, C);
if RayCastPlaneIntersect(RayPos, RayDir, Vertex1, N, P) then
begin
if SameSide(P, A, B, C) and SameSide(P, B, A, C) and SameSide(P, C, A, B) then
Result := True
else
Result := False;
end;
end;
procedure NegateVector(var V: TVector3D);
begin
V.X := -V.X;
V.Y := -V.Y;
V.Z := -V.Z;
end;
function QuaternionMagnitude(const q: TQuaternion3D): Single;
begin
Result := Sqrt(Vector3DNorm(q.ImagPart) + q.RealPart * q.RealPart);
end;
function QuaternionFromAngleAxis(const angle: Single; const axis: TVector3D): TQuaternion3D;
var
S: Single;
{$IFDEF FPC}
LAngle: Single;
{$ENDIF}
begin
{$IFDEF FPC}
LAngle := DegToRad(angle * cOneDotFive);
S := Sin(LAngle);
Result.RealPart := Cos(LAngle);
{$ELSE}
SinCos(DegToRad(angle * cOneDotFive), S, Result.RealPart);
{$ENDIF}
Result.ImagPart := Vector3DScale(axis, S / Vector3DLength(axis));
end;
function QuaternionMultiply(const qL, qR: TQuaternion3D): TQuaternion3D;
begin
Result.RealPart := qL.RealPart * qR.RealPart - qL.ImagPart.X * qR.ImagPart.X - qL.ImagPart.Y * qR.ImagPart.Y - qL.ImagPart.Z * qR.ImagPart.Z;
Result.ImagPart.X := qL.RealPart * qR.ImagPart.X + qR.RealPart * qL.ImagPart.X + qL.ImagPart.Y * qR.ImagPart.Z - qL.ImagPart.Z * qR.ImagPart.Y;
Result.ImagPart.Y := qL.RealPart * qR.ImagPart.Y + qR.RealPart * qL.ImagPart.Y + qL.ImagPart.Z * qR.ImagPart.X - qL.ImagPart.X * qR.ImagPart.Z;
Result.ImagPart.Z := qL.RealPart * qR.ImagPart.Z + qR.RealPart * qL.ImagPart.Z + qL.ImagPart.X * qR.ImagPart.Y - qL.ImagPart.Y * qR.ImagPart.X;
Result.ImagPart.W := 1;
end;
function QuaternionFromRollPitchYaw(const R, P, Y: Single): TQuaternion3D;
var
qp, qy, qR: TQuaternion3D;
begin
qR := QuaternionFromAngleAxis(R, Vector3D(0, 0, 1));
qp := QuaternionFromAngleAxis(P, Vector3D(1, 0, 0));
qy := QuaternionFromAngleAxis(Y, Vector3D(0, 1, 0));
Result := qy;
Result := QuaternionMultiply(qp, Result);
Result := QuaternionMultiply(qR, Result);
end;
procedure NormalizeQuaternion(var q: TQuaternion3D);
var
M, f: Single;
begin
M := QuaternionMagnitude(q);
if M > EPSILON2 then
begin
f := 1 / M;
q.ImagPart := Vector3DScale(q.ImagPart, f);
q.RealPart := q.RealPart * f;
end
else
q := IdentityQuaternion;
end;
function QuaternionToMatrix(Quaternion: TQuaternion3D): TMatrix3D;
var
W, X, Y, Z, xx, xy, xz, xw, yy, yz, yw, zz, zw: Single;
begin
NormalizeQuaternion(Quaternion);
W := Quaternion.RealPart;
X := Quaternion.ImagPart.X;
Y := Quaternion.ImagPart.Y;
Z := Quaternion.ImagPart.Z;
xx := X * X;
xy := X * Y;
xz := X * Z;
xw := X * W;
yy := Y * Y;
yz := Y * Z;
yw := Y * W;
zz := Z * Z;
zw := Z * W;
FillChar(Result, Sizeof(Result), 0);
Result.M11 := 1 - 2 * (yy + zz);
Result.M21 := 2 * (xy - zw);
Result.M31 := 2 * (xz + yw);
Result.M12 := 2 * (xy + zw);
Result.M22 := 1 - 2 * (xx + zz);
Result.M32 := 2 * (yz - xw);
Result.M13 := 2 * (xz - yw);
Result.M23 := 2 * (yz + xw);
Result.M33 := 1 - 2 * (xx + yy);
Result.M44 := 1;
end;
function QuaternionFromMatrix(const Matrix: TMatrix3D): TQuaternion3D;
var
Trace, S: double;
begin
Result.ImagPart.W := 1.0;
Trace := Matrix.m11 + Matrix.m22 + Matrix.m33;
if Trace > EPSILON then
begin
S := 0.5 / Sqrt(Trace + 1.0);
Result.ImagPart.X := (Matrix.M23 - Matrix.M32) * S;
Result.ImagPart.Y := (Matrix.M31 - Matrix.M13) * S;
Result.ImagPart.Z := (Matrix.M12 - Matrix.M21) * S;
Result.RealPart := 0.25 / S;
end
else if (Matrix.M11 > Matrix.M22) and (Matrix.M11 > Matrix.M33) then
begin
S := Sqrt(Max(EPSILON, cOne + Matrix.M11 - Matrix.M22 - Matrix.M33)) * 2.0;
Result.ImagPart.X := 0.25 * S;
Result.ImagPart.Y := (Matrix.M12 + Matrix.M21) / S;
Result.ImagPart.Z := (Matrix.M31 + Matrix.M13) / S;
Result.RealPart := (Matrix.M23 - Matrix.M32) / S;
end
else if (Matrix.M22 > Matrix.M33) then
begin
S := Sqrt(Max(EPSILON, cOne + Matrix.M22 - Matrix.M11 - Matrix.M33)) * 2.0;
Result.ImagPart.X := (Matrix.M12 + Matrix.M21) / S;
Result.ImagPart.Y := 0.25 * S;
Result.ImagPart.X := (Matrix.M23 + Matrix.M32) / S;
Result.RealPart := (Matrix.M31 - Matrix.M13) / S;
end else
begin
S := Sqrt(Max(EPSILON, cOne + Matrix.M33 - Matrix.M11 - Matrix.M22)) * 2.0;
Result.ImagPart.X := (Matrix.M31 + Matrix.M13) / S;
Result.ImagPart.Y := (Matrix.M23 + Matrix.M32) / S;
Result.ImagPart.Z := 0.25 * S;
Result.RealPart := (Matrix.M12 - Matrix.M21) / S;
end;
NormalizeQuaternion(Result);
end;
function CreateYawPitchRollMatrix3D(const Y, P, R: Single): TMatrix3D;
var
q: TQuaternion3D;
begin
q := QuaternionFromRollPitchYaw(R, P, Y);
Result := QuaternionToMatrix(q);
end;
function CreateScaleMatrix3D(const AScale: TVector3D): TMatrix3D;
begin
FillChar(Result, SizeOf(Result), 0);
Result.M11 := AScale.x;
Result.M22 := AScale.y;
Result.M33 := AScale.z;
Result.M44 := 1;
end;
function CreateTranslateMatrix3D(const ATranslate: TVector3D): TMatrix3D;
begin
Result := IdentityMatrix3D;
Result.M41 := ATranslate.x;
Result.M42 := ATranslate.y;
Result.M43 := ATranslate.z;
end;
function AxisRotationToMatrix3D(AAxis: TVector3D; AAngle: Single) : TMatrix3D;
var
cosine, sine, Len, onecosine: double;
begin
AAngle := AAngle * PI / 180;
sine := sin(AAngle);
cosine := cos(AAngle);
onecosine := 1 - cosine;
Len := Vector3DLength(AAxis);
if Len = 0 then
Result := IdentityMatrix3D
else
begin
AAxis := Vector3DScale(AAxis,1/Len);
Result.m11 := (onecosine * AAxis.x * AAxis.x) + cosine;
Result.m21 := (onecosine * AAxis.x * AAxis.y) - (AAxis.z * Sine);
Result.m31 := (onecosine * AAxis.z * AAxis.x) + (AAxis.y * Sine);
Result.m41 := 0;
Result.m12 := (onecosine * AAxis.x * AAxis.y) + (AAxis.z * Sine);
Result.m22 := (onecosine * AAxis.y * AAxis.y) + cosine;
Result.m32 := (onecosine * AAxis.y * AAxis.z) - (AAxis.x * Sine);
Result.m42 := 0;
Result.m13 := (onecosine * AAxis.z * AAxis.x) - (AAxis.y * Sine);
Result.m23 := (onecosine * AAxis.y * AAxis.z) + (AAxis.x * Sine);
Result.m33 := (onecosine * AAxis.z * AAxis.z) + cosine;
Result.m43 := 0;
Result.m14 := 0;
Result.m24 := 0;
Result.m34 := 0;
Result.m44 := 1;
end;
end;
{$EXCESSPRECISION ON}
{ TPosition3D }
constructor TPosition3D.Create(const ADefaultValue: TPoint3D);
begin
inherited Create;
FDefaultValue := ADefaultValue;
FX := FDefaultValue.X;
FY := FDefaultValue.Y;
FZ := FDefaultValue.Z;
FSave := Vector3D(FX, FY, FZ);
end;
procedure TPosition3D.Assign(Source: TPersistent);
begin
if Source is TPosition3D then
begin
Point := TPosition3D(Source).Point;
FSave := Vector;
end
else
inherited
end;
procedure TPosition3D.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('Point', ReadPoint, WritePoint, (FX <> DefaultValue.X) or
(FY <> DefaultValue.Y) or (FZ <> DefaultValue.Z));
end;
procedure TPosition3D.ReadPoint(Reader: TReader);
begin
Point := StringToPoint3D(Reader.ReadString);
end;
procedure TPosition3D.WritePoint(Writer: TWriter);
begin
Writer.WriteString(Point3DToString(Point));
end;
function TPosition3D.GetVector: TVector3D;
begin
Result := Vector3D(FX, FY, FZ);
end;
procedure TPosition3D.SetVector(const Value: TVector3D);
begin
SetPoint3D(Point3D(Value));
end;
function TPosition3D.GetPoint3D: TPoint3D;
begin
Result := Point3D(FX, FY, FZ);
end;
procedure TPosition3D.SetVectorNoChange(const P: TVector3D);
begin
FSave := Vector3D(FX, FY, FZ);
FX := P.X;
FY := P.Y;
FZ := P.Z;
end;
procedure TPosition3D.SetPoint3DNoChange(const P: TPoint3D);
begin
FSave := Vector3D(FX, FY, FZ);
FX := P.X;
FY := P.Y;
FZ := P.Z;
end;
procedure TPosition3D.SetPoint3D(const Value: TPoint3D);
begin
FSave := Vector3D(FX, FY, FZ);
FX := Value.X;
FY := Value.Y;
FZ := Value.Z;
if Assigned(OnChange) then
OnChange(Self);
end;
procedure TPosition3D.SetX(const Value: Single);
begin
if FX <> Value then
begin
FSave.X := FX;
FX := Value;
if Assigned(OnChangeX) then
OnChangeX(Self)
else if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TPosition3D.SetY(const Value: Single);
begin
if FY <> Value then
begin
FSave.Y := FY;
FY := Value;
if Assigned(OnChangeY) then
OnChangeY(Self)
else if Assigned(OnChange) then
OnChange(Self);
end;
end;
procedure TPosition3D.SetZ(const Value: Single);
begin
if FZ <> Value then
begin
FSave.Z := FZ;
FZ := Value;
if Assigned(OnChangeZ) then
OnChangeZ(Self)
else if Assigned(OnChange) then
OnChange(Self);
end;
end;
function TPosition3D.Empty: Boolean;
begin
Result := (FX = 0) and (FY = 0) and (FZ = 0);
end;
{ TMeshData }
constructor TMeshData.Create;
begin
inherited;
FVertexBuffer := TVertexBuffer.Create([TVertexFormat.vfVertex, TVertexFormat.vfNormal, TVertexFormat.vfTexCoord0], 0);
FIndexBuffer := TIndexBuffer.Create(0);
end;
destructor TMeshData.Destroy;
begin
FVertexBuffer.Free;
FIndexBuffer.Free;
inherited;
end;
procedure TMeshData.Assign(Source: TPersistent);
begin
if Source is TMeshData then
begin
FVertexBuffer.Assign(TMeshData(Source).FVertexBuffer);
FIndexBuffer.Assign(TMeshData(Source).FIndexBuffer);
if Assigned(FOnChanged) then
FOnChanged(Self);
end
else
inherited
end;
procedure TMeshData.AssignFromMeshVertex(const Vertices: array of TMeshVertex; const Indices: array of Word);
begin
FVertexBuffer.Length := Length(Vertices);
Move(Vertices[0], FVertexBuffer.Buffer^, FVertexBuffer.Size);
FIndexBuffer.Length := Length(Indices);
Move(Indices[0], FIndexBuffer.Buffer^, FIndexBuffer.Size);
end;
procedure TMeshData.CalcNormals;
var
i, j: Integer;
vn: TVector3D;
begin
for i := 0 to FIndexBuffer.Length - 1 do
FVertexBuffer.Normals[FIndexBuffer[i]] := Point3D(0, 0, 0);
for i := 0 to (IndexBuffer.Length div 3) - 1 do
begin
j := i * 3;
if False { CCW } then
vn := CalcPlaneNormal(Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 0]].X, FVertexBuffer.Vertices[FIndexBuffer[j + 0]].Y,
FVertexBuffer.Vertices[FIndexBuffer[j + 0]].Z), Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 1]].X,
FVertexBuffer.Vertices[FIndexBuffer[j + 1]].Y, FVertexBuffer.Vertices[FIndexBuffer[j + 1]].Z),
Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 2]].X, FVertexBuffer.Vertices[FIndexBuffer[j + 2]].Y,
FVertexBuffer.Vertices[FIndexBuffer[j + 2]].Z))
else
vn := CalcPlaneNormal(Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 2]].X, FVertexBuffer.Vertices[FIndexBuffer[j + 2]].Y,
FVertexBuffer.Vertices[FIndexBuffer[j + 2]].Z), Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 1]].X,
FVertexBuffer.Vertices[FIndexBuffer[j + 1]].Y, FVertexBuffer.Vertices[FIndexBuffer[j + 1]].Z),
Vector3D(FVertexBuffer.Vertices[FIndexBuffer[j + 0]].X, FVertexBuffer.Vertices[FIndexBuffer[j + 0]].Y,
FVertexBuffer.Vertices[FIndexBuffer[j + 0]].Z));
with FVertexBuffer.Normals[FIndexBuffer[j + 0]] do
FVertexBuffer.Normals[FIndexBuffer[j + 0]] := Point3D(X + vn.X, Y + vn.Y, Z + vn.Z);
with FVertexBuffer.Normals[FIndexBuffer[j + 1]] do
FVertexBuffer.Normals[FIndexBuffer[j + 1]] := Point3D(X + vn.X, Y + vn.Y, Z + vn.Z);
with FVertexBuffer.Normals[FIndexBuffer[j + 2]] do
FVertexBuffer.Normals[FIndexBuffer[j + 2]] := Point3D(X + vn.X, Y + vn.Y, Z + vn.Z);
end;
end;
procedure TMeshData.Clear;
begin
FVertexBuffer.Length := 0;
FIndexBuffer.Length := 0;
end;
procedure TMeshData.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineBinaryProperty('Mesh', ReadMesh, WriteMesh, FVertexBuffer.Size > 0);
end;
function TMeshData.RayCastIntersect(const Width, Height, Depth: single;
const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
var
INear, IFar, P1, P2, P3: TVector3D;
I: Integer;
begin
// Start with a simple test of the bounding cuboid
Result := RayCastCuboidIntersect(RayPos, RayDir, Vector3D(0,0,0), Width, Height, Depth, INear, IFar) > 0;
if Result then
begin
// Now, reset the result and check the triangles
Result := False;
if (VertexBuffer.Size > 0) and (IndexBuffer.Size > 0) then
begin
for I := 0 to (IndexBuffer.Length div 3) - 1 do
begin
if (IndexBuffer[(I * 3) + 0] < VertexBuffer.Length) and
(IndexBuffer[(I * 3) + 1] < VertexBuffer.Length) and
(IndexBuffer[(I * 3) + 2] < VertexBuffer.Length) then
begin
with VertexBuffer.Vertices[IndexBuffer[(I * 3) + 0]] do
P1 := Vector3D(X * Width, Y * Height, Z * Depth);
with VertexBuffer.Vertices[IndexBuffer[(I * 3) + 1]] do
P2 := Vector3D(X * Width, Y * Height, Z * Depth);
with VertexBuffer.Vertices[IndexBuffer[(I * 3) + 2]] do
P3 := Vector3D(X * Width, Y * Height, Z * Depth);
if RayCastTriangleIntersect(RayPos, RayDir, P1, P2, P3, INear)
then
begin
Intersection := INear;
Result := True;
Exit;
end;
end;
end;
end;
end;
end;
procedure TMeshData.ReadMesh(Stream: TStream);
var
l: Cardinal;
begin
Stream.Read(l, SizeOf(l));
FVertexBuffer.Length := l;
Stream.Read(FVertexBuffer.Buffer^, FVertexBuffer.Size);
Stream.Read(l, SizeOf(l));
FIndexBuffer.Length := l;
Stream.Read(FIndexBuffer.Buffer^, FIndexBuffer.Size);
end;
procedure TMeshData.WriteMesh(Stream: TStream);
var
l: Cardinal;
begin
l := FVertexBuffer.Length;
Stream.Write(l, SizeOf(l));
Stream.Write(FVertexBuffer.Buffer^, FVertexBuffer.Size);
l := FIndexBuffer.Length;
Stream.Write(l, SizeOf(l));
Stream.Write(FIndexBuffer.Buffer^, FIndexBuffer.Size);
end;
function TMeshData.GetNormals: AnsiString;
{$IFNDEF FPC}
var
i: Integer;
SB: TStringBuilder;
begin
SB := TStringBuilder.Create(FVertexBuffer.Length * (3 * 12 + 4));
try
for i := 0 to (FVertexBuffer.Length - 1) do
begin
SB.Append(FloatToStr(FVertexBuffer.Normals[i].x, USFormatSettings));
SB.Append(' ');
SB.Append(FloatToStr(FVertexBuffer.Normals[i].y, USFormatSettings));
SB.Append(' ');
SB.Append(FloatToStr(FVertexBuffer.Normals[i].z, USFormatSettings));
SB.Append(' ');
end;
Result := SB.ToString;
Result := Trim(Result);
finally
SB.Free;
end;
end;
{$ELSE}
var
S: AnsiString;
i, Pos: Integer;
begin
SetLength(Result, FVertexBuffer.Length * (3 * 12 + 4));
Pos := 0;
for i := 0 to (FVertexBuffer.Length - 1) do
begin
S := FloatToStr(FVertexBuffer.Normals[i].x, USFormatSettings) + ' ' + FloatToStr(FVertexBuffer.Normals[i].y, USFormatSettings) + ' '
+ FloatToStr(FVertexBuffer.Normals[i].z, USFormatSettings) + ' ';
System.Move(PWideChar(S)^, PByteArray(Result)[Pos], Length(S));
Pos := Pos + Length(S);
end;
SetLength(Result, Pos);
end;
{$ENDIF}
function TMeshData.GetPoint3Ds: AnsiString;
{$IFNDEF FPC}
var
i: Integer;
SB: TStringBuilder;
begin
SB := TStringBuilder.Create(FVertexBuffer.Length * (3 * 12 + 4));
try
for i := 0 to (FVertexBuffer.Length - 1) do
begin
SB.Append(FloatToStr(FVertexBuffer.Vertices[i].x, USFormatSettings));
SB.Append(' ');
SB.Append(FloatToStr(FVertexBuffer.Vertices[i].y, USFormatSettings));
SB.Append(' ');
SB.Append(FloatToStr(FVertexBuffer.Vertices[i].z, USFormatSettings));
SB.Append(' ');
end;
Result := SB.ToString;
Result := Trim(Result);
finally
SB.Free;
end;
end;
{$ELSE}
var
S: AnsiString;
i, Pos: Integer;
begin
SetLength(Result, FVertexBuffer.Length * (3 * 12 + 4));
Pos := 0;
for i := 0 to (FVertexBuffer.Length - 1) do
begin
S := FloatToStr(FVertexBuffer.Vertices[i].X, USFormatSettings) + ' ' + FloatToStr(FVertexBuffer.Vertices[i].Y, USFormatSettings) + ' ' +
FloatToStr(FVertexBuffer.Vertices[i].Z, USFormatSettings) + ' ';
System.Move(PWideChar(S)^, PByteArray(Result)[Pos], Length(S));
Pos := Pos + Length(S);
end;
SetLength(Result, Pos);
end;
{$ENDIF}
function TMeshData.GetTexCoordinates: AnsiString;
{$IFNDEF FPC}
var
i: Integer;
SB: TStringBuilder;
begin
SB := TStringBuilder.Create(FVertexBuffer.Length * (2 * 12 + 4));
try
for i := 0 to (FVertexBuffer.Length - 1) do
begin
SB.Append(FloatToStr(FVertexBuffer.TexCoord0[i].x, USFormatSettings));
SB.Append(' ');
SB.Append(FloatToStr(FVertexBuffer.TexCoord0[i].y, USFormatSettings));
SB.Append(' ');
end;
Result := SB.ToString;
Result := Trim(Result);
finally
SB.Free;
end;
end;
{$ELSE}
var
S: AnsiString;
i, Pos: Integer;
begin
SetLength(Result, FVertexBuffer.Length * (2 * 12 + 4));
Pos := 0;
for i := 0 to (FVertexBuffer.Length - 1) do
begin
S := FloatToStr(FVertexBuffer.TexCoord0[i].x, USFormatSettings) + ' ' + FloatToStr(FVertexBuffer.TexCoord0[i].y,
USFormatSettings) + ' ';
System.Move(PWideChar(S)^, PByteArray(Result)[Pos], Length(S));
Pos := Pos + Length(S);
end;
SetLength(Result, Pos);
end;
{$ENDIF}
function TMeshData.GetTriangleIndices: AnsiString;
{$IFNDEF FPC}
var
i: Integer;
SB: TStringBuilder;
begin
SB := TStringBuilder.Create(FIndexBuffer.Length * 7);
try
for i := 0 to (FIndexBuffer.Length - 1) do
begin
SB.Append(FloatToStr(FIndexBuffer[i], USFormatSettings));
SB.Append(' ');
if (i + 1) mod 3 = 0 then
SB.Append(' ');
end;
Result := SB.ToString;
Result := Trim(Result);
finally
SB.Free;
end;
end;
{$ELSE}
var
S: AnsiString;
i, Pos: Integer;
begin
SetLength(Result, (FIndexBuffer.Length - 1) * (7));
Pos := 0;
for i := 0 to (FIndexBuffer.Length - 1) do
begin
S := FloatToStr(FIndexBuffer[i], USFormatSettings) + ' ';
if (i + 1) mod 3 = 0 then
S := S + ' ';
System.Move(PWideChar(S)^, PByteArray(Result)[Pos], Length(S));
Pos := Pos + Length(S);
end;
SetLength(Result, Pos);
end;
{$ENDIF}
procedure TMeshData.SetNormals(const Value: AnsiString);
var
Pos, Count: Integer;
Val: WideString;
begin
// ensure a last separator
Val := Value + ' ,';
// calc size
Pos := 1;
Count := 0;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
WideGetToken(Pos, Val, ' ,');
WideGetToken(Pos, Val, ' ,');
WideGetToken(Pos, Val, ' ,');
except
end;
end;
// fill
FVertexBuffer.Length := Count;
Pos := 1;
Count := 0;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
FVertexBuffer.Normals[Count - 1] := Point3D(
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings),
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings),
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings)
);
except
end;
end;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
procedure TMeshData.SetPoint3Ds(const Value: AnsiString);
var
Pos, Count: Integer;
Val: WideString;
begin
// ensure a last separator
Val := Value + ' ,';
// calc size
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
WideGetToken(Pos, Val, ' ,');
WideGetToken(Pos, Val, ' ,');
WideGetToken(Pos, Val, ' ,');
except
end;
end;
// fill
FVertexBuffer.Length := Count;
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
FVertexBuffer.Vertices[Count - 1] := Point3D(
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings),
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings),
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings)
);
except
end;
end;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
procedure TMeshData.SetTexCoordinates(const Value: AnsiString);
var
Pos, Count: Integer;
Val: WideString;
begin
// ensure a last separator
Val := Value + ' ';
// calc size
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
WideGetToken(Pos, Val, ' ,');
WideGetToken(Pos, Val, ' ,');
except
end;
end;
// calc size
FVertexBuffer.Length := Count;
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
FVertexBuffer.TexCoord0[Count - 1] := PointF(
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings),
StrToFloat(WideGetToken(Pos, Val, ' ,'), USFormatSettings));
except
end;
end;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
procedure TMeshData.SetTriangleIndices(const Value: AnsiString);
var
Pos, Count: Integer;
Val: WideString;
begin
// ensure a last separator
Val := Value + ' ,';
// calc zise
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
WideGetToken(Pos, Val, ' ,');
except
end;
end;
// fill
FIndexBuffer.Length := Count;
Count := 0;
Pos := 1;
while Pos < Length(Val) do
begin
try
Count := Count + 1;
FIndexBuffer[Count - 1] := StrToInt(WideGetToken(Pos, Val, ' ,'));
except
end;
end;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
{ TMaterial }
constructor TMaterial.Create;
begin
inherited;
FDiffuse := DefaultDiffuse;
FAmbient := DefaultAmbient;
FSpecular := DefaultSpecular;
FEmissive := 0;
FShininess := DefaultShininess;
FLighting := True;
FShadeMode := TShadeMode.smGouraud;
FTextureFiltering := TTextureFiltering.tfLinear;
FTexture := TBitmap.Create(0, 0);
FTexture.OnChange := DoTextureChanged;
end;
destructor TMaterial.Destroy;
begin
FreeAndNil(FTexture);
inherited;
end;
procedure TMaterial.DoTextureChanged(Sender: TObject);
begin
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
function TMaterial.IsAmbientStored: Boolean;
begin
Result := FAmbient <> DefaultAmbient;
end;
function TMaterial.IsDiffuseStored: Boolean;
begin
Result := FDiffuse <> DefaultDiffuse;
end;
function TMaterial.IsEmissiveStored: Boolean;
begin
Result := FEmissive <> 0;
end;
function TMaterial.IsSpecularStored: Boolean;
begin
Result := FSpecular <> DefaultSpecular;
end;
procedure TMaterial.Assign(Source: TPersistent);
begin
if Source is TMaterial then
begin
FDiffuse := (Source as TMaterial).FDiffuse;
FAmbient := (Source as TMaterial).FAmbient;
FEmissive := (Source as TMaterial).FEmissive;
FSpecular := (Source as TMaterial).FSpecular;
FLighting := (Source as TMaterial).FLighting;
FModulation := (Source as TMaterial).FModulation;
FShadeMode := (Source as TMaterial).FShadeMode;
FFillMode := (Source as TMaterial).FFillMode;
FTextureFiltering := (Source as TMaterial).FTextureFiltering;
FTexture.Assign((Source as TMaterial).FTexture);
if Assigned(FOnChanged) then
FOnChanged(Self);
end
else
inherited
end;
procedure TMaterial.SetModulation(const Value: TTextureMode);
begin
if FModulation <> Value then
begin
FModulation := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetLighting(const Value: Boolean);
begin
if FLighting <> Value then
begin
FLighting := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetAmbient(const Value: TAlphaColor);
begin
if FAmbient <> Value then
begin
FAmbient := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetShadeMode(const Value: TShadeMode);
begin
if FShadeMode <> Value then
begin
FShadeMode := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetShininess(const Value: Integer);
begin
if FShininess <> Value then
begin
FShininess := Value;
if FShininess < 0 then FShininess := 0;
if FShininess > 128 then FShininess := 128;
end;
end;
procedure TMaterial.SetFillMode(const Value: TFillMode);
begin
if FFillMode <> Value then
begin
FFillMode := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetSpecular(const Value: TAlphaColor);
begin
if FSpecular <> Value then
begin
FSpecular := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetTexture(const Value: TBitmap);
begin
FTexture.Assign(Value);
end;
procedure TMaterial.SetTextureFiltering(const Value: TTextureFiltering);
begin
if FTextureFiltering <> Value then
begin
FTextureFiltering := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetDiffuse(const Value: TAlphaColor);
begin
if FDiffuse <> Value then
begin
FDiffuse := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
procedure TMaterial.SetEmissive(const Value: TAlphaColor);
begin
if FEmissive <> Value then
begin
FEmissive := Value;
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
end;
{ TIndexBuffer }
constructor TIndexBuffer.Create(const ALength: Integer);
begin
inherited Create;
FLength := ALength;
FSize := FLength * 2;
GetMem(FBuffer, Size);
end;
destructor TIndexBuffer.Destroy;
begin
FreeMem(FBuffer);
inherited;
end;
procedure TIndexBuffer.Assign(Source: TPersistent);
begin
if Source is TIndexBuffer then
begin
FreeMem(FBuffer);
FLength := TIndexBuffer(Source).FLength;
FSize := FLength * 2;
GetMem(FBuffer, Size);
Move(TIndexBuffer(Source).Buffer^, Buffer^, Size);
end
else
inherited;
end;
function TIndexBuffer.GetIndices(AIndex: Integer): Integer;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PWordArray(FBuffer)[AIndex];
end;
procedure TIndexBuffer.SetIndices(AIndex: Integer; const Value: Integer);
begin
assert((AIndex >= 0) and (AIndex < Length));
PWordArray(FBuffer)[AIndex] := Value
end;
procedure TIndexBuffer.SetLength(const Value: Integer);
var
Buf: Pointer;
SaveLength: Integer;
begin
if FLength <> Value then
begin
if FLength < Value then
SaveLength := FLength
else
SaveLength := Value;
GetMem(Buf, SaveLength * 2);
try
Move(FBuffer^, Buf^, SaveLength * 2);
FreeMem(FBuffer);
FLength := Value;
FSize := FLength * 2;
GetMem(FBuffer, FSize);
Move(Buf^, FBuffer^, SaveLength * 2);
finally
FreeMem(Buf);
end;
end;
end;
{ TVertexBuffer }
constructor TVertexBuffer.Create(const AFormat: TVertexFormats;
const ALength: Integer);
begin
inherited Create;
FFormat := AFormat;
FLength := ALength;
FVertexSize := FMX_Types3D.VertexSize(FFormat);
FSize := FVertexSize * FLength;
GetMem(FBuffer, Size);
FTexCoord0 := GetVertexOffset(TVertexFormat.vfTexCoord0, FFormat);
FTexCoord1 := GetVertexOffset(TVertexFormat.vfTexCoord1, FFormat);
FTexCoord2 := GetVertexOffset(TVertexFormat.vfTexCoord2, FFormat);
FTexCoord3 := GetVertexOffset(TVertexFormat.vfTexCoord3, FFormat);
FDiffuse := GetVertexOffset(TVertexFormat.vfDiffuse, FFormat);
FSpecular := GetVertexOffset(TVertexFormat.vfSpecular, FFormat);
FNormal := GetVertexOffset(TVertexFormat.vfNormal, FFormat);
end;
destructor TVertexBuffer.Destroy;
begin
FreeMem(FBuffer);
inherited;
end;
procedure TVertexBuffer.Assign(Source: TPersistent);
begin
if Source is TVertexBuffer then
begin
FreeMem(FBuffer);
FFormat := TVertexBuffer(Source).FFormat;
FLength := TVertexBuffer(Source).FLength;
FVertexSize := FMX_Types3D.VertexSize(FFormat);
FSize := FVertexSize * FLength;
GetMem(FBuffer, Size);
Move(TVertexBuffer(Source).Buffer^, Buffer^, Size);
end
else
inherited;
end;
function TVertexBuffer.GetVertices(AIndex: Integer): TPoint3D;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PPoint3D(@PByteArray(FBuffer)[AIndex * FVertexSize])^;
end;
procedure TVertexBuffer.SetVertices(AIndex: Integer; const Value: TPoint3D);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPoint3D(@PByteArray(FBuffer)[AIndex * FVertexSize])^ := Value;
end;
function TVertexBuffer.GetTexCoord0(AIndex: Integer): TPointF;
begin
Result := PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord0])^;
end;
procedure TVertexBuffer.SetTexCoord0(AIndex: Integer; const Value: TPointF);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord0])^ := Value;
end;
function TVertexBuffer.GetTexCoord1(AIndex: Integer): TPointF;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord1])^;
end;
procedure TVertexBuffer.SetTexCoord1(AIndex: Integer; const Value: TPointF);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord1])^ := Value;
end;
function TVertexBuffer.GetTexCoord2(AIndex: Integer): TPointF;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord2])^;
end;
procedure TVertexBuffer.SetTexCoord2(AIndex: Integer; const Value: TPointF);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord2])^ := Value;
end;
function TVertexBuffer.GetTexCoord3(AIndex: Integer): TPointF;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord3])^;
end;
procedure TVertexBuffer.SetTexCoord3(AIndex: Integer; const Value: TPointF);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPointF(@PByteArray(FBuffer)[AIndex * FVertexSize + FTexCoord3])^ := Value;
end;
function TVertexBuffer.GetDiffuse(AIndex: Integer): TAlphaColor;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PColor(@PByteArray(FBuffer)[AIndex * FVertexSize + FDiffuse])^;
end;
procedure TVertexBuffer.SetDiffuse(AIndex: Integer; const Value: TAlphaColor);
begin
assert((AIndex >= 0) and (AIndex < Length));
PColor(@PByteArray(FBuffer)[AIndex * FVertexSize + FDiffuse])^ := Value;
end;
procedure TVertexBuffer.SetLength(const Value: Integer);
var
SaveLength: Integer;
Buf: Pointer;
begin
if FLength <> Value then
begin
if FLength < Value then
SaveLength := FLength
else
SaveLength := Value;
GetMem(Buf, SaveLength * FVertexSize);
try
Move(FBuffer^, Buf^, SaveLength * FVertexSize);
FreeMem(FBuffer);
FLength := Value;
FSize := FLength * FVertexSize;
GetMem(FBuffer, FSize);
Move(Buf^, FBuffer^, SaveLength * FVertexSize);
finally
FreeMem(Buf);
end;
end;
end;
function TVertexBuffer.GetNormals(AIndex: Integer): TPoint3D;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PPoint3D(@PByteArray(FBuffer)[AIndex * FVertexSize + FNormal])^;
end;
procedure TVertexBuffer.SetNormals(AIndex: Integer; const Value: TPoint3D);
begin
assert((AIndex >= 0) and (AIndex < Length));
PPoint3D(@PByteArray(FBuffer)[AIndex * FVertexSize + FNormal])^ := Value;
end;
function TVertexBuffer.GetSpecular(AIndex: Integer): TAlphaColor;
begin
assert((AIndex >= 0) and (AIndex < Length));
Result := PColor(@PByteArray(FBuffer)[AIndex * FVertexSize + FSpecular])^;
end;
procedure TVertexBuffer.SetSpecular(AIndex: Integer; const Value: TAlphaColor);
begin
assert((AIndex >= 0) and (AIndex < Length));
PColor(@PByteArray(FBuffer)[AIndex * FVertexSize + FSpecular])^ := Value;
end;
{ TContext3D }
constructor TContext3D.CreateFromWindow(const AParent: TFmxHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean);
begin
inherited Create;
FParent := AParent;
FMultisample := AMultisample;
FDepthStencil := ADepthStencil;
FPaintToMatrix := IdentityMatrix3D;
FWidth := AWidth;
FHeight := AHeight;
FBitmaps := TList.Create;
FLights := TList.Create;
end;
constructor TContext3D.CreateFromBitmap(const ABitmap: TBitmap; const AMultisample: TMultisample;
const ADepthStencil: Boolean);
begin
inherited Create;
FMultisample := AMultisample;
FDepthStencil := ADepthStencil;
FBitmap := ABitmap;
FPaintToMatrix := IdentityMatrix3D;
FWidth := FBitmap.Width;
FHeight := FBitmap.Height;
FBitmaps := TList.Create;
FLights := TList.Create;
end;
destructor TContext3D.Destroy;
var
I: Integer;
begin
if FBitmaps.Count > 0 then
for I := FBitmaps.Count - 1 downto 0 do
FreeNotification(TBitmap(FBitmaps[I]));
FBitmaps.Free;
FreeBuffer;
FLights.Free;
inherited;
end;
procedure TContext3D.FreeNotification(AObject: TObject);
begin
if (AObject <> nil) and (AObject is TBitmap) then
DestroyBitmapHandle(TBitmap(AObject));
end;
function TContext3D.GetScreenMatrix: TMatrix3D;
var
matProj, scaleMatrix, transMatrix, orthoProj: TMatrix3D;
begin
orthoProj := MatrixOrthoOffCenterRH(0, FWidth, 0, FHeight, 1, 1000);
matProj := MatrixPerspectiveFovRH(cPI / 6, FWidth / FHeight, 1, 1000);
transMatrix := IdentityMatrix3D;
transMatrix.m41 := 0;
transMatrix.m42 := 0;
transMatrix.m43 := -2;
matProj := Matrix3DMultiply(transMatrix, matProj);
scaleMatrix := IdentityMatrix3D;
scaleMatrix.m11 := (orthoProj.m11 / matProj.m11) * 2;
scaleMatrix.m22 := -(orthoProj.m11 / matProj.m11) * 2;
scaleMatrix.m33 := -(orthoProj.m11 / matProj.m11) * 2;
matProj := Matrix3DMultiply(scaleMatrix, matProj);
transMatrix := IdentityMatrix3D;
transMatrix.m41 := -FWidth / 2;
transMatrix.m42 := -FHeight / 2;
transMatrix.m43 := 0;
matProj := Matrix3DMultiply(transMatrix, matProj);
Result := matProj;
end;
procedure TContext3D.AddLight(const ALight: TLight);
begin
FLights.Add(ALight);
if FViewport <> nil then
FViewport.NeedRender;
end;
procedure TContext3D.DeleteLight(const ALight: TLight);
begin
FLights.Remove(ALight);
if FViewport <> nil then
FViewport.NeedRender;
end;
function TContext3D.GetPixelToPixelPolygonOffset: TPointF;
begin
Result := PointF(0, 0);
end;
function TContext3D.GetProjectionMatrix: TMatrix3D;
begin
Result := MatrixPerspectiveFovRH(cPI / 4, FWidth / FHeight, 1.0, 1000.0);
if (FPaintToMatrix.m41 <> 0) or (FPaintToMatrix.m11 <> 1) then
begin
Result := Matrix3DMultiply(Result, FPaintToMatrix);
end;
end;
procedure TContext3D.CreateBuffer;
begin
CreateDefaultShaders;
end;
procedure TContext3D.FreeBuffer;
begin
FreeDefaultShaders;
end;
const
DX9VS2BIN_NoLight: array [0..603] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $3D, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $C8, $00, $00, $00, $00, $03, $FE, $FF, $04, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $C1, $00, $00, $00,
$6C, $00, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $78, $00, $00, $00, $00, $00, $00, $00, $88, $00, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $98, $00, $00, $00, $00, $00, $00, $00,
$A8, $00, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $98, $00, $00, $00, $00, $00, $00, $00, $B9, $00, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $98, $00, $00, $00, $00, $00, $00, $00,
$4D, $56, $50, $4D, $61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75,
$73, $65, $00, $AB, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $6F, $70, $74,
$69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65, $72, $20, $43,
$6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $AB, $AB, $AB, $51, $00, $00, $05, $04, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $80, $3F, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02,
$00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80,
$00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0, $1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $03, $E0, $01, $00, $00, $02, $00, $00, $07, $80, $04, $00, $E4, $A0,
$02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $8C, $00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80,
$01, $00, $E4, $90, $0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $80, $00, $00, $00, $80, $01, $00, $E4, $80, $0E, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80,
$11, $00, $24, $A0, $00, $00, $95, $80, $00, $00, $6A, $80, $02, $00, $00, $03, $01, $00, $0F, $80, $01, $00, $E4, $80, $00, $00, $E4, $81, $23, $00, $00, $02, $02, $00, $01, $80, $0C, $00, $00, $A0,
$0D, $00, $00, $03, $02, $00, $01, $80, $02, $00, $00, $81, $02, $00, $00, $80, $04, $00, $00, $04, $01, $00, $0F, $E0, $02, $00, $00, $80, $01, $00, $E4, $80, $00, $00, $E4, $80, $05, $00, $00, $03,
$00, $00, $0F, $80, $01, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80,
$02, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $01, $00, $00, $02, $02, $00, $03, $E0, $02, $00, $E4, $90,
$FF, $FF, $00, $00
);
DX9VS2BIN_1Light: array [0..2267] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $8E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $0F, $02, $00, $00, $00, $03, $FE, $FF, $0A, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $08, $02, $00, $00,
$E4, $00, $00, $00, $02, $00, $13, $00, $07, $00, $4E, $00, $70, $01, $00, $00, $00, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$9C, $01, $00, $00, $02, $00, $10, $00, $01, $00, $42, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $AC, $01, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$BB, $01, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $CC, $01, $00, $00, $02, $00, $12, $00, $01, $00, $4A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$D9, $01, $00, $00, $02, $00, $0F, $00, $01, $00, $3E, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $EA, $01, $00, $00, $02, $00, $04, $00, $04, $00, $12, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$F4, $01, $00, $00, $02, $00, $08, $00, $03, $00, $22, $00, $8C, $01, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$4C, $69, $67, $68, $74, $73, $00, $4F, $70, $74, $73, $00, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $41, $74, $74, $6E, $00, $50, $6F, $73, $00, $44, $69, $72,
$00, $44, $69, $66, $66, $75, $73, $65, $43, $6F, $6C, $6F, $72, $00, $53, $70, $65, $63, $75, $6C, $61, $72, $43, $6F, $6C, $6F, $72, $00, $41, $6D, $62, $69, $65, $6E, $74, $43, $6F, $6C, $6F, $72,
$00, $AB, $AB, $AB, $EB, $00, $00, $00, $F0, $00, $00, $00, $00, $01, $00, $00, $F0, $00, $00, $00, $05, $01, $00, $00, $F0, $00, $00, $00, $09, $01, $00, $00, $F0, $00, $00, $00, $0D, $01, $00, $00,
$F0, $00, $00, $00, $1A, $01, $00, $00, $F0, $00, $00, $00, $28, $01, $00, $00, $F0, $00, $00, $00, $05, $00, $00, $00, $01, $00, $1C, $00, $01, $00, $07, $00, $38, $01, $00, $00, $4D, $56, $50, $4D,
$61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $41, $6D, $62, $69, $65, $6E, $74, $00,
$4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75, $73, $65, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $4D, $61, $74, $65, $72, $69, $61, $6C,
$4F, $70, $74, $73, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $53, $70, $65, $63, $75, $6C, $61, $72, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65, $77, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65,
$77, $49, $54, $00, $6F, $70, $74, $69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53,
$68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $0B, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $C0, $00, $00, $80, $3F,
$1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $03, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80, $02, $00, $0F, $90, $1F, $00, $00, $02,
$05, $00, $00, $80, $03, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0, $1F, $00, $00, $02, $05, $00, $00, $80,
$02, $00, $03, $E0, $01, $00, $00, $02, $02, $00, $03, $E0, $03, $00, $E4, $90, $23, $00, $00, $02, $00, $00, $01, $80, $0C, $00, $00, $A0, $29, $00, $03, $02, $00, $00, $00, $81, $00, $00, $00, $80,
$01, $00, $00, $02, $00, $00, $01, $80, $0B, $00, $00, $A0, $02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $8C,
$00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80, $02, $00, $E4, $90, $0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $E0, $00, $00, $00, $80, $01, $00, $E4, $80,
$0E, $00, $E4, $A0, $2A, $00, $00, $00, $05, $00, $00, $03, $00, $00, $07, $80, $09, $00, $E4, $A0, $01, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80, $08, $00, $E4, $A0, $01, $00, $00, $90,
$00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80, $0A, $00, $E4, $A0, $01, $00, $AA, $90, $00, $00, $E4, $80, $24, $00, $00, $02, $01, $00, $07, $80, $00, $00, $E4, $80, $05, $00, $00, $03,
$00, $00, $07, $80, $05, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80, $04, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80,
$06, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $07, $80, $00, $00, $E4, $80, $07, $00, $E4, $A0, $23, $00, $00, $02, $00, $00, $08, $80, $13, $00, $55, $A0,
$29, $00, $03, $02, $00, $00, $FF, $81, $00, $00, $FF, $80, $08, $00, $00, $03, $00, $00, $08, $80, $01, $00, $E4, $81, $16, $00, $E4, $A0, $0B, $00, $00, $03, $00, $00, $08, $80, $00, $00, $FF, $80,
$0B, $00, $55, $A0, $0C, $00, $00, $03, $01, $00, $08, $80, $0B, $00, $55, $A0, $00, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $01, $80, $00, $00, $E4, $80, $00, $00, $E4, $80, $07, $00, $00, $02,
$02, $00, $01, $80, $02, $00, $00, $80, $04, $00, $00, $04, $02, $00, $07, $80, $00, $00, $E4, $80, $02, $00, $00, $81, $16, $00, $E4, $A0, $24, $00, $00, $02, $03, $00, $07, $80, $02, $00, $E4, $80,
$08, $00, $00, $03, $02, $00, $01, $80, $01, $00, $E4, $81, $03, $00, $E4, $80, $0B, $00, $00, $03, $02, $00, $01, $80, $02, $00, $00, $80, $0B, $00, $55, $A0, $20, $00, $00, $03, $03, $00, $01, $80,
$02, $00, $00, $80, $12, $00, $00, $A0, $05, $00, $00, $03, $02, $00, $0F, $80, $03, $00, $00, $80, $18, $00, $E4, $A0, $05, $00, $00, $03, $02, $00, $0F, $80, $01, $00, $FF, $80, $02, $00, $E4, $80,
$05, $00, $00, $03, $03, $00, $0F, $80, $00, $00, $FF, $80, $17, $00, $E4, $A0, $2A, $00, $00, $00, $01, $00, $00, $02, $03, $00, $0F, $80, $0B, $00, $55, $A0, $01, $00, $00, $02, $02, $00, $0F, $80,
$0B, $00, $55, $A0, $2B, $00, $00, $00, $01, $00, $00, $02, $04, $00, $0F, $80, $0B, $00, $E4, $A0, $02, $00, $00, $03, $04, $00, $05, $80, $04, $00, $E4, $80, $13, $00, $55, $A0, $29, $00, $03, $02,
$04, $00, $00, $8C, $04, $00, $00, $8B, $08, $00, $00, $03, $00, $00, $08, $80, $00, $00, $E4, $80, $00, $00, $E4, $80, $07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $02, $00, $00, $03,
$05, $00, $07, $80, $00, $00, $E4, $80, $15, $00, $E4, $A1, $08, $00, $00, $03, $01, $00, $08, $80, $05, $00, $E4, $80, $05, $00, $E4, $80, $07, $00, $00, $02, $01, $00, $08, $80, $01, $00, $FF, $80,
$05, $00, $00, $03, $05, $00, $07, $80, $05, $00, $E4, $80, $01, $00, $FF, $80, $04, $00, $00, $04, $06, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $81, $05, $00, $E4, $81, $24, $00, $00, $02,
$07, $00, $07, $80, $06, $00, $E4, $80, $08, $00, $00, $03, $00, $00, $08, $80, $01, $00, $E4, $80, $07, $00, $E4, $80, $0B, $00, $00, $03, $00, $00, $08, $80, $00, $00, $FF, $80, $0B, $00, $55, $A0,
$20, $00, $00, $03, $04, $00, $01, $80, $00, $00, $FF, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $00, $00, $08, $80, $01, $00, $FF, $80, $05, $00, $00, $03, $01, $00, $08, $80, $00, $00, $FF, $80,
$00, $00, $FF, $80, $04, $00, $00, $04, $00, $00, $08, $80, $14, $00, $55, $A0, $00, $00, $FF, $80, $14, $00, $00, $A0, $04, $00, $00, $04, $00, $00, $08, $80, $01, $00, $FF, $80, $14, $00, $AA, $A0,
$00, $00, $FF, $80, $06, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $08, $00, $00, $03, $01, $00, $08, $80, $01, $00, $E4, $80, $05, $00, $E4, $81, $0B, $00, $00, $03, $01, $00, $08, $80,
$01, $00, $FF, $80, $0B, $00, $55, $A0, $0C, $00, $00, $03, $05, $00, $01, $80, $0B, $00, $55, $A0, $01, $00, $FF, $80, $05, $00, $00, $03, $06, $00, $0F, $80, $04, $00, $00, $80, $18, $00, $E4, $A0,
$04, $00, $00, $04, $02, $00, $0F, $80, $05, $00, $00, $80, $06, $00, $E4, $80, $02, $00, $E4, $80, $05, $00, $00, $03, $05, $00, $0F, $80, $01, $00, $FF, $80, $17, $00, $E4, $A0, $04, $00, $00, $04,
$03, $00, $0F, $80, $05, $00, $E4, $80, $00, $00, $FF, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $29, $00, $03, $02, $04, $00, $AA, $8C, $04, $00, $AA, $8B, $08, $00, $00, $03, $00, $00, $08, $80,
$00, $00, $E4, $80, $00, $00, $E4, $80, $07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $02, $00, $00, $03, $05, $00, $07, $80, $00, $00, $E4, $80, $15, $00, $E4, $A1, $08, $00, $00, $03,
$01, $00, $08, $80, $05, $00, $E4, $80, $05, $00, $E4, $80, $07, $00, $00, $02, $01, $00, $08, $80, $01, $00, $FF, $80, $05, $00, $00, $03, $05, $00, $07, $80, $05, $00, $E4, $80, $01, $00, $FF, $80,
$04, $00, $00, $04, $00, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $81, $05, $00, $E4, $81, $24, $00, $00, $02, $06, $00, $07, $80, $00, $00, $E4, $80, $08, $00, $00, $03, $00, $00, $01, $80,
$01, $00, $E4, $80, $06, $00, $E4, $80, $06, $00, $00, $02, $00, $00, $02, $80, $01, $00, $FF, $80, $05, $00, $00, $03, $00, $00, $04, $80, $00, $00, $55, $80, $00, $00, $55, $80, $04, $00, $00, $04,
$00, $00, $02, $80, $14, $00, $55, $A0, $00, $00, $55, $80, $14, $00, $00, $A0, $04, $00, $00, $04, $00, $00, $02, $80, $00, $00, $AA, $80, $14, $00, $AA, $A0, $00, $00, $55, $80, $06, $00, $00, $02,
$00, $00, $02, $80, $00, $00, $55, $80, $08, $00, $00, $03, $00, $00, $04, $80, $05, $00, $E4, $80, $16, $00, $E4, $A0, $20, $00, $00, $03, $01, $00, $08, $80, $00, $00, $AA, $80, $13, $00, $FF, $A0,
$0C, $00, $00, $03, $00, $00, $04, $80, $13, $00, $AA, $A0, $00, $00, $AA, $80, $05, $00, $00, $03, $00, $00, $04, $80, $01, $00, $FF, $80, $00, $00, $AA, $80, $05, $00, $00, $03, $00, $00, $02, $80,
$00, $00, $55, $80, $00, $00, $AA, $80, $0B, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0B, $00, $55, $A0, $20, $00, $00, $03, $01, $00, $08, $80, $00, $00, $00, $80, $12, $00, $00, $A0,
$08, $00, $00, $03, $00, $00, $01, $80, $01, $00, $E4, $80, $05, $00, $E4, $81, $0B, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0B, $00, $55, $A0, $0C, $00, $00, $03, $00, $00, $04, $80,
$0B, $00, $55, $A0, $00, $00, $00, $80, $05, $00, $00, $03, $01, $00, $0F, $80, $01, $00, $FF, $80, $18, $00, $E4, $A0, $04, $00, $00, $04, $02, $00, $0F, $80, $00, $00, $AA, $80, $01, $00, $E4, $80,
$02, $00, $E4, $80, $05, $00, $00, $03, $01, $00, $0F, $80, $00, $00, $00, $80, $17, $00, $E4, $A0, $04, $00, $00, $04, $03, $00, $0F, $80, $01, $00, $E4, $80, $00, $00, $55, $80, $03, $00, $E4, $80,
$2B, $00, $00, $00, $05, $00, $00, $03, $00, $00, $0F, $80, $03, $00, $E4, $80, $0E, $00, $E4, $A0, $01, $00, $00, $02, $01, $00, $0F, $80, $19, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80,
$01, $00, $E4, $80, $10, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $80, $0F, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $0F, $80,
$11, $00, $24, $A0, $04, $00, $7F, $80, $04, $00, $D5, $80, $02, $00, $00, $03, $01, $00, $0F, $E0, $00, $00, $E4, $80, $01, $00, $E4, $80, $2B, $00, $00, $00, $05, $00, $00, $03, $00, $00, $0F, $80,
$01, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $A0,
$00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $FF, $FF, $00, $00
);
DX9VS2BIN_2Light: array [0..2439] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $8E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $0F, $02, $00, $00, $00, $03, $FE, $FF, $0A, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $08, $02, $00, $00,
$E4, $00, $00, $00, $02, $00, $13, $00, $0E, $00, $4E, $00, $70, $01, $00, $00, $00, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$9C, $01, $00, $00, $02, $00, $10, $00, $01, $00, $42, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $AC, $01, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$BB, $01, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $CC, $01, $00, $00, $02, $00, $12, $00, $01, $00, $4A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$D9, $01, $00, $00, $02, $00, $0F, $00, $01, $00, $3E, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $EA, $01, $00, $00, $02, $00, $04, $00, $04, $00, $12, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$F4, $01, $00, $00, $02, $00, $08, $00, $03, $00, $22, $00, $8C, $01, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$4C, $69, $67, $68, $74, $73, $00, $4F, $70, $74, $73, $00, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $41, $74, $74, $6E, $00, $50, $6F, $73, $00, $44, $69, $72,
$00, $44, $69, $66, $66, $75, $73, $65, $43, $6F, $6C, $6F, $72, $00, $53, $70, $65, $63, $75, $6C, $61, $72, $43, $6F, $6C, $6F, $72, $00, $41, $6D, $62, $69, $65, $6E, $74, $43, $6F, $6C, $6F, $72,
$00, $AB, $AB, $AB, $EB, $00, $00, $00, $F0, $00, $00, $00, $00, $01, $00, $00, $F0, $00, $00, $00, $05, $01, $00, $00, $F0, $00, $00, $00, $09, $01, $00, $00, $F0, $00, $00, $00, $0D, $01, $00, $00,
$F0, $00, $00, $00, $1A, $01, $00, $00, $F0, $00, $00, $00, $28, $01, $00, $00, $F0, $00, $00, $00, $05, $00, $00, $00, $01, $00, $1C, $00, $02, $00, $07, $00, $38, $01, $00, $00, $4D, $56, $50, $4D,
$61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $41, $6D, $62, $69, $65, $6E, $74, $00,
$4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75, $73, $65, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $4D, $61, $74, $65, $72, $69, $61, $6C,
$4F, $70, $74, $73, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $53, $70, $65, $63, $75, $6C, $61, $72, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65, $77, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65,
$77, $49, $54, $00, $6F, $70, $74, $69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53,
$68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $0B, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $40, $00, $00, $00, $00, $00, $00, $E0, $40,
$30, $00, $00, $05, $00, $00, $0F, $F0, $02, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02,
$03, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80, $02, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $03, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80,
$00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0, $1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $03, $E0, $01, $00, $00, $02, $02, $00, $03, $E0, $03, $00, $E4, $90,
$23, $00, $00, $02, $00, $00, $01, $80, $0C, $00, $00, $A0, $29, $00, $03, $02, $00, $00, $00, $81, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $01, $80, $0B, $00, $00, $A0, $02, $00, $00, $03,
$00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $8C, $00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80, $02, $00, $E4, $90,
$0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $E0, $00, $00, $00, $80, $01, $00, $E4, $80, $0E, $00, $E4, $A0, $2A, $00, $00, $00, $05, $00, $00, $03, $00, $00, $07, $80,
$05, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80, $04, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80, $06, $00, $E4, $A0,
$00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $07, $80, $00, $00, $E4, $80, $07, $00, $E4, $A0, $08, $00, $00, $03, $00, $00, $08, $80, $00, $00, $E4, $80, $00, $00, $E4, $80,
$07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $05, $00, $00, $03, $01, $00, $07, $80, $09, $00, $E4, $A0, $01, $00, $55, $90, $04, $00, $00, $04, $01, $00, $07, $80, $08, $00, $E4, $A0,
$01, $00, $00, $90, $01, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $07, $80, $0A, $00, $E4, $A0, $01, $00, $AA, $90, $01, $00, $E4, $80, $24, $00, $00, $02, $02, $00, $07, $80, $01, $00, $E4, $80,
$05, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $80, $01, $00, $00, $02, $03, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $04, $00, $0F, $80, $0B, $00, $AA, $A0,
$01, $00, $00, $02, $05, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $01, $00, $08, $80, $0B, $00, $AA, $A0, $26, $00, $00, $01, $00, $00, $E4, $F0, $05, $00, $00, $03, $02, $00, $08, $80,
$01, $00, $FF, $80, $0B, $00, $FF, $A0, $2E, $00, $00, $02, $00, $00, $01, $B0, $02, $00, $FF, $80, $02, $00, $00, $04, $05, $00, $0F, $80, $05, $00, $E4, $80, $19, $20, $E4, $A0, $00, $00, $00, $B0,
$23, $00, $00, $03, $02, $00, $08, $80, $13, $20, $55, $A0, $00, $00, $00, $B0, $29, $00, $03, $02, $02, $00, $FF, $81, $02, $00, $FF, $80, $08, $00, $00, $04, $02, $00, $08, $80, $02, $00, $E4, $81,
$16, $20, $E4, $A0, $00, $00, $00, $B0, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80,
$04, $00, $00, $05, $06, $00, $0E, $80, $00, $00, $90, $80, $00, $00, $FF, $81, $16, $20, $90, $A0, $00, $00, $00, $B0, $24, $00, $00, $02, $07, $00, $07, $80, $06, $00, $F9, $80, $08, $00, $00, $03,
$06, $00, $02, $80, $02, $00, $E4, $81, $07, $00, $E4, $80, $0B, $00, $00, $03, $06, $00, $02, $80, $06, $00, $55, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $07, $00, $01, $80, $06, $00, $55, $80,
$12, $00, $00, $A0, $05, $00, $00, $04, $07, $00, $0F, $80, $07, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $07, $00, $E4, $80,
$04, $00, $E4, $80, $04, $00, $00, $05, $03, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $03, $00, $E4, $80, $2B, $00, $00, $00, $01, $00, $00, $02, $06, $00, $03, $80,
$0B, $00, $E4, $A0, $02, $00, $00, $04, $06, $00, $03, $80, $06, $00, $E4, $8C, $13, $20, $55, $A0, $00, $00, $00, $B0, $29, $00, $03, $02, $06, $00, $00, $8C, $06, $00, $00, $8B, $02, $00, $00, $04,
$06, $00, $0D, $80, $00, $00, $94, $80, $15, $20, $94, $A1, $00, $00, $00, $B0, $08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $F8, $80, $06, $00, $F8, $80, $07, $00, $00, $02, $02, $00, $08, $80,
$02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $F8, $80, $02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03,
$07, $00, $01, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $07, $00, $01, $80, $07, $00, $00, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $08, $00, $01, $80, $07, $00, $00, $80,
$12, $00, $00, $A0, $06, $00, $00, $02, $07, $00, $01, $80, $02, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $02, $80, $07, $00, $00, $80, $07, $00, $00, $80, $04, $00, $00, $06, $07, $00, $01, $80,
$14, $20, $55, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $14, $20, $00, $A0, $00, $00, $00, $B0, $04, $00, $00, $05, $07, $00, $01, $80, $07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0,
$07, $00, $00, $80, $06, $00, $00, $02, $07, $00, $01, $80, $07, $00, $00, $80, $05, $00, $00, $03, $06, $00, $0D, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80,
$02, $00, $E4, $80, $06, $00, $F8, $81, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80,
$05, $00, $00, $04, $08, $00, $0F, $80, $08, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $08, $00, $E4, $80, $04, $00, $E4, $80,
$05, $00, $00, $04, $08, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $08, $00, $E4, $80, $07, $00, $00, $80, $03, $00, $E4, $80,
$2B, $00, $00, $00, $29, $00, $03, $02, $06, $00, $55, $8C, $06, $00, $55, $8B, $02, $00, $00, $04, $06, $00, $07, $80, $00, $00, $E4, $80, $15, $20, $E4, $A1, $00, $00, $00, $B0, $08, $00, $00, $03,
$02, $00, $08, $80, $06, $00, $E4, $80, $06, $00, $E4, $80, $07, $00, $00, $02, $02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $81,
$01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03, $06, $00, $08, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $06, $00, $08, $80,
$06, $00, $FF, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $07, $00, $01, $80, $06, $00, $FF, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $06, $00, $08, $80, $02, $00, $FF, $80, $05, $00, $00, $03,
$07, $00, $02, $80, $06, $00, $FF, $80, $06, $00, $FF, $80, $04, $00, $00, $06, $06, $00, $08, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $14, $20, $00, $A0, $00, $00, $00, $B0,
$04, $00, $00, $05, $06, $00, $08, $80, $07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $06, $00, $00, $02, $06, $00, $08, $80, $06, $00, $FF, $80, $05, $00, $00, $03,
$06, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $80, $06, $00, $E4, $81, $08, $00, $00, $04, $06, $00, $01, $80, $06, $00, $E4, $80,
$16, $20, $E4, $A0, $00, $00, $00, $B0, $20, $00, $00, $04, $07, $00, $02, $80, $06, $00, $00, $80, $13, $20, $FF, $A0, $00, $00, $00, $B0, $0C, $00, $00, $04, $06, $00, $01, $80, $13, $20, $AA, $A0,
$00, $00, $00, $B0, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $07, $00, $55, $80, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $06, $00, $FF, $80, $06, $00, $00, $80,
$0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $02, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $07, $00, $0F, $80,
$07, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $55, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04, $07, $00, $0F, $80,
$02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $00, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $02, $00, $00, $03,
$01, $00, $08, $80, $01, $00, $FF, $80, $0B, $00, $00, $A1, $27, $00, $00, $00, $05, $00, $00, $03, $00, $00, $0F, $80, $03, $00, $E4, $80, $0E, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80,
$05, $00, $E4, $80, $10, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $04, $00, $E4, $80, $0F, $00, $E4, $A0, $00, $00, $E4, $80, $01, $00, $00, $02, $01, $00, $05, $80,
$0B, $00, $E4, $A0, $04, $00, $00, $04, $01, $00, $0F, $80, $11, $00, $24, $A0, $01, $00, $80, $8B, $01, $00, $2A, $8B, $02, $00, $00, $03, $01, $00, $0F, $E0, $00, $00, $E4, $80, $01, $00, $E4, $80,
$2B, $00, $00, $00, $05, $00, $00, $03, $00, $00, $0F, $80, $01, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80,
$04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $FF, $FF, $00, $00
);
DX9VS2BIN_3Light: array [0..2463] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $8E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $0F, $02, $00, $00, $00, $03, $FE, $FF, $0A, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $08, $02, $00, $00,
$E4, $00, $00, $00, $02, $00, $13, $00, $15, $00, $4E, $00, $70, $01, $00, $00, $00, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$9C, $01, $00, $00, $02, $00, $10, $00, $01, $00, $42, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $AC, $01, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$BB, $01, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $CC, $01, $00, $00, $02, $00, $12, $00, $01, $00, $4A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$D9, $01, $00, $00, $02, $00, $0F, $00, $01, $00, $3E, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $EA, $01, $00, $00, $02, $00, $04, $00, $04, $00, $12, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$F4, $01, $00, $00, $02, $00, $08, $00, $03, $00, $22, $00, $8C, $01, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$4C, $69, $67, $68, $74, $73, $00, $4F, $70, $74, $73, $00, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $41, $74, $74, $6E, $00, $50, $6F, $73, $00, $44, $69, $72,
$00, $44, $69, $66, $66, $75, $73, $65, $43, $6F, $6C, $6F, $72, $00, $53, $70, $65, $63, $75, $6C, $61, $72, $43, $6F, $6C, $6F, $72, $00, $41, $6D, $62, $69, $65, $6E, $74, $43, $6F, $6C, $6F, $72,
$00, $AB, $AB, $AB, $EB, $00, $00, $00, $F0, $00, $00, $00, $00, $01, $00, $00, $F0, $00, $00, $00, $05, $01, $00, $00, $F0, $00, $00, $00, $09, $01, $00, $00, $F0, $00, $00, $00, $0D, $01, $00, $00,
$F0, $00, $00, $00, $1A, $01, $00, $00, $F0, $00, $00, $00, $28, $01, $00, $00, $F0, $00, $00, $00, $05, $00, $00, $00, $01, $00, $1C, $00, $03, $00, $07, $00, $38, $01, $00, $00, $4D, $56, $50, $4D,
$61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $41, $6D, $62, $69, $65, $6E, $74, $00,
$4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75, $73, $65, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $4D, $61, $74, $65, $72, $69, $61, $6C,
$4F, $70, $74, $73, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $53, $70, $65, $63, $75, $6C, $61, $72, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65, $77, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65,
$77, $49, $54, $00, $6F, $70, $74, $69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53,
$68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $0B, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $E0, $40,
$51, $00, $00, $05, $0D, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $C0, $00, $00, $00, $00, $00, $00, $00, $00, $30, $00, $00, $05, $00, $00, $0F, $F0, $03, $00, $00, $00, $00, $00, $00, $00,
$00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $03, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80,
$02, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $03, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0,
$1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $03, $E0, $01, $00, $00, $02, $02, $00, $03, $E0, $03, $00, $E4, $90, $23, $00, $00, $02, $00, $00, $01, $80, $0C, $00, $00, $A0, $29, $00, $03, $02,
$00, $00, $00, $81, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $01, $80, $0B, $00, $00, $A0, $02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03,
$00, $00, $01, $80, $00, $00, $00, $8C, $00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80, $02, $00, $E4, $90, $0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $E0,
$00, $00, $00, $80, $01, $00, $E4, $80, $0E, $00, $E4, $A0, $2A, $00, $00, $00, $05, $00, $00, $03, $00, $00, $07, $80, $05, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80,
$04, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80, $06, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $07, $80,
$00, $00, $E4, $80, $07, $00, $E4, $A0, $08, $00, $00, $03, $00, $00, $08, $80, $00, $00, $E4, $80, $00, $00, $E4, $80, $07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $05, $00, $00, $03,
$01, $00, $07, $80, $09, $00, $E4, $A0, $01, $00, $55, $90, $04, $00, $00, $04, $01, $00, $07, $80, $08, $00, $E4, $A0, $01, $00, $00, $90, $01, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $07, $80,
$0A, $00, $E4, $A0, $01, $00, $AA, $90, $01, $00, $E4, $80, $24, $00, $00, $02, $02, $00, $07, $80, $01, $00, $E4, $80, $05, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $80,
$01, $00, $00, $02, $03, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $04, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $05, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02,
$01, $00, $08, $80, $0B, $00, $AA, $A0, $26, $00, $00, $01, $00, $00, $E4, $F0, $05, $00, $00, $03, $02, $00, $08, $80, $01, $00, $FF, $80, $0B, $00, $FF, $A0, $2E, $00, $00, $02, $00, $00, $01, $B0,
$02, $00, $FF, $80, $02, $00, $00, $04, $05, $00, $0F, $80, $05, $00, $E4, $80, $19, $20, $E4, $A0, $00, $00, $00, $B0, $23, $00, $00, $03, $02, $00, $08, $80, $13, $20, $55, $A0, $00, $00, $00, $B0,
$29, $00, $03, $02, $02, $00, $FF, $81, $02, $00, $FF, $80, $08, $00, $00, $04, $02, $00, $08, $80, $02, $00, $E4, $81, $16, $20, $E4, $A0, $00, $00, $00, $B0, $0B, $00, $00, $03, $02, $00, $08, $80,
$02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $04, $00, $00, $05, $06, $00, $0E, $80, $00, $00, $90, $80, $00, $00, $FF, $81,
$16, $20, $90, $A0, $00, $00, $00, $B0, $24, $00, $00, $02, $07, $00, $07, $80, $06, $00, $F9, $80, $08, $00, $00, $03, $06, $00, $02, $80, $02, $00, $E4, $81, $07, $00, $E4, $80, $0B, $00, $00, $03,
$06, $00, $02, $80, $06, $00, $55, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $07, $00, $01, $80, $06, $00, $55, $80, $12, $00, $00, $A0, $05, $00, $00, $04, $07, $00, $0F, $80, $07, $00, $00, $80,
$18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $04, $00, $00, $05, $03, $00, $0F, $80, $02, $00, $FF, $80,
$17, $20, $E4, $A0, $00, $00, $00, $B0, $03, $00, $E4, $80, $2B, $00, $00, $00, $01, $00, $00, $03, $06, $00, $02, $80, $13, $20, $55, $A0, $00, $00, $00, $B0, $02, $00, $00, $03, $06, $00, $03, $80,
$06, $00, $55, $80, $0D, $00, $E4, $A0, $29, $00, $03, $02, $06, $00, $00, $8C, $06, $00, $00, $8B, $02, $00, $00, $04, $06, $00, $0D, $80, $00, $00, $94, $80, $15, $20, $94, $A1, $00, $00, $00, $B0,
$08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $F8, $80, $06, $00, $F8, $80, $07, $00, $00, $02, $02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $F8, $80,
$02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03, $07, $00, $01, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03,
$07, $00, $01, $80, $07, $00, $00, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $08, $00, $01, $80, $07, $00, $00, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $07, $00, $01, $80, $02, $00, $FF, $80,
$05, $00, $00, $03, $07, $00, $02, $80, $07, $00, $00, $80, $07, $00, $00, $80, $04, $00, $00, $06, $07, $00, $01, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $14, $20, $00, $A0,
$00, $00, $00, $B0, $04, $00, $00, $05, $07, $00, $01, $80, $07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $06, $00, $00, $02, $07, $00, $01, $80, $07, $00, $00, $80,
$05, $00, $00, $03, $06, $00, $0D, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $80, $06, $00, $F8, $81, $0B, $00, $00, $03, $02, $00, $08, $80,
$02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $08, $00, $0F, $80, $08, $00, $00, $80, $18, $20, $E4, $A0,
$00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $08, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04, $08, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0,
$00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $08, $00, $E4, $80, $07, $00, $00, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $29, $00, $03, $02, $06, $00, $55, $8C, $06, $00, $55, $8B,
$02, $00, $00, $04, $06, $00, $07, $80, $00, $00, $E4, $80, $15, $20, $E4, $A1, $00, $00, $00, $B0, $08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $E4, $80, $06, $00, $E4, $80, $07, $00, $00, $02,
$02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80,
$08, $00, $00, $03, $06, $00, $08, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $06, $00, $08, $80, $06, $00, $FF, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $07, $00, $01, $80,
$06, $00, $FF, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $06, $00, $08, $80, $02, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $02, $80, $06, $00, $FF, $80, $06, $00, $FF, $80, $04, $00, $00, $06,
$06, $00, $08, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $14, $20, $00, $A0, $00, $00, $00, $B0, $04, $00, $00, $05, $06, $00, $08, $80, $07, $00, $55, $80, $14, $20, $AA, $A0,
$00, $00, $00, $B0, $06, $00, $FF, $80, $06, $00, $00, $02, $06, $00, $08, $80, $06, $00, $FF, $80, $05, $00, $00, $03, $06, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03,
$02, $00, $08, $80, $02, $00, $E4, $80, $06, $00, $E4, $81, $08, $00, $00, $04, $06, $00, $01, $80, $06, $00, $E4, $80, $16, $20, $E4, $A0, $00, $00, $00, $B0, $20, $00, $00, $04, $07, $00, $02, $80,
$06, $00, $00, $80, $13, $20, $FF, $A0, $00, $00, $00, $B0, $0C, $00, $00, $04, $06, $00, $01, $80, $13, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80,
$07, $00, $55, $80, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $06, $00, $FF, $80, $06, $00, $00, $80, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0,
$0C, $00, $00, $03, $06, $00, $02, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $07, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04,
$04, $00, $0F, $80, $06, $00, $55, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04,
$03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $00, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $02, $00, $00, $03, $01, $00, $08, $80, $01, $00, $FF, $80, $0B, $00, $00, $A1, $27, $00, $00, $00,
$05, $00, $00, $03, $00, $00, $0F, $80, $03, $00, $E4, $80, $0E, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80, $05, $00, $E4, $80, $10, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04,
$00, $00, $0F, $80, $04, $00, $E4, $80, $0F, $00, $E4, $A0, $00, $00, $E4, $80, $01, $00, $00, $02, $01, $00, $05, $80, $0B, $00, $E4, $A0, $04, $00, $00, $04, $01, $00, $0F, $80, $11, $00, $24, $A0,
$01, $00, $80, $8B, $01, $00, $2A, $8B, $02, $00, $00, $03, $01, $00, $0F, $E0, $00, $00, $E4, $80, $01, $00, $E4, $80, $2B, $00, $00, $00, $05, $00, $00, $03, $00, $00, $0F, $80, $01, $00, $E4, $A0,
$00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $A0, $00, $00, $AA, $90,
$00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $FF, $FF, $00, $00
);
DX9VS2BIN_4Light: array [0..2483] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $8E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $0F, $02, $00, $00, $00, $03, $FE, $FF, $0A, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $08, $02, $00, $00,
$E4, $00, $00, $00, $02, $00, $13, $00, $1C, $00, $4E, $00, $70, $01, $00, $00, $00, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$9C, $01, $00, $00, $02, $00, $10, $00, $01, $00, $42, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $AC, $01, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$BB, $01, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $CC, $01, $00, $00, $02, $00, $12, $00, $01, $00, $4A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$D9, $01, $00, $00, $02, $00, $0F, $00, $01, $00, $3E, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $EA, $01, $00, $00, $02, $00, $04, $00, $04, $00, $12, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$F4, $01, $00, $00, $02, $00, $08, $00, $03, $00, $22, $00, $8C, $01, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$4C, $69, $67, $68, $74, $73, $00, $4F, $70, $74, $73, $00, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $41, $74, $74, $6E, $00, $50, $6F, $73, $00, $44, $69, $72,
$00, $44, $69, $66, $66, $75, $73, $65, $43, $6F, $6C, $6F, $72, $00, $53, $70, $65, $63, $75, $6C, $61, $72, $43, $6F, $6C, $6F, $72, $00, $41, $6D, $62, $69, $65, $6E, $74, $43, $6F, $6C, $6F, $72,
$00, $AB, $AB, $AB, $EB, $00, $00, $00, $F0, $00, $00, $00, $00, $01, $00, $00, $F0, $00, $00, $00, $05, $01, $00, $00, $F0, $00, $00, $00, $09, $01, $00, $00, $F0, $00, $00, $00, $0D, $01, $00, $00,
$F0, $00, $00, $00, $1A, $01, $00, $00, $F0, $00, $00, $00, $28, $01, $00, $00, $F0, $00, $00, $00, $05, $00, $00, $00, $01, $00, $1C, $00, $04, $00, $07, $00, $38, $01, $00, $00, $4D, $56, $50, $4D,
$61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $41, $6D, $62, $69, $65, $6E, $74, $00,
$4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75, $73, $65, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $4D, $61, $74, $65, $72, $69, $61, $6C,
$4F, $70, $74, $73, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $53, $70, $65, $63, $75, $6C, $61, $72, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65, $77, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65,
$77, $49, $54, $00, $6F, $70, $74, $69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53,
$68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $0B, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $E0, $40,
$51, $00, $00, $05, $0D, $00, $0F, $A0, $00, $00, $00, $C0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $00, $30, $00, $00, $05, $00, $00, $0F, $F0, $04, $00, $00, $00, $00, $00, $00, $00,
$00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $03, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80,
$02, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $03, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0,
$1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $03, $E0, $05, $00, $00, $03, $00, $00, $0F, $80, $01, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0,
$00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $02, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80,
$03, $00, $E4, $A0, $23, $00, $00, $02, $00, $00, $01, $80, $0C, $00, $00, $A0, $29, $00, $03, $02, $00, $00, $00, $81, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $01, $80, $0B, $00, $00, $A0,
$02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $8C, $00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80,
$02, $00, $E4, $90, $0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $E0, $00, $00, $00, $80, $01, $00, $E4, $80, $0E, $00, $E4, $A0, $2A, $00, $00, $00, $05, $00, $00, $03,
$00, $00, $07, $80, $05, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80, $04, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80,
$06, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $07, $80, $00, $00, $E4, $80, $07, $00, $E4, $A0, $08, $00, $00, $03, $00, $00, $08, $80, $00, $00, $E4, $80,
$00, $00, $E4, $80, $07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $05, $00, $00, $03, $01, $00, $07, $80, $09, $00, $E4, $A0, $01, $00, $55, $90, $04, $00, $00, $04, $01, $00, $07, $80,
$08, $00, $E4, $A0, $01, $00, $00, $90, $01, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $07, $80, $0A, $00, $E4, $A0, $01, $00, $AA, $90, $01, $00, $E4, $80, $24, $00, $00, $02, $02, $00, $07, $80,
$01, $00, $E4, $80, $05, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $80, $01, $00, $00, $02, $03, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $04, $00, $0F, $80,
$0B, $00, $AA, $A0, $01, $00, $00, $02, $05, $00, $0F, $80, $0B, $00, $AA, $A0, $01, $00, $00, $02, $01, $00, $08, $80, $0B, $00, $AA, $A0, $26, $00, $00, $01, $00, $00, $E4, $F0, $05, $00, $00, $03,
$02, $00, $08, $80, $01, $00, $FF, $80, $0B, $00, $FF, $A0, $2E, $00, $00, $02, $00, $00, $01, $B0, $02, $00, $FF, $80, $02, $00, $00, $04, $05, $00, $0F, $80, $05, $00, $E4, $80, $19, $20, $E4, $A0,
$00, $00, $00, $B0, $01, $00, $00, $03, $06, $00, $02, $80, $13, $20, $55, $A0, $00, $00, $00, $B0, $02, $00, $00, $03, $06, $00, $03, $80, $06, $00, $55, $80, $0D, $00, $E4, $A0, $29, $00, $03, $02,
$06, $00, $00, $8C, $06, $00, $00, $8B, $02, $00, $00, $04, $06, $00, $0D, $80, $00, $00, $94, $80, $15, $20, $94, $A1, $00, $00, $00, $B0, $08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $F8, $80,
$06, $00, $F8, $80, $07, $00, $00, $02, $02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $F8, $80, $02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02,
$08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03, $07, $00, $01, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $07, $00, $01, $80, $07, $00, $00, $80, $0B, $00, $AA, $A0,
$20, $00, $00, $03, $08, $00, $01, $80, $07, $00, $00, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $07, $00, $01, $80, $02, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $02, $80, $07, $00, $00, $80,
$07, $00, $00, $80, $04, $00, $00, $06, $07, $00, $01, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $14, $20, $00, $A0, $00, $00, $00, $B0, $04, $00, $00, $05, $07, $00, $01, $80,
$07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $06, $00, $00, $02, $07, $00, $01, $80, $07, $00, $00, $80, $05, $00, $00, $03, $06, $00, $0D, $80, $06, $00, $E4, $80,
$02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $80, $06, $00, $F8, $81, $08, $00, $00, $04, $06, $00, $01, $80, $06, $00, $F8, $80, $16, $20, $E4, $A0, $00, $00, $00, $B0,
$20, $00, $00, $04, $07, $00, $02, $80, $06, $00, $00, $80, $13, $20, $FF, $A0, $00, $00, $00, $B0, $0C, $00, $00, $04, $06, $00, $01, $80, $13, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $00, $80,
$05, $00, $00, $03, $06, $00, $01, $80, $07, $00, $55, $80, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $07, $00, $00, $80, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $04, $80,
$08, $00, $00, $80, $06, $00, $00, $80, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $08, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80,
$05, $00, $00, $04, $07, $00, $0F, $80, $06, $00, $AA, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $FF, $80, $07, $00, $E4, $80, $04, $00, $E4, $80,
$05, $00, $00, $04, $07, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $00, $80, $03, $00, $E4, $80,
$2B, $00, $00, $00, $29, $00, $03, $02, $06, $00, $55, $8C, $06, $00, $55, $8B, $02, $00, $00, $04, $06, $00, $07, $80, $00, $00, $E4, $80, $15, $20, $E4, $A1, $00, $00, $00, $B0, $08, $00, $00, $03,
$02, $00, $08, $80, $06, $00, $E4, $80, $06, $00, $E4, $80, $07, $00, $00, $02, $02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $81,
$01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03, $06, $00, $08, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $06, $00, $08, $80,
$06, $00, $FF, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $07, $00, $01, $80, $06, $00, $FF, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $06, $00, $08, $80, $02, $00, $FF, $80, $05, $00, $00, $03,
$07, $00, $02, $80, $06, $00, $FF, $80, $06, $00, $FF, $80, $04, $00, $00, $06, $06, $00, $08, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $14, $20, $00, $A0, $00, $00, $00, $B0,
$04, $00, $00, $05, $06, $00, $08, $80, $07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $06, $00, $00, $02, $06, $00, $08, $80, $06, $00, $FF, $80, $05, $00, $00, $03,
$07, $00, $01, $80, $07, $00, $00, $80, $06, $00, $FF, $80, $05, $00, $00, $03, $06, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $80,
$06, $00, $E4, $81, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04,
$07, $00, $0F, $80, $07, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04,
$07, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $FF, $80, $03, $00, $E4, $80, $2B, $00, $00, $00,
$23, $00, $00, $03, $02, $00, $08, $80, $13, $20, $55, $A0, $00, $00, $00, $B0, $29, $00, $03, $02, $02, $00, $FF, $81, $02, $00, $FF, $80, $04, $00, $00, $05, $06, $00, $07, $80, $00, $00, $E4, $80,
$00, $00, $FF, $81, $16, $20, $E4, $A0, $00, $00, $00, $B0, $24, $00, $00, $02, $07, $00, $07, $80, $06, $00, $E4, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $81, $07, $00, $E4, $80,
$0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $20, $00, $00, $03, $06, $00, $01, $80, $02, $00, $FF, $80, $12, $00, $00, $A0, $08, $00, $00, $04, $02, $00, $08, $80,
$02, $00, $E4, $81, $16, $20, $E4, $A0, $00, $00, $00, $B0, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0B, $00, $AA, $A0, $04, $00, $00, $05, $03, $00, $0F, $80, $17, $20, $E4, $A0,
$00, $00, $00, $B0, $02, $00, $FF, $80, $03, $00, $E4, $80, $0C, $00, $00, $03, $02, $00, $08, $80, $0B, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $06, $00, $0F, $80, $06, $00, $00, $80,
$18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $02, $00, $FF, $80, $06, $00, $E4, $80, $04, $00, $E4, $80, $2B, $00, $00, $00, $02, $00, $00, $03, $01, $00, $08, $80,
$01, $00, $FF, $80, $0B, $00, $00, $A1, $27, $00, $00, $00, $01, $00, $00, $02, $00, $00, $05, $80, $0B, $00, $E4, $A0, $04, $00, $00, $04, $00, $00, $0F, $80, $11, $00, $24, $A0, $00, $00, $80, $8B,
$00, $00, $2A, $8B, $04, $00, $00, $04, $00, $00, $0F, $80, $05, $00, $E4, $80, $10, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $0F, $80, $03, $00, $E4, $80, $0E, $00, $E4, $A0,
$00, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $1F, $E0, $04, $00, $E4, $80, $0F, $00, $E4, $A0, $00, $00, $E4, $80, $2B, $00, $00, $00, $01, $00, $00, $02, $02, $00, $03, $E0, $03, $00, $E4, $90,
$FF, $FF, $00, $00
);
DX9VS2BIN_Full: array [0..2515] of byte = (
$00, $03, $FE, $FF, $FE, $FF, $8E, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $0F, $02, $00, $00, $00, $03, $FE, $FF, $0A, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $08, $02, $00, $00,
$E4, $00, $00, $00, $02, $00, $13, $00, $38, $00, $4E, $00, $70, $01, $00, $00, $00, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $00, $04, $00, $02, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$9C, $01, $00, $00, $02, $00, $10, $00, $01, $00, $42, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $AC, $01, $00, $00, $02, $00, $0E, $00, $01, $00, $3A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$BB, $01, $00, $00, $02, $00, $11, $00, $01, $00, $46, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $CC, $01, $00, $00, $02, $00, $12, $00, $01, $00, $4A, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$D9, $01, $00, $00, $02, $00, $0F, $00, $01, $00, $3E, $00, $F0, $00, $00, $00, $00, $00, $00, $00, $EA, $01, $00, $00, $02, $00, $04, $00, $04, $00, $12, $00, $8C, $01, $00, $00, $00, $00, $00, $00,
$F4, $01, $00, $00, $02, $00, $08, $00, $03, $00, $22, $00, $8C, $01, $00, $00, $00, $00, $00, $00, $00, $02, $00, $00, $02, $00, $0C, $00, $01, $00, $32, $00, $F0, $00, $00, $00, $00, $00, $00, $00,
$4C, $69, $67, $68, $74, $73, $00, $4F, $70, $74, $73, $00, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $41, $74, $74, $6E, $00, $50, $6F, $73, $00, $44, $69, $72,
$00, $44, $69, $66, $66, $75, $73, $65, $43, $6F, $6C, $6F, $72, $00, $53, $70, $65, $63, $75, $6C, $61, $72, $43, $6F, $6C, $6F, $72, $00, $41, $6D, $62, $69, $65, $6E, $74, $43, $6F, $6C, $6F, $72,
$00, $AB, $AB, $AB, $EB, $00, $00, $00, $F0, $00, $00, $00, $00, $01, $00, $00, $F0, $00, $00, $00, $05, $01, $00, $00, $F0, $00, $00, $00, $09, $01, $00, $00, $F0, $00, $00, $00, $0D, $01, $00, $00,
$F0, $00, $00, $00, $1A, $01, $00, $00, $F0, $00, $00, $00, $28, $01, $00, $00, $F0, $00, $00, $00, $05, $00, $00, $00, $01, $00, $1C, $00, $08, $00, $07, $00, $38, $01, $00, $00, $4D, $56, $50, $4D,
$61, $74, $72, $69, $78, $00, $AB, $AB, $03, $00, $03, $00, $04, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $41, $6D, $62, $69, $65, $6E, $74, $00,
$4D, $61, $74, $65, $72, $69, $61, $6C, $44, $69, $66, $75, $73, $65, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $45, $6D, $69, $73, $73, $69, $6F, $6E, $00, $4D, $61, $74, $65, $72, $69, $61, $6C,
$4F, $70, $74, $73, $00, $4D, $61, $74, $65, $72, $69, $61, $6C, $53, $70, $65, $63, $75, $6C, $61, $72, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65, $77, $00, $4D, $6F, $64, $65, $6C, $56, $69, $65,
$77, $49, $54, $00, $6F, $70, $74, $69, $6F, $6E, $73, $00, $76, $73, $5F, $33, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53,
$68, $61, $64, $65, $72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $0B, $00, $0F, $A0, $00, $00, $00, $C0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $00,
$51, $00, $00, $05, $0D, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $E0, $40, $30, $00, $00, $05, $00, $00, $0F, $F0, $08, $00, $00, $00, $00, $00, $00, $00,
$00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $03, $00, $00, $80, $01, $00, $0F, $90, $1F, $00, $00, $02, $0A, $00, $00, $80,
$02, $00, $0F, $90, $1F, $00, $00, $02, $05, $00, $00, $80, $03, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $0F, $E0, $1F, $00, $00, $02, $0A, $00, $00, $80, $01, $00, $0F, $E0,
$1F, $00, $00, $02, $05, $00, $00, $80, $02, $00, $03, $E0, $01, $00, $00, $02, $02, $00, $03, $E0, $03, $00, $E4, $90, $23, $00, $00, $02, $00, $00, $01, $80, $0C, $00, $00, $A0, $29, $00, $03, $02,
$00, $00, $00, $81, $00, $00, $00, $80, $01, $00, $00, $02, $00, $00, $01, $80, $0D, $00, $00, $A0, $02, $00, $00, $03, $00, $00, $01, $80, $00, $00, $00, $80, $0C, $00, $55, $A0, $0D, $00, $00, $03,
$00, $00, $01, $80, $00, $00, $00, $8C, $00, $00, $00, $8B, $04, $00, $00, $04, $01, $00, $0F, $80, $02, $00, $E4, $90, $0E, $00, $E4, $A0, $0E, $00, $E4, $A1, $04, $00, $00, $04, $01, $00, $0F, $E0,
$00, $00, $00, $80, $01, $00, $E4, $80, $0E, $00, $E4, $A0, $2A, $00, $00, $00, $05, $00, $00, $03, $00, $00, $07, $80, $05, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $07, $80,
$04, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04, $00, $00, $07, $80, $06, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $07, $80,
$00, $00, $E4, $80, $07, $00, $E4, $A0, $08, $00, $00, $03, $00, $00, $08, $80, $00, $00, $E4, $80, $00, $00, $E4, $80, $07, $00, $00, $02, $00, $00, $08, $80, $00, $00, $FF, $80, $05, $00, $00, $03,
$01, $00, $07, $80, $09, $00, $E4, $A0, $01, $00, $55, $90, $04, $00, $00, $04, $01, $00, $07, $80, $08, $00, $E4, $A0, $01, $00, $00, $90, $01, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $07, $80,
$0A, $00, $E4, $A0, $01, $00, $AA, $90, $01, $00, $E4, $80, $24, $00, $00, $02, $02, $00, $07, $80, $01, $00, $E4, $80, $05, $00, $00, $03, $01, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $80,
$01, $00, $00, $02, $03, $00, $0F, $80, $0D, $00, $AA, $A0, $01, $00, $00, $02, $04, $00, $0F, $80, $0D, $00, $AA, $A0, $01, $00, $00, $02, $05, $00, $0F, $80, $0D, $00, $AA, $A0, $01, $00, $00, $02,
$01, $00, $08, $80, $0D, $00, $AA, $A0, $26, $00, $00, $01, $00, $00, $E4, $F0, $05, $00, $00, $03, $02, $00, $08, $80, $01, $00, $FF, $80, $0D, $00, $FF, $A0, $2E, $00, $00, $02, $00, $00, $01, $B0,
$02, $00, $FF, $80, $01, $00, $00, $02, $06, $00, $04, $80, $0D, $00, $AA, $A0, $29, $00, $04, $03, $06, $00, $AA, $80, $13, $20, $00, $A0, $00, $00, $00, $B0, $01, $00, $00, $03, $06, $00, $02, $80,
$13, $20, $55, $A0, $00, $00, $00, $B0, $02, $00, $00, $03, $06, $00, $03, $80, $06, $00, $55, $80, $0B, $00, $E4, $A0, $29, $00, $03, $02, $06, $00, $00, $8C, $06, $00, $00, $8B, $02, $00, $00, $04,
$06, $00, $0D, $80, $00, $00, $94, $80, $15, $20, $94, $A1, $00, $00, $00, $B0, $08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $F8, $80, $06, $00, $F8, $80, $07, $00, $00, $02, $02, $00, $08, $80,
$02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $F8, $80, $02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80, $07, $00, $E4, $80, $08, $00, $00, $03,
$07, $00, $01, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $07, $00, $01, $80, $07, $00, $00, $80, $0D, $00, $AA, $A0, $20, $00, $00, $03, $08, $00, $01, $80, $07, $00, $00, $80,
$12, $00, $00, $A0, $06, $00, $00, $02, $07, $00, $01, $80, $02, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $02, $80, $07, $00, $00, $80, $07, $00, $00, $80, $04, $00, $00, $06, $07, $00, $01, $80,
$14, $20, $55, $A0, $00, $00, $00, $B0, $07, $00, $00, $80, $14, $20, $00, $A0, $00, $00, $00, $B0, $04, $00, $00, $05, $07, $00, $01, $80, $07, $00, $55, $80, $14, $20, $AA, $A0, $00, $00, $00, $B0,
$07, $00, $00, $80, $06, $00, $00, $02, $07, $00, $01, $80, $07, $00, $00, $80, $05, $00, $00, $03, $06, $00, $0D, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80,
$02, $00, $E4, $80, $06, $00, $F8, $81, $08, $00, $00, $04, $06, $00, $01, $80, $06, $00, $F8, $80, $16, $20, $E4, $A0, $00, $00, $00, $B0, $20, $00, $00, $04, $07, $00, $02, $80, $06, $00, $00, $80,
$13, $20, $FF, $A0, $00, $00, $00, $B0, $0C, $00, $00, $04, $06, $00, $01, $80, $13, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $07, $00, $55, $80,
$06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $01, $80, $07, $00, $00, $80, $06, $00, $00, $80, $05, $00, $00, $03, $06, $00, $04, $80, $08, $00, $00, $80, $06, $00, $00, $80, $0B, $00, $00, $03,
$02, $00, $08, $80, $02, $00, $FF, $80, $0D, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $08, $80, $0D, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $06, $00, $AA, $80,
$18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $FF, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $02, $00, $FF, $80,
$17, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $00, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $29, $00, $03, $02, $06, $00, $55, $8C,
$06, $00, $55, $8B, $02, $00, $00, $04, $06, $00, $07, $80, $00, $00, $E4, $80, $15, $20, $E4, $A1, $00, $00, $00, $B0, $08, $00, $00, $03, $02, $00, $08, $80, $06, $00, $E4, $80, $06, $00, $E4, $80,
$07, $00, $00, $02, $02, $00, $08, $80, $02, $00, $FF, $80, $04, $00, $00, $04, $07, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $81, $01, $00, $E4, $81, $24, $00, $00, $02, $08, $00, $07, $80,
$07, $00, $E4, $80, $08, $00, $00, $03, $06, $00, $08, $80, $02, $00, $E4, $80, $08, $00, $E4, $80, $0B, $00, $00, $03, $06, $00, $08, $80, $06, $00, $FF, $80, $0D, $00, $AA, $A0, $20, $00, $00, $03,
$07, $00, $01, $80, $06, $00, $FF, $80, $12, $00, $00, $A0, $06, $00, $00, $02, $06, $00, $08, $80, $02, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $02, $80, $06, $00, $FF, $80, $06, $00, $FF, $80,
$04, $00, $00, $06, $06, $00, $08, $80, $14, $20, $55, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $14, $20, $00, $A0, $00, $00, $00, $B0, $04, $00, $00, $05, $06, $00, $08, $80, $07, $00, $55, $80,
$14, $20, $AA, $A0, $00, $00, $00, $B0, $06, $00, $FF, $80, $06, $00, $00, $02, $06, $00, $08, $80, $06, $00, $FF, $80, $05, $00, $00, $03, $07, $00, $01, $80, $07, $00, $00, $80, $06, $00, $FF, $80,
$05, $00, $00, $03, $06, $00, $07, $80, $06, $00, $E4, $80, $02, $00, $FF, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $80, $06, $00, $E4, $81, $0B, $00, $00, $03, $02, $00, $08, $80,
$02, $00, $FF, $80, $0D, $00, $AA, $A0, $0C, $00, $00, $03, $06, $00, $01, $80, $0D, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $07, $00, $00, $80, $18, $20, $E4, $A0,
$00, $00, $00, $B0, $04, $00, $00, $04, $04, $00, $0F, $80, $06, $00, $00, $80, $07, $00, $E4, $80, $04, $00, $E4, $80, $05, $00, $00, $04, $07, $00, $0F, $80, $02, $00, $FF, $80, $17, $20, $E4, $A0,
$00, $00, $00, $B0, $04, $00, $00, $04, $03, $00, $0F, $80, $07, $00, $E4, $80, $06, $00, $FF, $80, $03, $00, $E4, $80, $2B, $00, $00, $00, $23, $00, $00, $03, $02, $00, $08, $80, $13, $20, $55, $A0,
$00, $00, $00, $B0, $29, $00, $03, $02, $02, $00, $FF, $81, $02, $00, $FF, $80, $04, $00, $00, $05, $06, $00, $07, $80, $00, $00, $E4, $80, $00, $00, $FF, $81, $16, $20, $E4, $A0, $00, $00, $00, $B0,
$24, $00, $00, $02, $07, $00, $07, $80, $06, $00, $E4, $80, $08, $00, $00, $03, $02, $00, $08, $80, $02, $00, $E4, $81, $07, $00, $E4, $80, $0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80,
$0D, $00, $AA, $A0, $20, $00, $00, $03, $06, $00, $01, $80, $02, $00, $FF, $80, $12, $00, $00, $A0, $08, $00, $00, $04, $02, $00, $08, $80, $02, $00, $E4, $81, $16, $20, $E4, $A0, $00, $00, $00, $B0,
$0B, $00, $00, $03, $02, $00, $08, $80, $02, $00, $FF, $80, $0D, $00, $AA, $A0, $04, $00, $00, $05, $03, $00, $0F, $80, $17, $20, $E4, $A0, $00, $00, $00, $B0, $02, $00, $FF, $80, $03, $00, $E4, $80,
$0C, $00, $00, $03, $02, $00, $08, $80, $0D, $00, $AA, $A0, $02, $00, $FF, $80, $05, $00, $00, $04, $06, $00, $0F, $80, $06, $00, $00, $80, $18, $20, $E4, $A0, $00, $00, $00, $B0, $04, $00, $00, $04,
$04, $00, $0F, $80, $02, $00, $FF, $80, $06, $00, $E4, $80, $04, $00, $E4, $80, $2B, $00, $00, $00, $02, $00, $00, $04, $05, $00, $0F, $80, $05, $00, $E4, $80, $19, $20, $E4, $A0, $00, $00, $00, $B0,
$2B, $00, $00, $00, $02, $00, $00, $03, $01, $00, $08, $80, $01, $00, $FF, $80, $0D, $00, $00, $A1, $27, $00, $00, $00, $01, $00, $00, $02, $00, $00, $05, $80, $0D, $00, $E4, $A0, $04, $00, $00, $04,
$00, $00, $0F, $80, $11, $00, $24, $A0, $00, $00, $80, $8B, $00, $00, $2A, $8B, $04, $00, $00, $04, $00, $00, $0F, $80, $05, $00, $E4, $80, $10, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04,
$00, $00, $0F, $80, $03, $00, $E4, $80, $0E, $00, $E4, $A0, $00, $00, $E4, $80, $04, $00, $00, $04, $01, $00, $0F, $E0, $04, $00, $E4, $80, $0F, $00, $E4, $A0, $00, $00, $E4, $80, $2B, $00, $00, $00,
$05, $00, $00, $03, $00, $00, $0F, $80, $01, $00, $E4, $A0, $00, $00, $55, $90, $04, $00, $00, $04, $00, $00, $0F, $80, $00, $00, $E4, $A0, $00, $00, $00, $90, $00, $00, $E4, $80, $04, $00, $00, $04,
$00, $00, $0F, $80, $02, $00, $E4, $A0, $00, $00, $AA, $90, $00, $00, $E4, $80, $02, $00, $00, $03, $00, $00, $0F, $E0, $00, $00, $E4, $80, $03, $00, $E4, $A0, $FF, $FF, $00, $00
);
ARBVP1_NoLight: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[20] = { program.local[0..18],'#13+
' { 0, 1 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'MOV R0.x, c[19].y;'#13+
'ADD R0.x, -R0, c[12].y;'#13+
'ABS R0.x, R0;'#13+
'SGE R1.x, c[19], R0;'#13+
'ABS R1.y, R1.x;'#13+
'ABS R1.x, c[12];'#13+
'MUL R0, vertex.color, c[14];'#13+
'SGE R2.x, c[19], R1;'#13+
'SGE R1.y, c[19].x, R1;'#13+
'MUL R2.y, R2.x, R1;'#13+
'ADD R1, -R0, c[14];'#13+
'MAD R1, R1, R2.y, R0;'#13+
'ABS R0.w, R2.x;'#13+
'SGE R2.x, c[19], R0.w;'#13+
'MOV R0.xyz, c[17];'#13+
'MOV R0.w, c[19].y;'#13+
'ADD R0, R0, -R1;'#13+
'MAD result.color, R0, R2.x, R1;'#13+
'MOV R0.w, c[19].y;'#13+
'MOV R0.xyz, vertex.position;'#13+
'DP4 result.position.w, R0, c[3];'#13+
'DP4 result.position.z, R0, c[2];'#13+
'DP4 result.position.y, R0, c[1];'#13+
'DP4 result.position.x, R0, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
ARBVP1_1Light: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[27] = { program.local[0..25],'#13+
' { 0, 1, 2 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'TEMP R3;'#13+
'TEMP R4;'#13+
'TEMP R5;'#13+
'TEMP R6;'#13+
'MOV R0.w, c[26].y;'#13+
'MOV R0.xyz, vertex.position;'#13+
'MOV R3.xyz, vertex.normal;'#13+
'MOV R3.w, c[26].x;'#13+
'DP4 R5.z, R3, c[10];'#13+
'DP4 R5.x, R3, c[8];'#13+
'DP4 R5.y, R3, c[9];'#13+
'DP3 R3.x, R5, R5;'#13+
'DP4 R1.z, R0, c[6];'#13+
'DP4 R1.x, R0, c[4];'#13+
'DP4 R1.y, R0, c[5];'#13+
'ADD R2.xyz, R1, -c[21];'#13+
'DP3 R1.w, R2, R2;'#13+
'RSQ R2.w, R1.w;'#13+
'DP3 R1.w, R1, R1;'#13+
'MUL R2.xyz, R2.w, R2;'#13+
'RSQ R1.w, R1.w;'#13+
'MAD R4.xyz, -R1.w, R1, -R2;'#13+
'DP3 R4.w, R4, R4;'#13+
'RSQ R3.w, R3.x;'#13+
'RSQ R3.y, R4.w;'#13+
'MUL R3.xyz, R3.y, R4;'#13+
'MUL R4.xyz, R3.w, R5;'#13+
'DP3 R3.x, R4, R3;'#13+
'DP3 R3.y, R4, -R2;'#13+
'MAX R6.z, R3.y, c[26].x;'#13+
'DP3 R3.y, R2, c[22];'#13+
'RCP R2.x, R2.w;'#13+
'MAX R3.x, R3, c[26];'#13+
'MOV R5.xy, c[26].yzzw;'#13+
'POW R3.x, R3.x, c[18].x;'#13+
'SLT R2.w, c[19].z, R3.y;'#13+
'MAD R2.z, R2.x, c[20].y, c[20].x;'#13+
'MUL R2.y, R2.x, c[20].z;'#13+
'MAD R2.x, R2.y, R2, R2.z;'#13+
'RCP R5.w, R2.x;'#13+
'ABS R2.y, R2.w;'#13+
'POW R2.z, R3.y, c[19].w;'#13+
'SGE R3.y, c[26].x, R2;'#13+
'ABS R2.y, c[12].x;'#13+
'SGE R4.w, c[26].x, R2.y;'#13+
'ABS R2.y, R4.w;'#13+
'ADD R2.w, -R5.y, c[19].y;'#13+
'ABS R2.w, R2;'#13+
'SGE R6.x, c[26], R2.y;'#13+
'SGE R2.w, c[26].x, R2;'#13+
'MUL R5.y, R6.x, R2.w;'#13+
'MUL R2.y, R5, R3;'#13+
'SLT R3.w, c[26].x, R6.z;'#13+
'MAD R2.y, -R2.z, R2, R2.z;'#13+
'MUL R5.z, R5.w, R2.y;'#13+
'MUL R2.x, R3, R5.z;'#13+
'MUL R3.y, R3.w, R5;'#13+
'MUL R2, R2.x, c[24];'#13+
'MUL R2, R2, R3.y;'#13+
'MUL R6.y, R3.x, R5.w;'#13+
'MAD R3.xyz, -R1.w, R1, c[22];'#13+
'MUL R1, R6.y, c[24];'#13+
'DP3 R6.w, R3, R3;'#13+
'ADD R6.y, -R5.x, c[19];'#13+
'RSQ R6.w, R6.w;'#13+
'MUL R3.xyz, R6.w, R3;'#13+
'DP3 R3.x, -R4, R3;'#13+
'DP3 R4.y, -R4, c[22];'#13+
'MAX R4.y, R4, c[26].x;'#13+
'ABS R6.y, R6;'#13+
'SGE R6.y, c[26].x, R6;'#13+
'ABS R4.x, c[19].y;'#13+
'SGE R4.x, c[26], R4;'#13+
'MUL R4.x, R6, R4;'#13+
'SLT R4.z, c[26].x, R4.y;'#13+
'MUL R4.z, R4.x, R4;'#13+
'MUL R6.y, R6.x, R6;'#13+
'MAX R6.w, R3.x, c[26].x;'#13+
'MUL R3.x, R6.y, R3.w;'#13+
'MAD R3, R1, R3.x, R2;'#13+
'POW R1.x, R6.w, c[18].x;'#13+
'MUL R1, R1.x, c[24];'#13+
'MAD R1, R1, R4.z, R3;'#13+
'MUL R2, R6.z, c[23];'#13+
'MUL R3, R5.w, R2;'#13+
'MUL R2, R5.z, R2;'#13+
'MUL R2, R5.y, R2;'#13+
'MAD R3, R6.y, R3, R2;'#13+
'ADD R4.z, -R5.x, c[12].y;'#13+
'MUL R2, R4.y, c[23];'#13+
'MAD R2, R4.x, R2, R3;'#13+
'ABS R4.z, R4;'#13+
'SGE R4.z, c[26].x, R4;'#13+
'ABS R4.y, R4.z;'#13+
'SGE R4.x, c[26], R4.y;'#13+
'MUL R3, vertex.color, c[14];'#13+
'MUL R5.x, R4.w, R4;'#13+
'ADD R4, -R3, c[14];'#13+
'MAD R4, R4, R5.x, R3;'#13+
'MOV R3.xyz, c[17];'#13+
'MOV R3.w, c[26].y;'#13+
'ADD R5, R3, -R4;'#13+
'MOV R3, c[16];'#13+
'MAD R4, R6.x, R5, R4;'#13+
'MUL R3, R3, c[25];'#13+
'MAD R3, R6.x, R3, R4;'#13+
'MUL R2, R2, c[14];'#13+
'MAD R2, R6.x, R2, R3;'#13+
'MUL R1, R1, c[15];'#13+
'MAD R1, R1, R6.x, R2;'#13+
'MIN R2, R1, c[26].y;'#13+
'MAX R2, R2, c[26].x;'#13+
'ADD R2, R2, -R1;'#13+
'MAD result.color, R2, R6.x, R1;'#13+
'DP4 result.position.w, R0, c[3];'#13+
'DP4 result.position.z, R0, c[2];'#13+
'DP4 result.position.y, R0, c[1];'#13+
'DP4 result.position.x, R0, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
ARBVP1_2Light: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[34] = { program.local[0..32],'#13+
' { 0, 1, 2 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'TEMP R3;'#13+
'TEMP R4;'#13+
'TEMP R5;'#13+
'TEMP R6;'#13+
'TEMP R7;'#13+
'TEMP R8;'#13+
'TEMP R9;'#13+
'MOV R1.w, c[33].y;'#13+
'MOV R1.xyz, vertex.position;'#13+
'DP4 R4.z, R1, c[6];'#13+
'DP4 R4.x, R1, c[4];'#13+
'DP4 R4.y, R1, c[5];'#13+
'ADD R2.xyz, R4, -c[21];'#13+
'DP3 R0.x, R2, R2;'#13+
'RSQ R3.w, R0.x;'#13+
'MUL R3.xyz, R3.w, R2;'#13+
'DP3 R0.x, R4, R4;'#13+
'RSQ R8.z, R0.x;'#13+
'MAD R0.xyz, -R8.z, R4, -R3;'#13+
'DP3 R0.w, R0, R0;'#13+
'RSQ R0.w, R0.w;'#13+
'MUL R2.xyz, R0.w, R0;'#13+
'MOV R7.xy, c[33].yzzw;'#13+
'MOV R0.w, c[33].x;'#13+
'MOV R0.xyz, vertex.normal;'#13+
'DP4 R5.z, R0, c[10];'#13+
'DP4 R5.x, R0, c[8];'#13+
'DP4 R5.y, R0, c[9];'#13+
'DP3 R0.w, R5, R5;'#13+
'MAD R0.xyz, -R8.z, R4, c[22];'#13+
'RSQ R0.w, R0.w;'#13+
'MUL R6.xyz, R0.w, R5;'#13+
'DP3 R0.w, R6, R2;'#13+
'DP3 R2.z, -R6, c[22];'#13+
'DP3 R2.w, R0, R0;'#13+
'RSQ R2.x, R2.w;'#13+
'MAX R4.w, R2.z, c[33].x;'#13+
'MUL R0.xyz, R2.x, R0;'#13+
'DP3 R2.x, -R6, R0;'#13+
'MAX R2.x, R2, c[33];'#13+
'POW R2.y, R2.x, c[18].x;'#13+
'ABS R2.x, c[12];'#13+
'SGE R5.w, c[33].x, R2.x;'#13+
'ABS R2.x, R5.w;'#13+
'MAX R0.w, R0, c[33].x;'#13+
'POW R0.w, R0.w, c[18].x;'#13+
'ABS R2.z, c[19].y;'#13+
'SGE R6.w, c[33].x, R2.x;'#13+
'SGE R2.z, c[33].x, R2;'#13+
'SLT R2.w, c[33].x, R4;'#13+
'MUL R7.w, R6, R2.z;'#13+
'MUL R5.x, R7.w, R2.w;'#13+
'MUL R2, R2.y, c[24];'#13+
'MUL R2, R2, R5.x;'#13+
'DP3 R5.x, R6, -R3;'#13+
'MAX R8.w, R5.x, c[33].x;'#13+
'ADD R5.y, -R7.x, c[19];'#13+
'ABS R5.x, R5.y;'#13+
'SGE R5.y, c[33].x, R5.x;'#13+
'ADD R5.x, -R7.y, c[19].y;'#13+
'ABS R5.x, R5;'#13+
'SGE R5.x, c[33], R5;'#13+
'SLT R8.y, c[33].x, R8.w;'#13+
'MUL R8.x, R6.w, R5;'#13+
'MUL R7.z, R6.w, R5.y;'#13+
'MUL R5.y, R8, R7.z;'#13+
'MUL R0, R0.w, c[24];'#13+
'MAD R2, R0, R5.y, R2;'#13+
'MUL R9.x, R8, R8.y;'#13+
'MAD R0, R9.x, R0, R2;'#13+
'MAD R2.xyz, -R8.z, R4, c[29];'#13+
'ADD R5.xyz, R4, -c[28];'#13+
'DP3 R8.y, R5, R5;'#13+
'RSQ R8.y, R8.y;'#13+
'MUL R5.xyz, R8.y, R5;'#13+
'MAD R4.xyz, -R8.z, R4, -R5;'#13+
'DP3 R2.w, R2, R2;'#13+
'RSQ R8.z, R2.w;'#13+
'DP3 R2.w, R4, R4;'#13+
'MUL R2.xyz, R8.z, R2;'#13+
'DP3 R8.z, -R6, R2;'#13+
'RSQ R2.w, R2.w;'#13+
'MUL R2.xyz, R2.w, R4;'#13+
'DP3 R2.x, R6, R2;'#13+
'DP3 R4.z, -R6, c[29];'#13+
'MAX R2.w, R8.z, c[33].x;'#13+
'MAX R9.x, R4.z, c[33];'#13+
'ABS R4.y, c[26];'#13+
'SGE R4.y, c[33].x, R4;'#13+
'MAX R4.x, R2, c[33];'#13+
'POW R2.y, R2.w, c[18].x;'#13+
'MUL R2, R2.y, c[31];'#13+
'MUL R8.z, R6.w, R4.y;'#13+
'SLT R4.z, c[33].x, R9.x;'#13+
'MUL R4.y, R8.z, R4.z;'#13+
'MAD R0, R2, R4.y, R0;'#13+
'POW R2.x, R4.x, c[18].x;'#13+
'DP3 R4.x, R6, -R5;'#13+
'DP3 R5.y, R5, c[29];'#13+
'MAX R6.z, R4.x, c[33].x;'#13+
'ADD R4.y, -R7.x, c[26];'#13+
'ABS R4.z, R4.y;'#13+
'ADD R4.y, -R7, c[26];'#13+
'SGE R4.z, c[33].x, R4;'#13+
'SLT R5.z, c[26], R5.y;'#13+
'ABS R4.y, R4;'#13+
'SGE R4.y, c[33].x, R4;'#13+
'MUL R6.x, R6.w, R4.y;'#13+
'RCP R3.w, R3.w;'#13+
'MUL R6.y, R6.w, R4.z;'#13+
'SLT R4.x, c[33], R6.z;'#13+
'MUL R4.z, R4.x, R6.y;'#13+
'MUL R2, R2.x, c[31];'#13+
'MAD R0, R2, R4.z, R0;'#13+
'MUL R4.x, R6, R4;'#13+
'MAD R2, R4.x, R2, R0;'#13+
'MUL R0, R8.w, c[23];'#13+
'MAD R4.y, R3.w, c[20], c[20].x;'#13+
'MUL R4.x, R3.w, c[20].z;'#13+
'MAD R3.w, R4.x, R3, R4.y;'#13+
'DP3 R8.w, R3, c[22];'#13+
'SLT R4.x, c[19].z, R8.w;'#13+
'ABS R9.y, R4.x;'#13+
'RCP R7.y, R3.w;'#13+
'MUL R4, R4.w, c[23];'#13+
'SGE R9.y, c[33].x, R9;'#13+
'MUL R4, R7.w, R4;'#13+
'MUL R3, R0, R7.y;'#13+
'MAD R3, R7.z, R3, R4;'#13+
'RCP R4.x, R8.y;'#13+
'MAD R4.z, R4.x, c[27].y, c[27].x;'#13+
'MUL R4.y, R4.x, c[27].z;'#13+
'MAD R4.x, R4.y, R4, R4.z;'#13+
'RCP R5.x, R4.x;'#13+
'ABS R5.z, R5;'#13+
'POW R8.w, R8.w, c[19].w;'#13+
'MUL R9.y, R8.x, R9;'#13+
'MAD R8.w, -R8, R9.y, R8;'#13+
'MUL R7.y, R7, R8.w;'#13+
'MUL R0, R0, R7.y;'#13+
'MAD R3, R8.x, R0, R3;'#13+
'MUL R0, R9.x, c[30];'#13+
'MAD R0, R8.z, R0, R3;'#13+
'MUL R3, R6.z, c[30];'#13+
'MUL R4, R3, R5.x;'#13+
'MAD R0, R6.y, R4, R0;'#13+
'SGE R4.y, c[33].x, R5.z;'#13+
'POW R4.x, R5.y, c[26].w;'#13+
'MUL R4.y, R6.x, R4;'#13+
'MAD R4.x, -R4, R4.y, R4;'#13+
'MUL R4.x, R5, R4;'#13+
'MUL R3, R3, R4.x;'#13+
'ADD R4.y, -R7.x, c[12];'#13+
'ABS R4.y, R4;'#13+
'MAD R0, R6.x, R3, R0;'#13+
'SGE R4.x, c[33], R4.y;'#13+
'ABS R3.x, R4;'#13+
'MUL R4, R0, c[14];'#13+
'SGE R3.x, c[33], R3;'#13+
'MUL R0, vertex.color, c[14];'#13+
'MUL R5.x, R5.w, R3;'#13+
'ADD R3, -R0, c[14];'#13+
'MAD R5, R3, R5.x, R0;'#13+
'MOV R3, c[32];'#13+
'ADD R3, R3, c[25];'#13+
'MAD R3, R3, c[16], R4;'#13+
'MOV R0.xyz, c[17];'#13+
'MOV R0.w, c[33].y;'#13+
'ADD R0, R0, -R5;'#13+
'MAD R0, R6.w, R0, R5;'#13+
'MAD R2, R2, c[15], R3;'#13+
'MAD result.color, R2, R6.w, R0;'#13+
'DP4 result.position.w, R1, c[3];'#13+
'DP4 result.position.z, R1, c[2];'#13+
'DP4 result.position.y, R1, c[1];'#13+
'DP4 result.position.x, R1, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
ARBVP1_3Light: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[41] = { program.local[0..39],'#13+
' { 0, 1, 2 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'TEMP R3;'#13+
'TEMP R4;'#13+
'TEMP R5;'#13+
'TEMP R6;'#13+
'TEMP R7;'#13+
'TEMP R8;'#13+
'TEMP R9;'#13+
'TEMP R10;'#13+
'TEMP R11;'#13+
'MOV R8.xy, c[40].yzzw;'#13+
'MOV R0.w, c[40].y;'#13+
'MOV R0.xyz, vertex.position;'#13+
'DP4 R4.z, R0, c[6];'#13+
'DP4 R4.x, R0, c[4];'#13+
'DP4 R4.y, R0, c[5];'#13+
'ADD R2.xyz, R4, -c[21];'#13+
'DP3 R1.x, R2, R2;'#13+
'RSQ R3.w, R1.x;'#13+
'MUL R3.xyz, R3.w, R2;'#13+
'DP3 R1.x, R4, R4;'#13+
'RSQ R11.x, R1.x;'#13+
'MAD R1.xyz, -R11.x, R4, -R3;'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R2.xyz, R1.w, R1;'#13+
'MAD R5.xyz, -R11.x, R4, c[22];'#13+
'MOV R1.xyz, vertex.normal;'#13+
'MOV R1.w, c[40].x;'#13+
'DP4 R6.z, R1, c[10];'#13+
'DP4 R6.x, R1, c[8];'#13+
'DP4 R6.y, R1, c[9];'#13+
'DP3 R1.x, R6, R6;'#13+
'DP3 R1.y, R5, R5;'#13+
'RSQ R1.x, R1.x;'#13+
'MUL R7.xyz, R1.x, R6;'#13+
'DP3 R1.w, R7, R2;'#13+
'DP3 R4.w, -R7, c[22];'#13+
'RSQ R1.y, R1.y;'#13+
'MUL R1.xyz, R1.y, R5;'#13+
'DP3 R1.y, -R7, R1;'#13+
'MAX R1.w, R1, c[40].x;'#13+
'MAX R2.x, R1.y, c[40];'#13+
'MAX R4.w, R4, c[40].x;'#13+
'ABS R5.x, c[12];'#13+
'SGE R5.w, c[40].x, R5.x;'#13+
'ABS R5.x, R5.w;'#13+
'POW R1.x, R1.w, c[18].x;'#13+
'POW R2.x, R2.x, c[18].x;'#13+
'ABS R5.y, c[19];'#13+
'SGE R6.w, c[40].x, R5.x;'#13+
'SGE R5.y, c[40].x, R5;'#13+
'MUL R10.z, R6.w, R5.y;'#13+
'SLT R5.z, c[40].x, R4.w;'#13+
'ADD R5.y, -R8.x, c[19];'#13+
'MUL R1, R1.x, c[24];'#13+
'MUL R5.x, R10.z, R5.z;'#13+
'MUL R2, R2.x, c[24];'#13+
'MUL R2, R2, R5.x;'#13+
'DP3 R5.x, R7, -R3;'#13+
'MAX R10.w, R5.x, c[40].x;'#13+
'ABS R5.y, R5;'#13+
'SGE R5.x, c[40], R5.y;'#13+
'MUL R10.x, R6.w, R5;'#13+
'SLT R6.y, c[40].x, R10.w;'#13+
'MUL R5.y, R6, R10.x;'#13+
'ADD R5.x, -R8.y, c[19].y;'#13+
'ABS R5.x, R5;'#13+
'SGE R6.x, c[40], R5;'#13+
'MAD R2, R1, R5.y, R2;'#13+
'MUL R9.x, R6.w, R6;'#13+
'ADD R5.xyz, R4, -c[28];'#13+
'DP3 R6.x, R5, R5;'#13+
'MUL R6.y, R9.x, R6;'#13+
'MAD R2, R6.y, R1, R2;'#13+
'RSQ R7.w, R6.x;'#13+
'MUL R6.xyz, R7.w, R5;'#13+
'MAD R1.xyz, -R11.x, R4, -R6;'#13+
'MAD R5.xyz, -R11.x, R4, c[29];'#13+
'DP3 R8.z, R5, R5;'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R8.z, R8.z;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R1;'#13+
'MUL R5.xyz, R8.z, R5;'#13+
'DP3 R1.w, -R7, R5;'#13+
'DP3 R1.x, R7, R1;'#13+
'DP3 R5.z, -R7, c[29];'#13+
'MAX R8.w, R5.z, c[40].x;'#13+
'MAX R1.y, R1.w, c[40].x;'#13+
'MAX R1.x, R1, c[40];'#13+
'ABS R5.y, c[26];'#13+
'SGE R5.y, c[40].x, R5;'#13+
'POW R5.x, R1.x, c[18].x;'#13+
'POW R1.y, R1.y, c[18].x;'#13+
'MUL R8.z, R6.w, R5.y;'#13+
'SLT R5.z, c[40].x, R8.w;'#13+
'MUL R5.y, R8.z, R5.z;'#13+
'MUL R1, R1.y, c[31];'#13+
'MAD R2, R1, R5.y, R2;'#13+
'MUL R1, R5.x, c[31];'#13+
'DP3 R5.x, R7, -R6;'#13+
'MAX R9.y, R5.x, c[40].x;'#13+
'ADD R5.y, -R8.x, c[26];'#13+
'ABS R5.x, R5.y;'#13+
'SGE R5.y, c[40].x, R5.x;'#13+
'ADD R5.x, -R8.y, c[26].y;'#13+
'ABS R5.x, R5;'#13+
'SGE R5.x, c[40], R5;'#13+
'MUL R9.w, R6, R5.x;'#13+
'SLT R10.y, c[40].x, R9;'#13+
'MUL R9.z, R6.w, R5.y;'#13+
'MUL R5.y, R10, R9.z;'#13+
'MAD R2, R1, R5.y, R2;'#13+
'MUL R11.y, R9.w, R10;'#13+
'MAD R1, R11.y, R1, R2;'#13+
'MAD R2.xyz, -R11.x, R4, c[36];'#13+
'ADD R5.xyz, R4, -c[35];'#13+
'DP3 R10.y, R5, R5;'#13+
'RSQ R10.y, R10.y;'#13+
'MUL R5.xyz, R10.y, R5;'#13+
'MAD R4.xyz, -R11.x, R4, -R5;'#13+
'DP3 R2.w, R2, R2;'#13+
'RSQ R11.x, R2.w;'#13+
'DP3 R2.w, R4, R4;'#13+
'MUL R2.xyz, R11.x, R2;'#13+
'DP3 R11.x, -R7, R2;'#13+
'RSQ R2.w, R2.w;'#13+
'MUL R2.xyz, R2.w, R4;'#13+
'DP3 R2.x, R7, R2;'#13+
'DP3 R4.z, -R7, c[36];'#13+
'MAX R2.w, R11.x, c[40].x;'#13+
'MAX R11.y, R4.z, c[40].x;'#13+
'ABS R4.y, c[33];'#13+
'SGE R4.y, c[40].x, R4;'#13+
'MAX R4.x, R2, c[40];'#13+
'POW R2.y, R2.w, c[18].x;'#13+
'MUL R2, R2.y, c[38];'#13+
'MUL R11.x, R6.w, R4.y;'#13+
'SLT R4.z, c[40].x, R11.y;'#13+
'MUL R4.y, R11.x, R4.z;'#13+
'MAD R1, R2, R4.y, R1;'#13+
'POW R2.x, R4.x, c[18].x;'#13+
'DP3 R4.x, R7, -R5;'#13+
'MAX R7.x, R4, c[40];'#13+
'ADD R4.y, -R8.x, c[33];'#13+
'ABS R4.z, R4.y;'#13+
'ADD R4.y, -R8, c[33];'#13+
'SGE R4.z, c[40].x, R4;'#13+
'ABS R4.y, R4;'#13+
'SGE R4.y, c[40].x, R4;'#13+
'DP3 R5.y, R5, c[36];'#13+
'MUL R7.y, R6.w, R4;'#13+
'RCP R3.w, R3.w;'#13+
'MUL R2, R2.x, c[38];'#13+
'MUL R7.z, R6.w, R4;'#13+
'SLT R4.x, c[40], R7;'#13+
'MUL R4.z, R4.x, R7;'#13+
'MAD R1, R2, R4.z, R1;'#13+
'MUL R4.x, R7.y, R4;'#13+
'MAD R1, R4.x, R2, R1;'#13+
'MUL R2, R10.w, c[23];'#13+
'MAD R4.y, R3.w, c[20], c[20].x;'#13+
'MUL R4.x, R3.w, c[20].z;'#13+
'MAD R3.w, R4.x, R3, R4.y;'#13+
'DP3 R10.w, R3, c[22];'#13+
'SLT R4.x, c[19].z, R10.w;'#13+
'ABS R11.z, R4.x;'#13+
'RCP R8.y, R3.w;'#13+
'MUL R4, R4.w, c[23];'#13+
'SGE R11.z, c[40].x, R11;'#13+
'MUL R4, R10.z, R4;'#13+
'MUL R3, R2, R8.y;'#13+
'MAD R3, R10.x, R3, R4;'#13+
'RCP R4.x, R7.w;'#13+
'DP3 R4.w, R6, c[29];'#13+
'SLT R6.x, c[26].z, R4.w;'#13+
'MAD R4.z, R4.x, c[27].y, c[27].x;'#13+
'MUL R4.y, R4.x, c[27].z;'#13+
'MAD R4.x, R4.y, R4, R4.z;'#13+
'ABS R4.y, R6.x;'#13+
'RCP R6.x, R4.x;'#13+
'SGE R4.y, c[40].x, R4;'#13+
'POW R4.x, R4.w, c[26].w;'#13+
'MUL R4.y, R9.w, R4;'#13+
'MAD R6.y, -R4.x, R4, R4.x;'#13+
'POW R10.w, R10.w, c[19].w;'#13+
'MUL R11.z, R9.x, R11;'#13+
'MAD R10.w, -R10, R11.z, R10;'#13+
'MUL R8.y, R8, R10.w;'#13+
'MUL R2, R2, R8.y;'#13+
'MAD R2, R9.x, R2, R3;'#13+
'MUL R3, R8.w, c[30];'#13+
'MAD R2, R8.z, R3, R2;'#13+
'MUL R3, R9.y, c[30];'#13+
'MUL R4, R3, R6.x;'#13+
'MAD R2, R9.z, R4, R2;'#13+
'RCP R4.x, R10.y;'#13+
'MUL R6.x, R6, R6.y;'#13+
'MUL R3, R3, R6.x;'#13+
'MAD R2, R9.w, R3, R2;'#13+
'MUL R3, R11.y, c[37];'#13+
'MAD R2, R11.x, R3, R2;'#13+
'MAD R4.z, R4.x, c[34].y, c[34].x;'#13+
'MUL R4.y, R4.x, c[34].z;'#13+
'MAD R4.x, R4.y, R4, R4.z;'#13+
'SLT R4.y, c[33].z, R5;'#13+
'ABS R5.z, R4.y;'#13+
'SGE R5.z, c[40].x, R5;'#13+
'RCP R5.x, R4.x;'#13+
'MUL R3, R7.x, c[37];'#13+
'MUL R4, R3, R5.x;'#13+
'MAD R2, R7.z, R4, R2;'#13+
'MUL R5.z, R7.y, R5;'#13+
'POW R5.y, R5.y, c[33].w;'#13+
'MAD R5.y, -R5, R5.z, R5;'#13+
'MUL R4.x, R5, R5.y;'#13+
'MUL R3, R3, R4.x;'#13+
'MAD R2, R7.y, R3, R2;'#13+
'ADD R4.y, -R8.x, c[12];'#13+
'ABS R4.x, R4.y;'#13+
'SGE R3.x, c[40], R4;'#13+
'ABS R4.x, R3;'#13+
'SGE R5.x, c[40], R4;'#13+
'MOV R3, c[32];'#13+
'MUL R4, vertex.color, c[14];'#13+
'MUL R6.x, R5.w, R5;'#13+
'ADD R5, -R4, c[14];'#13+
'MAD R5, R5, R6.x, R4;'#13+
'ADD R4, R3, c[25];'#13+
'MUL R2, R2, c[14];'#13+
'ADD R4, R4, c[39];'#13+
'MAD R2, R4, c[16], R2;'#13+
'MOV R3.xyz, c[17];'#13+
'MOV R3.w, c[40].y;'#13+
'ADD R3, R3, -R5;'#13+
'MAD R3, R6.w, R3, R5;'#13+
'MAD R1, R1, c[15], R2;'#13+
'MAD result.color, R1, R6.w, R3;'#13+
'DP4 result.position.w, R0, c[3];'#13+
'DP4 result.position.z, R0, c[2];'#13+
'DP4 result.position.y, R0, c[1];'#13+
'DP4 result.position.x, R0, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
ARBVP1_4Light: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[48] = { program.local[0..46],'#13+
' { 1, 0, 2 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'TEMP R3;'#13+
'TEMP R4;'#13+
'TEMP R5;'#13+
'TEMP R6;'#13+
'TEMP R7;'#13+
'TEMP R8;'#13+
'TEMP R9;'#13+
'TEMP R10;'#13+
'TEMP R11;'#13+
'TEMP R12;'#13+
'MOV R7.xy, c[47].xzzw;'#13+
'MOV R1.w, c[47].x;'#13+
'MOV R1.xyz, vertex.position;'#13+
'DP4 R3.z, R1, c[6];'#13+
'DP4 R3.x, R1, c[4];'#13+
'DP4 R3.y, R1, c[5];'#13+
'ADD R2.xyz, R3, -c[21];'#13+
'DP3 R0.x, R2, R2;'#13+
'RSQ R2.w, R0.x;'#13+
'DP3 R0.x, R3, R3;'#13+
'RSQ R11.w, R0.x;'#13+
'MUL R2.xyz, R2.w, R2;'#13+
'MAD R4.xyz, -R11.w, R3, -R2;'#13+
'DP3 R3.w, R4, R4;'#13+
'MOV R0.xyz, vertex.normal;'#13+
'MOV R0.w, c[47].y;'#13+
'DP4 R5.z, R0, c[10];'#13+
'DP4 R5.x, R0, c[8];'#13+
'DP4 R5.y, R0, c[9];'#13+
'DP3 R0.x, R5, R5;'#13+
'RSQ R0.w, R0.x;'#13+
'MUL R5.xyz, R0.w, R5;'#13+
'DP3 R0.w, R5, -R2;'#13+
'RSQ R0.y, R3.w;'#13+
'MUL R0.xyz, R0.y, R4;'#13+
'DP3 R0.x, R5, R0;'#13+
'DP3 R2.x, R2, c[22];'#13+
'DP3 R12.y, -R5, c[36];'#13+
'MAX R3.w, R0, c[47].y;'#13+
'MAX R0.x, R0, c[47].y;'#13+
'POW R4.x, R0.x, c[18].x;'#13+
'RCP R0.x, R2.w;'#13+
'MAX R12.y, R12, c[47];'#13+
'SLT R6.x, c[47].y, R3.w;'#13+
'SLT R2.y, c[19].z, R2.x;'#13+
'MAD R0.z, R0.x, c[20].y, c[20].x;'#13+
'MUL R0.y, R0.x, c[20].z;'#13+
'MAD R0.y, R0, R0.x, R0.z;'#13+
'ABS R0.x, R2.y;'#13+
'POW R0.z, R2.x, c[19].w;'#13+
'SGE R2.y, c[47], R0.x;'#13+
'ABS R0.x, c[12];'#13+
'SGE R5.w, c[47].y, R0.x;'#13+
'ABS R0.x, R5.w;'#13+
'ADD R2.x, -R7.y, c[19].y;'#13+
'ABS R2.x, R2;'#13+
'SGE R6.w, c[47].y, R0.x;'#13+
'SGE R2.x, c[47].y, R2;'#13+
'MUL R11.z, R6.w, R2.x;'#13+
'MUL R0.x, R11.z, R2.y;'#13+
'MAD R0.x, -R0.z, R0, R0.z;'#13+
'RCP R11.x, R0.y;'#13+
'MUL R4.w, R11.x, R0.x;'#13+
'MUL R0.x, R4, R4.w;'#13+
'MUL R0, R0.x, c[24];'#13+
'MUL R2.x, R6, R11.z;'#13+
'MUL R2, R0, R2.x;'#13+
'ADD R4.y, -R7.x, c[19];'#13+
'ABS R0.y, R4;'#13+
'MUL R0.x, R4, R11;'#13+
'SGE R4.x, c[47].y, R0.y;'#13+
'MUL R10.w, R6, R4.x;'#13+
'MUL R0, R0.x, c[24];'#13+
'MUL R6.y, R10.w, R6.x;'#13+
'MAD R2, R0, R6.y, R2;'#13+
'MAD R0.xyz, -R11.w, R3, c[22];'#13+
'ADD R4.xyz, R3, -c[28];'#13+
'DP3 R6.x, R4, R4;'#13+
'RSQ R7.z, R6.x;'#13+
'MUL R4.xyz, R7.z, R4;'#13+
'DP3 R0.w, R0, R0;'#13+
'RSQ R7.w, R0.w;'#13+
'MAD R6.xyz, -R11.w, R3, -R4;'#13+
'DP3 R0.w, R6, R6;'#13+
'MUL R0.xyz, R7.w, R0;'#13+
'DP3 R7.w, -R5, R0;'#13+
'RSQ R0.w, R0.w;'#13+
'MUL R0.xyz, R0.w, R6;'#13+
'DP3 R0.x, R5, R0;'#13+
'DP3 R6.z, -R5, c[22];'#13+
'MAX R0.w, R7, c[47].y;'#13+
'MAX R9.y, R6.z, c[47];'#13+
'MAX R6.x, R0, c[47].y;'#13+
'POW R0.y, R0.w, c[18].x;'#13+
'ABS R6.y, c[19];'#13+
'SGE R6.y, c[47], R6;'#13+
'MUL R0, R0.y, c[24];'#13+
'MUL R9.x, R6.w, R6.y;'#13+
'SLT R6.z, c[47].y, R9.y;'#13+
'MUL R6.y, R9.x, R6.z;'#13+
'MAD R2, R0, R6.y, R2;'#13+
'DP3 R0.w, R5, -R4;'#13+
'RCP R0.x, R7.z;'#13+
'MAX R10.y, R0.w, c[47];'#13+
'DP3 R4.x, R4, c[29];'#13+
'POW R6.x, R6.x, c[18].x;'#13+
'MAD R0.z, R0.x, c[27].y, c[27].x;'#13+
'MUL R0.y, R0.x, c[27].z;'#13+
'MAD R0.x, R0.y, R0, R0.z;'#13+
'POW R0.y, R4.x, c[26].w;'#13+
'ADD R0.z, -R7.y, c[26].y;'#13+
'SLT R4.x, c[26].z, R4;'#13+
'ABS R0.z, R0;'#13+
'SGE R0.z, c[47].y, R0;'#13+
'ABS R4.x, R4;'#13+
'MUL R8.z, R6.w, R0;'#13+
'SGE R4.x, c[47].y, R4;'#13+
'MUL R0.z, R8, R4.x;'#13+
'SLT R6.y, c[47], R10;'#13+
'RCP R8.x, R0.x;'#13+
'MAD R0.y, -R0, R0.z, R0;'#13+
'MUL R8.w, R8.x, R0.y;'#13+
'MUL R0.x, R6, R8.w;'#13+
'MUL R0, R0.x, c[31];'#13+
'MUL R4.y, R6, R8.z;'#13+
'MAD R2, R0, R4.y, R2;'#13+
'ADD R4.x, -R7, c[26].y;'#13+
'ABS R0.y, R4.x;'#13+
'SGE R4.x, c[47].y, R0.y;'#13+
'MUL R8.y, R6.w, R4.x;'#13+
'MUL R0.x, R6, R8;'#13+
'ADD R4.xyz, R3, -c[35];'#13+
'DP3 R6.x, R4, R4;'#13+
'RSQ R9.z, R6.x;'#13+
'MUL R4.xyz, R9.z, R4;'#13+
'MUL R0, R0.x, c[31];'#13+
'MUL R6.y, R8, R6;'#13+
'MAD R2, R0, R6.y, R2;'#13+
'MAD R0.xyz, -R11.w, R3, c[29];'#13+
'DP3 R0.w, R0, R0;'#13+
'RSQ R7.z, R0.w;'#13+
'MAD R6.xyz, -R11.w, R3, -R4;'#13+
'DP3 R0.w, R6, R6;'#13+
'MUL R0.xyz, R7.z, R0;'#13+
'DP3 R7.z, -R5, R0;'#13+
'RSQ R0.w, R0.w;'#13+
'MUL R0.xyz, R0.w, R6;'#13+
'DP3 R0.x, R5, R0;'#13+
'DP3 R6.z, -R5, c[29];'#13+
'MAX R0.w, R7.z, c[47].y;'#13+
'MAX R7.w, R6.z, c[47].y;'#13+
'MAX R6.x, R0, c[47].y;'#13+
'POW R0.y, R0.w, c[18].x;'#13+
'ABS R6.y, c[26];'#13+
'SGE R6.y, c[47], R6;'#13+
'MUL R7.z, R6.w, R6.y;'#13+
'SLT R6.z, c[47].y, R7.w;'#13+
'POW R6.x, R6.x, c[18].x;'#13+
'MUL R6.y, R7.z, R6.z;'#13+
'MUL R0, R0.y, c[31];'#13+
'MAD R0, R0, R6.y, R2;'#13+
'RCP R2.x, R9.z;'#13+
'DP3 R2.w, R4, c[36];'#13+
'MAD R2.z, R2.x, c[34].y, c[34].x;'#13+
'MUL R2.y, R2.x, c[34].z;'#13+
'MAD R2.x, R2.y, R2, R2.z;'#13+
'RCP R9.z, R2.x;'#13+
'DP3 R2.x, R5, -R4;'#13+
'MAX R10.z, R2.x, c[47].y;'#13+
'POW R2.y, R2.w, c[33].w;'#13+
'ADD R2.z, -R7.y, c[33].y;'#13+
'SLT R2.w, c[33].z, R2;'#13+
'ABS R2.z, R2;'#13+
'SGE R2.z, c[47].y, R2;'#13+
'ABS R2.w, R2;'#13+
'ADD R4.y, -R7.x, c[33];'#13+
'MUL R9.w, R6, R2.z;'#13+
'SGE R2.w, c[47].y, R2;'#13+
'MUL R2.z, R9.w, R2.w;'#13+
'MAD R2.y, -R2, R2.z, R2;'#13+
'MUL R10.x, R9.z, R2.y;'#13+
'MUL R2.y, R6.x, R10.x;'#13+
'SLT R4.x, c[47].y, R10.z;'#13+
'MUL R4.z, R4.x, R9.w;'#13+
'MUL R2, R2.y, c[38];'#13+
'MAD R2, R2, R4.z, R0;'#13+
'ABS R4.y, R4;'#13+
'SGE R0.y, c[47], R4;'#13+
'MUL R11.y, R6.w, R0;'#13+
'MUL R0.x, R6, R9.z;'#13+
'MUL R0, R0.x, c[38];'#13+
'MUL R4.x, R11.y, R4;'#13+
'MAD R2, R0, R4.x, R2;'#13+
'MAD R0.xyz, -R11.w, R3, c[36];'#13+
'ADD R4.xyz, R3, -c[42];'#13+
'DP3 R0.w, R4, R4;'#13+
'RSQ R12.z, R0.w;'#13+
'DP3 R6.x, R0, R0;'#13+
'RSQ R0.w, R6.x;'#13+
'MUL R6.xyz, R0.w, R0;'#13+
'MUL R4.xyz, R12.z, R4;'#13+
'MAD R0.xyz, -R11.w, R3, -R4;'#13+
'DP3 R6.x, -R5, R6;'#13+
'DP3 R0.w, R0, R0;'#13+
'MAX R6.x, R6, c[47].y;'#13+
'POW R12.x, R6.x, c[18].x;'#13+
'RSQ R0.w, R0.w;'#13+
'MUL R6.xyz, R0.w, R0;'#13+
'MUL R0, R12.x, c[38];'#13+
'ABS R12.x, c[33].y;'#13+
'SGE R12.x, c[47].y, R12;'#13+
'MAD R3.xyz, -R11.w, R3, c[43];'#13+
'MUL R12.x, R6.w, R12;'#13+
'SLT R12.w, c[47].y, R12.y;'#13+
'MUL R12.w, R12.x, R12;'#13+
'MAD R0, R0, R12.w, R2;'#13+
'RCP R2.y, R12.z;'#13+
'DP3 R2.x, R5, R6;'#13+
'MAX R2.x, R2, c[47].y;'#13+
'MAD R2.w, R2.y, c[41].y, c[41].x;'#13+
'MUL R2.z, R2.y, c[41];'#13+
'MAD R2.y, R2.z, R2, R2.w;'#13+
'DP3 R2.z, R4, c[43];'#13+
'RCP R6.x, R2.y;'#13+
'POW R2.x, R2.x, c[18].x;'#13+
'MUL R12.z, R2.x, R6.x;'#13+
'POW R2.y, R2.z, c[40].w;'#13+
'ADD R2.w, -R7.y, c[40].y;'#13+
'SLT R6.y, c[40].z, R2.z;'#13+
'ABS R2.z, R2.w;'#13+
'ABS R2.w, R6.y;'#13+
'SGE R2.z, c[47].y, R2;'#13+
'MUL R6.y, R6.w, R2.z;'#13+
'SGE R2.w, c[47].y, R2;'#13+
'MUL R2.z, R6.y, R2.w;'#13+
'MAD R2.z, -R2.y, R2, R2.y;'#13+
'DP3 R2.y, R5, -R4;'#13+
'MUL R7.y, R6.x, R2.z;'#13+
'MAX R6.z, R2.y, c[47].y;'#13+
'SLT R4.x, c[47].y, R6.z;'#13+
'MUL R2.x, R2, R7.y;'#13+
'ADD R4.z, -R7.x, c[40].y;'#13+
'ABS R4.z, R4;'#13+
'SGE R4.z, c[47].y, R4;'#13+
'MUL R4.y, R4.x, R6;'#13+
'MUL R2, R2.x, c[45];'#13+
'MAD R2, R2, R4.y, R0;'#13+
'DP3 R4.y, R3, R3;'#13+
'RSQ R4.y, R4.y;'#13+
'MUL R3.xyz, R4.y, R3;'#13+
'DP3 R3.x, -R5, R3;'#13+
'DP3 R5.y, -R5, c[43];'#13+
'MUL R11.w, R6, R4.z;'#13+
'MAX R5.y, R5, c[47];'#13+
'ABS R5.x, c[40].y;'#13+
'SGE R5.x, c[47].y, R5;'#13+
'MUL R0, R12.z, c[45];'#13+
'MUL R3.y, R11.w, R4.x;'#13+
'MAD R2, R0, R3.y, R2;'#13+
'MAX R0.x, R3, c[47].y;'#13+
'MUL R3, R3.w, c[23];'#13+
'MUL R4, R4.w, R3;'#13+
'POW R0.x, R0.x, c[18].x;'#13+
'MUL R5.x, R6.w, R5;'#13+
'SLT R5.z, c[47].y, R5.y;'#13+
'MUL R5.z, R5.x, R5;'#13+
'MUL R0, R0.x, c[45];'#13+
'MAD R0, R0, R5.z, R2;'#13+
'MUL R2, R11.z, R4;'#13+
'MUL R3, R11.x, R3;'#13+
'MAD R4, R10.w, R3, R2;'#13+
'MUL R3, R9.y, c[23];'#13+
'MAD R3, R9.x, R3, R4;'#13+
'MUL R2, R10.y, c[30];'#13+
'MUL R4, R8.w, R2;'#13+
'MAD R3, R8.z, R4, R3;'#13+
'MUL R2, R8.x, R2;'#13+
'MAD R2, R8.y, R2, R3;'#13+
'MUL R4, R7.w, c[30];'#13+
'MUL R3, R10.z, c[37];'#13+
'MAD R2, R7.z, R4, R2;'#13+
'MUL R4, R10.x, R3;'#13+
'MAD R2, R9.w, R4, R2;'#13+
'MUL R3, R9.z, R3;'#13+
'MAD R2, R11.y, R3, R2;'#13+
'MUL R4, R12.y, c[37];'#13+
'MUL R3, R6.z, c[44];'#13+
'MAD R2, R12.x, R4, R2;'#13+
'MUL R4, R7.y, R3;'#13+
'MAD R2, R6.y, R4, R2;'#13+
'MUL R3, R6.x, R3;'#13+
'MAD R2, R11.w, R3, R2;'#13+
'MUL R3, R5.y, c[44];'#13+
'MAD R2, R5.x, R3, R2;'#13+
'ADD R4.x, -R7, c[12].y;'#13+
'ABS R4.x, R4;'#13+
'SGE R4.x, c[47].y, R4;'#13+
'ABS R4.x, R4;'#13+
'SGE R5.x, c[47].y, R4;'#13+
'MOV R3, c[32];'#13+
'ADD R3, R3, c[25];'#13+
'MUL R4, vertex.color, c[14];'#13+
'MUL R6.x, R5.w, R5;'#13+
'ADD R5, -R4, c[14];'#13+
'MAD R5, R5, R6.x, R4;'#13+
'ADD R4, R3, c[39];'#13+
'ADD R4, R4, c[46];'#13+
'MOV R3.xyz, c[17];'#13+
'MOV R3.w, c[47].x;'#13+
'ADD R3, R3, -R5;'#13+
'MAD R3, R6.w, R3, R5;'#13+
'MUL R4, R4, c[16];'#13+
'MAD R3, R6.w, R4, R3;'#13+
'MUL R2, R2, c[14];'#13+
'MAD R2, R6.w, R2, R3;'#13+
'MUL R0, R0, c[15];'#13+
'MAD R0, R0, R6.w, R2;'#13+
'MIN R2, R0, c[47].x;'#13+
'MAX R2, R2, c[47].y;'#13+
'ADD R2, R2, -R0;'#13+
'MAD result.color, R2, R6.w, R0;'#13+
'DP4 result.position.w, R1, c[3];'#13+
'DP4 result.position.z, R1, c[2];'#13+
'DP4 result.position.y, R1, c[1];'#13+
'DP4 result.position.x, R1, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
ARBVP1_Full: PAnsiChar =
'!!ARBvp1.0'#13+
'PARAM c[76] = { program.local[0..74],'#13+
' { 1, 0, 2 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'TEMP R3;'#13+
'TEMP R4;'#13+
'TEMP R5;'#13+
'TEMP R6;'#13+
'TEMP R7;'#13+
'TEMP R8;'#13+
'TEMP R9;'#13+
'TEMP R10;'#13+
'TEMP R11;'#13+
'TEMP R12;'#13+
'TEMP R13;'#13+
'TEMP R14;'#13+
'TEMP R15;'#13+
'TEMP R16;'#13+
'TEMP R17;'#13+
'TEMP R18;'#13+
'TEMP R19;'#13+
'ABS R6.w, c[19].y;'#13+
'MOV R0.w, c[75].x;'#13+
'MOV R0.xyz, vertex.position;'#13+
'DP4 R3.z, R0, c[6];'#13+
'DP4 R3.x, R0, c[4];'#13+
'DP4 R3.y, R0, c[5];'#13+
'ADD R1.xyz, R3, -c[21];'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R2.w, R1.w;'#13+
'DP3 R1.w, R3, R3;'#13+
'RSQ R4.w, R1.w;'#13+
'MUL R1.xyz, R2.w, R1;'#13+
'MAD R4.xyz, -R4.w, R3, -R1;'#13+
'DP3 R3.w, R4, R4;'#13+
'RSQ R3.w, R3.w;'#13+
'MUL R4.xyz, R3.w, R4;'#13+
'MOV R5.xyz, vertex.normal;'#13+
'MOV R5.w, c[75].y;'#13+
'DP4 R2.z, R5, c[10];'#13+
'DP4 R2.x, R5, c[8];'#13+
'DP4 R2.y, R5, c[9];'#13+
'DP3 R1.w, R2, R2;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R6.xyz, R1.w, R2;'#13+
'DP3 R1.w, R6, R4;'#13+
'MOV R5.xy, c[75].xzzw;'#13+
'DP3 R2.x, R1, c[22];'#13+
'DP3 R7.x, -R6, c[22];'#13+
'DP3 R19.y, -R6, c[64];'#13+
'MAX R17.y, R7.x, c[75];'#13+
'MAX R1.w, R1, c[75].y;'#13+
'POW R4.x, R1.w, c[18].x;'#13+
'DP3 R1.w, R6, -R1;'#13+
'RCP R1.x, R2.w;'#13+
'MAX R18.w, R1, c[75].y;'#13+
'MAX R19.y, R19, c[75];'#13+
'SLT R2.y, c[19].z, R2.x;'#13+
'MAD R1.z, R1.x, c[20].y, c[20].x;'#13+
'MUL R1.y, R1.x, c[20].z;'#13+
'MAD R1.y, R1, R1.x, R1.z;'#13+
'ABS R1.x, R2.y;'#13+
'POW R1.z, R2.x, c[19].w;'#13+
'SGE R2.y, c[75], R1.x;'#13+
'ABS R1.x, c[12];'#13+
'SGE R7.z, c[75].y, R1.x;'#13+
'ADD R2.x, -R5.y, c[19].y;'#13+
'ABS R1.x, R7.z;'#13+
'ABS R2.x, R2;'#13+
'SGE R7.y, c[75], R1.x;'#13+
'SGE R2.x, c[75].y, R2;'#13+
'MUL R18.y, R7, R2.x;'#13+
'SLT R5.z, c[75].y, R18.w;'#13+
'MUL R1.x, R18.y, R2.y;'#13+
'SGE R6.w, c[75].y, R6;'#13+
'MAD R1.x, -R1.z, R1, R1.z;'#13+
'RCP R18.x, R1.y;'#13+
'MUL R3.w, R18.x, R1.x;'#13+
'MUL R1.x, R4, R3.w;'#13+
'MUL R1, R1.x, c[24];'#13+
'MUL R2.x, R5.z, R18.y;'#13+
'MUL R2, R1, R2.x;'#13+
'ADD R4.y, -R5.x, c[19];'#13+
'ABS R1.y, R4;'#13+
'MUL R1.x, R4, R18;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R17.w, R7.y, R4.x;'#13+
'MUL R1, R1.x, c[24];'#13+
'MUL R5.w, R17, R5.z;'#13+
'MAD R2, R1, R5.w, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[22];'#13+
'ADD R4.xyz, R3, -c[28];'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R5.w, R1.w;'#13+
'MUL R1.xyz, R5.w, R1;'#13+
'DP3 R5.z, R4, R4;'#13+
'RSQ R5.z, R5.z;'#13+
'MUL R4.xyz, R5.z, R4;'#13+
'MAD R8.xyz, -R4.w, R3, -R4;'#13+
'DP3 R1.w, R8, R8;'#13+
'DP3 R5.w, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R8;'#13+
'DP3 R1.x, R6, R1;'#13+
'MAX R1.w, R5, c[75].y;'#13+
'MAX R5.w, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'MUL R1, R1.y, c[24];'#13+
'MUL R17.x, R7.y, R6.w;'#13+
'SLT R7.x, c[75].y, R17.y;'#13+
'MUL R6.w, R17.x, R7.x;'#13+
'MAD R2, R1, R6.w, R2;'#13+
'DP3 R1.w, R6, -R4;'#13+
'RCP R1.x, R5.z;'#13+
'DP3 R7.x, -R6, c[29];'#13+
'MAX R17.z, R1.w, c[75].y;'#13+
'MAX R14.x, R7, c[75].y;'#13+
'ABS R6.w, c[26].y;'#13+
'SGE R6.w, c[75].y, R6;'#13+
'DP3 R4.x, R4, c[29];'#13+
'POW R5.w, R5.w, c[18].x;'#13+
'MAD R1.z, R1.x, c[27].y, c[27].x;'#13+
'MUL R1.y, R1.x, c[27].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'POW R1.y, R4.x, c[26].w;'#13+
'ADD R1.z, -R5.y, c[26].y;'#13+
'SLT R4.x, c[26].z, R4;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'ABS R4.x, R4;'#13+
'MUL R16.y, R7, R1.z;'#13+
'SLT R5.z, c[75].y, R17;'#13+
'SGE R4.x, c[75].y, R4;'#13+
'MUL R1.z, R16.y, R4.x;'#13+
'RCP R16.x, R1.x;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R16.z, R16.x, R1.y;'#13+
'MUL R1.x, R5.w, R16.z;'#13+
'MUL R1, R1.x, c[31];'#13+
'MUL R4.y, R5.z, R16;'#13+
'MAD R2, R1, R4.y, R2;'#13+
'ADD R4.x, -R5, c[26].y;'#13+
'ABS R1.y, R4.x;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R15.x, R7.y, R4;'#13+
'MUL R1.x, R5.w, R16;'#13+
'MUL R1, R1.x, c[31];'#13+
'MUL R5.w, R15.x, R5.z;'#13+
'MAD R2, R1, R5.w, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[29];'#13+
'ADD R4.xyz, R3, -c[35];'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R5.w, R1.w;'#13+
'MUL R1.xyz, R5.w, R1;'#13+
'DP3 R5.z, R4, R4;'#13+
'RSQ R5.z, R5.z;'#13+
'MUL R4.xyz, R5.z, R4;'#13+
'MAD R8.xyz, -R4.w, R3, -R4;'#13+
'DP3 R1.w, R8, R8;'#13+
'DP3 R5.w, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R8;'#13+
'DP3 R1.x, R6, R1;'#13+
'MAX R1.w, R5, c[75].y;'#13+
'MAX R5.w, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'MUL R1, R1.y, c[31];'#13+
'MUL R13.w, R7.y, R6;'#13+
'SLT R7.x, c[75].y, R14;'#13+
'MUL R6.w, R13, R7.x;'#13+
'MAD R2, R1, R6.w, R2;'#13+
'DP3 R1.w, R6, -R4;'#13+
'RCP R1.x, R5.z;'#13+
'DP3 R7.x, -R6, c[36];'#13+
'MAX R14.w, R1, c[75].y;'#13+
'MAX R11.z, R7.x, c[75].y;'#13+
'ABS R6.w, c[33].y;'#13+
'SGE R6.w, c[75].y, R6;'#13+
'DP3 R4.x, R4, c[36];'#13+
'POW R5.w, R5.w, c[18].x;'#13+
'MAD R1.z, R1.x, c[34].y, c[34].x;'#13+
'MUL R1.y, R1.x, c[34].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'POW R1.y, R4.x, c[33].w;'#13+
'ADD R1.z, -R5.y, c[33].y;'#13+
'SLT R4.x, c[33].z, R4;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'ABS R4.x, R4;'#13+
'MUL R12.y, R7, R1.z;'#13+
'SLT R5.z, c[75].y, R14.w;'#13+
'SGE R4.x, c[75].y, R4;'#13+
'MUL R1.z, R12.y, R4.x;'#13+
'RCP R11.w, R1.x;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R12.z, R11.w, R1.y;'#13+
'MUL R1.x, R5.w, R12.z;'#13+
'MUL R1, R1.x, c[38];'#13+
'MUL R4.y, R5.z, R12;'#13+
'MAD R2, R1, R4.y, R2;'#13+
'ADD R4.x, -R5, c[33].y;'#13+
'ABS R1.y, R4.x;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R12.x, R7.y, R4;'#13+
'MUL R1.x, R5.w, R11.w;'#13+
'MUL R1, R1.x, c[38];'#13+
'MUL R5.w, R12.x, R5.z;'#13+
'MAD R2, R1, R5.w, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[36];'#13+
'ADD R4.xyz, R3, -c[42];'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R5.w, R1.w;'#13+
'MUL R1.xyz, R5.w, R1;'#13+
'DP3 R5.z, R4, R4;'#13+
'RSQ R5.z, R5.z;'#13+
'MUL R4.xyz, R5.z, R4;'#13+
'MAD R8.xyz, -R4.w, R3, -R4;'#13+
'DP3 R1.w, R8, R8;'#13+
'DP3 R5.w, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R8;'#13+
'DP3 R1.x, R6, R1;'#13+
'MAX R1.w, R5, c[75].y;'#13+
'MAX R5.w, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'MUL R1, R1.y, c[38];'#13+
'MUL R11.y, R7, R6.w;'#13+
'SLT R7.x, c[75].y, R11.z;'#13+
'MUL R6.w, R11.y, R7.x;'#13+
'MAD R2, R1, R6.w, R2;'#13+
'DP3 R1.w, R6, -R4;'#13+
'RCP R1.x, R5.z;'#13+
'DP3 R7.x, -R6, c[43];'#13+
'MAX R10.z, R1.w, c[75].y;'#13+
'MAX R9.w, R7.x, c[75].y;'#13+
'ABS R6.w, c[40].y;'#13+
'SGE R6.w, c[75].y, R6;'#13+
'DP3 R4.x, R4, c[43];'#13+
'POW R5.w, R5.w, c[18].x;'#13+
'MAD R1.z, R1.x, c[41].y, c[41].x;'#13+
'MUL R1.y, R1.x, c[41].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'POW R1.y, R4.x, c[40].w;'#13+
'ADD R1.z, -R5.y, c[40].y;'#13+
'SLT R4.x, c[40].z, R4;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'ABS R4.x, R4;'#13+
'MUL R10.w, R7.y, R1.z;'#13+
'SLT R5.z, c[75].y, R10;'#13+
'SGE R4.x, c[75].y, R4;'#13+
'MUL R1.z, R10.w, R4.x;'#13+
'RCP R10.x, R1.x;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R11.x, R10, R1.y;'#13+
'MUL R1.x, R5.w, R11;'#13+
'MUL R1, R1.x, c[45];'#13+
'MUL R4.y, R5.z, R10.w;'#13+
'MAD R2, R1, R4.y, R2;'#13+
'ADD R4.x, -R5, c[40].y;'#13+
'ABS R1.y, R4.x;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R10.y, R7, R4.x;'#13+
'MUL R1.x, R5.w, R10;'#13+
'MUL R1, R1.x, c[45];'#13+
'MUL R5.w, R10.y, R5.z;'#13+
'MAD R2, R1, R5.w, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[43];'#13+
'ADD R4.xyz, R3, -c[49];'#13+
'DP3 R5.z, R4, R4;'#13+
'RSQ R5.w, R5.z;'#13+
'MUL R4.xyz, R5.w, R4;'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R5.z, R1.w;'#13+
'MAD R8.xyz, -R4.w, R3, -R4;'#13+
'DP3 R1.w, R8, R8;'#13+
'MUL R1.xyz, R5.z, R1;'#13+
'DP3 R5.z, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R8;'#13+
'DP3 R1.x, R6, R1;'#13+
'MAX R1.w, R5.z, c[75].y;'#13+
'MAX R5.z, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'MUL R1, R1.y, c[45];'#13+
'MUL R9.z, R7.y, R6.w;'#13+
'SLT R7.x, c[75].y, R9.w;'#13+
'MUL R6.w, R9.z, R7.x;'#13+
'MAD R2, R1, R6.w, R2;'#13+
'DP3 R1.w, R6, -R4;'#13+
'RCP R1.x, R5.w;'#13+
'DP3 R7.x, -R6, c[50];'#13+
'MAX R8.w, R1, c[75].y;'#13+
'MAX R8.x, R7, c[75].y;'#13+
'ABS R6.w, c[47].y;'#13+
'SGE R6.w, c[75].y, R6;'#13+
'DP3 R4.x, R4, c[50];'#13+
'POW R5.z, R5.z, c[18].x;'#13+
'MAD R1.z, R1.x, c[48].y, c[48].x;'#13+
'MUL R1.y, R1.x, c[48].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'POW R1.y, R4.x, c[47].w;'#13+
'ADD R1.z, -R5.y, c[47].y;'#13+
'SLT R4.x, c[47].z, R4;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'ABS R4.x, R4;'#13+
'MUL R9.x, R7.y, R1.z;'#13+
'SGE R4.x, c[75].y, R4;'#13+
'MUL R1.z, R9.x, R4.x;'#13+
'SLT R5.w, c[75].y, R8;'#13+
'RCP R8.y, R1.x;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R9.y, R8, R1;'#13+
'MUL R1.x, R5.z, R9.y;'#13+
'MUL R1, R1.x, c[52];'#13+
'MUL R4.y, R5.w, R9.x;'#13+
'MAD R2, R1, R4.y, R2;'#13+
'ADD R4.x, -R5, c[47].y;'#13+
'ABS R1.y, R4.x;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R8.z, R7.y, R4.x;'#13+
'MUL R1.x, R5.z, R8.y;'#13+
'ADD R4.xyz, R3, -c[56];'#13+
'DP3 R5.z, R4, R4;'#13+
'RSQ R5.z, R5.z;'#13+
'MUL R4.xyz, R5.z, R4;'#13+
'MAD R13.xyz, -R4.w, R3, -R4;'#13+
'MUL R1, R1.x, c[52];'#13+
'MUL R5.w, R8.z, R5;'#13+
'MAD R2, R1, R5.w, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[50];'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R5.w, R1.w;'#13+
'DP3 R1.w, R13, R13;'#13+
'MUL R1.xyz, R5.w, R1;'#13+
'DP3 R5.w, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R13;'#13+
'DP3 R1.x, R6, R1;'#13+
'MAX R1.w, R5, c[75].y;'#13+
'MAX R5.w, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'MUL R1, R1.y, c[52];'#13+
'POW R12.w, R5.w, c[18].x;'#13+
'MUL R7.w, R7.y, R6;'#13+
'SLT R7.x, c[75].y, R8;'#13+
'MUL R6.w, R7, R7.x;'#13+
'MAD R2, R1, R6.w, R2;'#13+
'RCP R1.x, R5.z;'#13+
'DP3 R1.w, R6, -R4;'#13+
'MAX R5.z, R1.w, c[75].y;'#13+
'DP3 R4.x, R4, c[57];'#13+
'SLT R13.x, c[75].y, R5.z;'#13+
'MAD R1.z, R1.x, c[55].y, c[55].x;'#13+
'MUL R1.y, R1.x, c[55].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'POW R1.y, R4.x, c[54].w;'#13+
'ADD R1.z, -R5.y, c[54].y;'#13+
'SLT R4.x, c[54].z, R4;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'MUL R7.x, R7.y, R1.z;'#13+
'ABS R4.x, R4;'#13+
'SGE R4.x, c[75].y, R4;'#13+
'MUL R1.z, R7.x, R4.x;'#13+
'RCP R6.w, R1.x;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R5.w, R6, R1.y;'#13+
'MUL R1.x, R12.w, R5.w;'#13+
'MUL R1, R1.x, c[59];'#13+
'MUL R4.y, R13.x, R7.x;'#13+
'MAD R2, R1, R4.y, R2;'#13+
'ADD R4.x, -R5, c[54].y;'#13+
'ABS R1.y, R4.x;'#13+
'SGE R4.x, c[75].y, R1.y;'#13+
'MUL R1.x, R12.w, R6.w;'#13+
'MUL R12.w, R7.y, R4.x;'#13+
'MUL R1, R1.x, c[59];'#13+
'MUL R13.y, R12.w, R13.x;'#13+
'MAD R2, R1, R13.y, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[57];'#13+
'ADD R4.xyz, R3, -c[63];'#13+
'DP3 R13.x, R4, R4;'#13+
'RSQ R15.y, R13.x;'#13+
'MUL R4.xyz, R15.y, R4;'#13+
'DP3 R1.w, R1, R1;'#13+
'RSQ R14.y, R1.w;'#13+
'MAD R13.xyz, -R4.w, R3, -R4;'#13+
'DP3 R1.w, R13, R13;'#13+
'MUL R1.xyz, R14.y, R1;'#13+
'DP3 R14.y, -R6, R1;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R1.xyz, R1.w, R13;'#13+
'DP3 R1.x, R6, R1;'#13+
'DP3 R13.z, -R6, c[57];'#13+
'MAX R1.w, R14.y, c[75].y;'#13+
'MAX R14.z, R13, c[75].y;'#13+
'MAX R13.x, R1, c[75].y;'#13+
'POW R1.y, R1.w, c[18].x;'#13+
'ABS R13.y, c[54];'#13+
'SGE R13.y, c[75], R13;'#13+
'MUL R1, R1.y, c[59];'#13+
'MUL R14.y, R7, R13;'#13+
'SLT R13.z, c[75].y, R14;'#13+
'MUL R13.y, R14, R13.z;'#13+
'MAD R2, R1, R13.y, R2;'#13+
'RCP R1.x, R15.y;'#13+
'DP3 R1.w, R4, c[64];'#13+
'POW R13.x, R13.x, c[18].x;'#13+
'MAD R1.z, R1.x, c[62].y, c[62].x;'#13+
'MUL R1.y, R1.x, c[62].z;'#13+
'MAD R1.x, R1.y, R1, R1.z;'#13+
'RCP R15.y, R1.x;'#13+
'DP3 R1.x, R6, -R4;'#13+
'MAX R16.w, R1.x, c[75].y;'#13+
'POW R1.y, R1.w, c[61].w;'#13+
'ADD R1.z, -R5.y, c[61].y;'#13+
'ADD R4.y, -R5.x, c[61];'#13+
'SLT R1.w, c[61].z, R1;'#13+
'ABS R1.z, R1;'#13+
'SGE R1.z, c[75].y, R1;'#13+
'ABS R1.w, R1;'#13+
'MUL R15.z, R7.y, R1;'#13+
'SGE R1.w, c[75].y, R1;'#13+
'MUL R1.z, R15, R1.w;'#13+
'MAD R1.y, -R1, R1.z, R1;'#13+
'MUL R15.w, R15.y, R1.y;'#13+
'MUL R1.y, R13.x, R15.w;'#13+
'SLT R4.x, c[75].y, R16.w;'#13+
'MUL R1, R1.y, c[66];'#13+
'MUL R4.z, R4.x, R15;'#13+
'MAD R2, R1, R4.z, R2;'#13+
'ABS R4.y, R4;'#13+
'SGE R1.y, c[75], R4;'#13+
'MUL R18.z, R7.y, R1.y;'#13+
'MUL R1.x, R13, R15.y;'#13+
'MUL R1, R1.x, c[66];'#13+
'MUL R4.x, R18.z, R4;'#13+
'MAD R2, R1, R4.x, R2;'#13+
'MAD R1.xyz, -R4.w, R3, c[64];'#13+
'ADD R4.xyz, R3, -c[70];'#13+
'DP3 R1.w, R4, R4;'#13+
'RSQ R19.z, R1.w;'#13+
'DP3 R13.x, R1, R1;'#13+
'RSQ R1.w, R13.x;'#13+
'MUL R13.xyz, R1.w, R1;'#13+
'MUL R4.xyz, R19.z, R4;'#13+
'MAD R1.xyz, -R4.w, R3, -R4;'#13+
'DP3 R13.x, -R6, R13;'#13+
'DP3 R1.w, R1, R1;'#13+
'MAX R13.x, R13, c[75].y;'#13+
'POW R19.x, R13.x, c[18].x;'#13+
'RSQ R1.w, R1.w;'#13+
'MUL R13.xyz, R1.w, R1;'#13+
'MUL R1, R19.x, c[66];'#13+
'ABS R19.x, c[61].y;'#13+
'SGE R19.x, c[75].y, R19;'#13+
'MAD R3.xyz, -R4.w, R3, c[71];'#13+
'MUL R19.x, R7.y, R19;'#13+
'SLT R19.w, c[75].y, R19.y;'#13+
'MUL R19.w, R19.x, R19;'#13+
'MAD R1, R1, R19.w, R2;'#13+
'RCP R2.y, R19.z;'#13+
'DP3 R2.x, R6, R13;'#13+
'MAX R2.x, R2, c[75].y;'#13+
'MAD R2.w, R2.y, c[69].y, c[69].x;'#13+
'MUL R2.z, R2.y, c[69];'#13+
'MAD R2.y, R2.z, R2, R2.w;'#13+
'DP3 R2.z, R4, c[71];'#13+
'RCP R13.x, R2.y;'#13+
'ADD R2.w, -R5.y, c[68].y;'#13+
'POW R2.x, R2.x, c[18].x;'#13+
'MUL R19.z, R2.x, R13.x;'#13+
'POW R2.y, R2.z, c[68].w;'#13+
'SLT R5.y, c[68].z, R2.z;'#13+
'ABS R2.z, R2.w;'#13+
'ABS R2.w, R5.y;'#13+
'SGE R2.z, c[75].y, R2;'#13+
'MUL R5.y, R7, R2.z;'#13+
'SGE R2.w, c[75].y, R2;'#13+
'MUL R2.z, R5.y, R2.w;'#13+
'MAD R2.z, -R2.y, R2, R2.y;'#13+
'DP3 R2.y, R6, -R4;'#13+
'MUL R13.z, R13.x, R2;'#13+
'MAX R13.y, R2, c[75];'#13+
'SLT R4.x, c[75].y, R13.y;'#13+
'ADD R4.z, -R5.x, c[68].y;'#13+
'MUL R2.x, R2, R13.z;'#13+
'ABS R4.z, R4;'#13+
'MUL R4.y, R4.x, R5;'#13+
'MUL R2, R2.x, c[73];'#13+
'MAD R2, R2, R4.y, R1;'#13+
'DP3 R4.y, R3, R3;'#13+
'RSQ R4.y, R4.y;'#13+
'MUL R3.xyz, R4.y, R3;'#13+
'DP3 R3.x, -R6, R3;'#13+
'DP3 R6.y, -R6, c[71];'#13+
'MAX R6.y, R6, c[75];'#13+
'ABS R6.x, c[68].y;'#13+
'SGE R6.x, c[75].y, R6;'#13+
'MUL R1, R19.z, c[73];'#13+
'SGE R4.z, c[75].y, R4;'#13+
'MUL R19.z, R7.y, R4;'#13+
'MUL R3.y, R19.z, R4.x;'#13+
'MAD R4, R1, R3.y, R2;'#13+
'MAX R2.x, R3, c[75].y;'#13+
'MUL R6.x, R7.y, R6;'#13+
'SLT R6.z, c[75].y, R6.y;'#13+
'MUL R1, R18.w, c[23];'#13+
'POW R3.x, R2.x, c[18].x;'#13+
'MUL R2, R3.w, R1;'#13+
'MUL R6.z, R6.x, R6;'#13+
'MUL R3, R3.x, c[73];'#13+
'MAD R3, R3, R6.z, R4;'#13+
'MUL R2, R18.y, R2;'#13+
'MUL R1, R18.x, R1;'#13+
'MAD R4, R17.w, R1, R2;'#13+
'MUL R2, R17.y, c[23];'#13+
'MAD R4, R17.x, R2, R4;'#13+
'MUL R1, R17.z, c[30];'#13+
'MUL R2, R16.z, R1;'#13+
'MAD R2, R16.y, R2, R4;'#13+
'MUL R1, R16.x, R1;'#13+
'MAD R4, R15.x, R1, R2;'#13+
'MUL R2, R14.x, c[30];'#13+
'MAD R4, R13.w, R2, R4;'#13+
'MUL R1, R14.w, c[37];'#13+
'MUL R2, R12.z, R1;'#13+
'MAD R2, R12.y, R2, R4;'#13+
'MUL R1, R11.w, R1;'#13+
'MAD R1, R12.x, R1, R2;'#13+
'MUL R4, R11.z, c[37];'#13+
'MUL R2, R10.z, c[44];'#13+
'MAD R1, R11.y, R4, R1;'#13+
'MUL R4, R11.x, R2;'#13+
'MAD R1, R10.w, R4, R1;'#13+
'MUL R2, R10.x, R2;'#13+
'MAD R1, R10.y, R2, R1;'#13+
'MUL R4, R9.w, c[44];'#13+
'MUL R2, R8.w, c[51];'#13+
'MAD R1, R9.z, R4, R1;'#13+
'MUL R4, R9.y, R2;'#13+
'MAD R1, R9.x, R4, R1;'#13+
'MUL R2, R8.y, R2;'#13+
'MAD R1, R8.z, R2, R1;'#13+
'MUL R4, R8.x, c[51];'#13+
'MUL R2, R5.z, c[58];'#13+
'MAD R1, R7.w, R4, R1;'#13+
'MUL R4, R5.w, R2;'#13+
'MAD R1, R7.x, R4, R1;'#13+
'MUL R2, R6.w, R2;'#13+
'MAD R1, R12.w, R2, R1;'#13+
'MUL R4, R14.z, c[58];'#13+
'MUL R2, R16.w, c[65];'#13+
'MAD R1, R14.y, R4, R1;'#13+
'MUL R4, R15.w, R2;'#13+
'MAD R1, R15.z, R4, R1;'#13+
'MUL R2, R15.y, R2;'#13+
'MAD R1, R18.z, R2, R1;'#13+
'MUL R4, R19.y, c[65];'#13+
'MUL R2, R13.y, c[72];'#13+
'MAD R1, R19.x, R4, R1;'#13+
'MUL R4, R13.z, R2;'#13+
'MAD R1, R5.y, R4, R1;'#13+
'MUL R2, R13.x, R2;'#13+
'MAD R2, R19.z, R2, R1;'#13+
'MUL R4, R6.y, c[72];'#13+
'MAD R4, R6.x, R4, R2;'#13+
'ADD R2.x, -R5, c[12].y;'#13+
'MOV R1, c[32];'#13+
'ADD R1, R1, c[25];'#13+
'ADD R1, R1, c[39];'#13+
'ABS R2.x, R2;'#13+
'ADD R1, R1, c[46];'#13+
'SGE R2.x, c[75].y, R2;'#13+
'ABS R2.x, R2;'#13+
'SGE R5.x, c[75].y, R2;'#13+
'ADD R1, R1, c[53];'#13+
'ADD R1, R1, c[60];'#13+
'MUL R2, vertex.color, c[14];'#13+
'MUL R6.x, R7.z, R5;'#13+
'ADD R5, -R2, c[14];'#13+
'MAD R5, R5, R6.x, R2;'#13+
'ADD R2, R1, c[67];'#13+
'ADD R2, R2, c[74];'#13+
'MOV R1.xyz, c[17];'#13+
'MOV R1.w, c[75].x;'#13+
'ADD R1, R1, -R5;'#13+
'MAD R1, R7.y, R1, R5;'#13+
'MUL R2, R2, c[16];'#13+
'MAD R2, R7.y, R2, R1;'#13+
'MUL R1, R4, c[14];'#13+
'MAD R2, R7.y, R1, R2;'#13+
'MUL R1, R3, c[15];'#13+
'MAD R1, R1, R7.y, R2;'#13+
'MIN R2, R1, c[75].x;'#13+
'MAX R2, R2, c[75].y;'#13+
'ADD R2, R2, -R1;'#13+
'MAD result.color, R2, R7.y, R1;'#13+
'DP4 result.position.w, R0, c[3];'#13+
'DP4 result.position.z, R0, c[2];'#13+
'DP4 result.position.y, R0, c[1];'#13+
'DP4 result.position.x, R0, c[0];'#13+
'MOV result.texcoord[0].xy, vertex.texcoord[0];'#13+
'END';
GLES_GLSLV_NoLight: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' } '#13+
' } else {'#13+
' COLOR0 = vec4(VSParam17.xyz, 1.0);'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
GLES_GLSLV_1Light: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'uniform vec4 VSParam19;'#13+ // ligth1 Opts
'uniform vec4 VSParam20;'#13+ // light1 Attn
'uniform vec4 VSParam21;'#13+ // light1 Pos
'uniform vec4 VSParam22;'#13+ // light1 Dir
'uniform vec4 VSParam23;'#13+ // light1 Diffuse
'uniform vec4 VSParam24;'#13+ // light1 Specular
'uniform vec4 VSParam25;'#13+ // light1 Ambient
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void Lighting(vec3 normal, vec3 eyeDir, vec3 lightDir, vec4 lightColor, vec4 lightSpecularColor, float attenuation) {'#13+
' float NdotL = max(dot(normal, lightDir), 0.0);'#13+
' DiffuseLight += NdotL * lightColor * attenuation;'#13+
' if (NdotL > 0.0) {'#13+
' vec3 halfVector = normalize(lightDir + eyeDir);'#13+
' float NdotH = max(0.0, dot(normal, halfVector));'#13+
' float specular = pow(NdotH, VSParam18.x);'#13+
' SpecularLight += lightSpecularColor * (specular * attenuation);'#13+
' }'#13+
'}'#13+
'void DirectionalLight(vec3 normal, vec3 vertexPos, vec4 LDir, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' Lighting(-normal, eyeDir, LDir.xyz, LDiffuse, LSpecular, 1.0);'#13+
'}'#13+
'void PointLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LAttn, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 vp = vertexPos - LPos.xyz;'#13+
' float d = length(vp);'#13+
' vec3 lightDir = -normalize(vp);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void SpotLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LDir, vec4 LAttn, vec4 LOpts, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 VP = vertexPos - LPos.xyz;'#13+
' float d = length(VP);'#13+
' vec3 lightDir = -normalize(VP);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float spotDot = dot(-lightDir, LDir.xyz);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' float spotattenuation;'#13+
' if (spotDot > LOpts.z) {'#13+
' spotattenuation = pow(spotDot, LOpts.w);'#13+
' } else {'#13+
' spotattenuation = 0.0;'#13+
' }'#13+
' attenuation *= spotattenuation;'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' DiffuseLight = vec4(0.0);'#13+
' SpecularLight = vec4(0.0);'#13+
' AmbientLight = vec4(0.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' }'#13+
' } else {'#13+
' vec3 normal = normalize((VSParam8 * vec4(a_normal, 0)).xyz);'#13+
' vec3 ecPosition = (VSParam4 * vec4(a_position, 1.0)).xyz;'#13+
// light 1
' if (VSParam19.x > 0.0) {'#13+
' if (VSParam19.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam22, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam21, VSParam20, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam21, VSParam22, VSParam20, VSParam19, VSParam23, VSParam24);'#13+
' AmbientLight += VSParam25;'#13+
' }'#13+
' COLOR0 = vec4(VSParam17.xyz, 1);'#13+
' COLOR0 += AmbientLight * VSParam16 + DiffuseLight * VSParam14 + SpecularLight * VSParam15;'#13+
' COLOR0 = clamp(COLOR0, 0.0, 1.0 );'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
GLES_GLSLV_2Light: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'uniform vec4 VSParam19;'#13+ // ligth1 Opts
'uniform vec4 VSParam20;'#13+ // light1 Attn
'uniform vec4 VSParam21;'#13+ // light1 Pos
'uniform vec4 VSParam22;'#13+ // light1 Dir
'uniform vec4 VSParam23;'#13+ // light1 Diffuse
'uniform vec4 VSParam24;'#13+ // light1 Specular
'uniform vec4 VSParam25;'#13+ // light1 Ambient
'uniform vec4 VSParam26;'#13+ // ligth2 Opts
'uniform vec4 VSParam27;'#13+ // light2 Attn
'uniform vec4 VSParam28;'#13+ // light2 Pos
'uniform vec4 VSParam29;'#13+ // light2 Dir
'uniform vec4 VSParam30;'#13+ // light2 Diffuse
'uniform vec4 VSParam31;'#13+ // light2 Specular
'uniform vec4 VSParam32;'#13+ // light2 Ambient
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void Lighting(vec3 normal, vec3 eyeDir, vec3 lightDir, vec4 lightColor, vec4 lightSpecularColor, float attenuation) {'#13+
' float NdotL = max(dot(normal, lightDir), 0.0);'#13+
' DiffuseLight += NdotL * lightColor * attenuation;'#13+
' if (NdotL > 0.0) {'#13+
' vec3 halfVector = normalize(lightDir + eyeDir);'#13+
' float NdotH = max(0.0, dot(normal, halfVector));'#13+
' float specular = pow(NdotH, VSParam18.x);'#13+
' SpecularLight += lightSpecularColor * (specular * attenuation);'#13+
' }'#13+
'}'#13+
'void DirectionalLight(vec3 normal, vec3 vertexPos, vec4 LDir, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' Lighting(-normal, eyeDir, LDir.xyz, LDiffuse, LSpecular, 1.0);'#13+
'}'#13+
'void PointLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LAttn, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 vp = vertexPos - LPos.xyz;'#13+
' float d = length(vp);'#13+
' vec3 lightDir = -normalize(vp);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void SpotLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LDir, vec4 LAttn, vec4 LOpts, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 VP = vertexPos - LPos.xyz;'#13+
' float d = length(VP);'#13+
' vec3 lightDir = -normalize(VP);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float spotDot = dot(-lightDir, LDir.xyz);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' float spotattenuation;'#13+
' if (spotDot > LOpts.z) {'#13+
' spotattenuation = pow(spotDot, LOpts.w);'#13+
' } else {'#13+
' spotattenuation = 0.0;'#13+
' }'#13+
' attenuation *= spotattenuation;'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' DiffuseLight = vec4(0.0);'#13+
' SpecularLight = vec4(0.0);'#13+
' AmbientLight = vec4(0.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' }'#13+
' } else'#13+
' {'#13+
' vec3 normal = normalize((VSParam8 * vec4(a_normal, 0)).xyz);'#13+
' vec3 ecPosition = (VSParam4 * vec4(a_position, 1.0)).xyz;'#13+
// light 0
' if (VSParam19.x > 0.0) {'#13+
' if (VSParam19.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam22, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam21, VSParam20, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam21, VSParam22, VSParam20, VSParam19, VSParam23, VSParam24);'#13+
' AmbientLight += VSParam25;'#13+
' }'#13+
// light 1
' if (VSParam26.x > 0.0) {'#13+
' if (VSParam26.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam29, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam28, VSParam27, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam28, VSParam29, VSParam27, VSParam26, VSParam30, VSParam31);'#13+
' AmbientLight += VSParam32;'#13+
' }'#13+
' COLOR0 = vec4(VSParam17.xyz, 1);'#13+
' COLOR0 += AmbientLight * VSParam16 + DiffuseLight * VSParam14 + SpecularLight * VSParam15;'#13+
' COLOR0 = clamp(COLOR0, 0.0, 1.0 );'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
GLES_GLSLV_3Light: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'uniform vec4 VSParam19;'#13+ // ligth1 Opts
'uniform vec4 VSParam20;'#13+ // light1 Attn
'uniform vec4 VSParam21;'#13+ // light1 Pos
'uniform vec4 VSParam22;'#13+ // light1 Dir
'uniform vec4 VSParam23;'#13+ // light1 Diffuse
'uniform vec4 VSParam24;'#13+ // light1 Specular
'uniform vec4 VSParam25;'#13+ // light1 Ambient
'uniform vec4 VSParam26;'#13+ // ligth2 Opts
'uniform vec4 VSParam27;'#13+ // light2 Attn
'uniform vec4 VSParam28;'#13+ // light2 Pos
'uniform vec4 VSParam29;'#13+ // light2 Dir
'uniform vec4 VSParam30;'#13+ // light2 Diffuse
'uniform vec4 VSParam31;'#13+ // light2 Specular
'uniform vec4 VSParam32;'#13+ // light2 Ambient
'uniform vec4 VSParam33;'#13+ // ligth3 Opts
'uniform vec4 VSParam34;'#13+ // light3 Attn
'uniform vec4 VSParam35;'#13+ // light3 Pos
'uniform vec4 VSParam36;'#13+ // light3 Dir
'uniform vec4 VSParam37;'#13+ // light3 Diffuse
'uniform vec4 VSParam38;'#13+ // light3 Specular
'uniform vec4 VSParam39;'#13+ // light3 Ambient
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void Lighting(vec3 normal, vec3 eyeDir, vec3 lightDir, vec4 lightColor, vec4 lightSpecularColor, float attenuation) {'#13+
' float NdotL = max(dot(normal, lightDir), 0.0);'#13+
' DiffuseLight += NdotL * lightColor * attenuation;'#13+
' if (NdotL > 0.0) {'#13+
' vec3 halfVector = normalize(lightDir + eyeDir);'#13+
' float NdotH = max(0.0, dot(normal, halfVector));'#13+
' float specular = pow(NdotH, VSParam18.x);'#13+
' SpecularLight += lightSpecularColor * (specular * attenuation);'#13+
' }'#13+
'}'#13+
'void DirectionalLight(vec3 normal, vec3 vertexPos, vec4 LDir, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' Lighting(-normal, eyeDir, LDir.xyz, LDiffuse, LSpecular, 1.0);'#13+
'}'#13+
'void PointLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LAttn, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 vp = vertexPos - LPos.xyz;'#13+
' float d = length(vp);'#13+
' vec3 lightDir = -normalize(vp);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void SpotLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LDir, vec4 LAttn, vec4 LOpts, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 VP = vertexPos - LPos.xyz;'#13+
' float d = length(VP);'#13+
' vec3 lightDir = -normalize(VP);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float spotDot = dot(-lightDir, LDir.xyz);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' float spotattenuation;'#13+
' if (spotDot > LOpts.z) {'#13+
' spotattenuation = pow(spotDot, LOpts.w);'#13+
' } else {'#13+
' spotattenuation = 0.0;'#13+
' }'#13+
' attenuation *= spotattenuation;'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' DiffuseLight = vec4(0.0);'#13+
' SpecularLight = vec4(0.0);'#13+
' AmbientLight = vec4(0.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' }'#13+
' } else'#13+
' {'#13+
' vec3 normal = normalize((VSParam8 * vec4(a_normal, 0)).xyz);'#13+
' vec3 ecPosition = (VSParam4 * vec4(a_position, 1.0)).xyz;'#13+
// light 1
' if (VSParam19.x > 0.0) {'#13+
' if (VSParam19.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam22, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam21, VSParam20, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam21, VSParam22, VSParam20, VSParam19, VSParam23, VSParam24);'#13+
' AmbientLight += VSParam25;'#13+
' }'#13+
// light 2
' if (VSParam26.x > 0.0) {'#13+
' if (VSParam26.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam29, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam28, VSParam27, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam28, VSParam29, VSParam27, VSParam26, VSParam30, VSParam31);'#13+
' AmbientLight += VSParam32;'#13+
' }'#13+
// light 3
' if (VSParam33.x > 0.0) {'#13+
' if (VSParam33.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam36, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam35, VSParam34, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam35, VSParam36, VSParam34, VSParam33, VSParam37, VSParam38);'#13+
' AmbientLight += VSParam39;'#13+
' }'#13+
' COLOR0 = vec4(VSParam17.xyz, 1);'#13+
' COLOR0 += AmbientLight * VSParam16 + DiffuseLight * VSParam14 + SpecularLight * VSParam15;'#13+
' COLOR0 = clamp(COLOR0, 0.0, 1.0 );'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
GLES_GLSLV_4Light: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'uniform vec4 VSParam19;'#13+ // ligth1 Opts
'uniform vec4 VSParam20;'#13+ // light1 Attn
'uniform vec4 VSParam21;'#13+ // light1 Pos
'uniform vec4 VSParam22;'#13+ // light1 Dir
'uniform vec4 VSParam23;'#13+ // light1 Diffuse
'uniform vec4 VSParam24;'#13+ // light1 Specular
'uniform vec4 VSParam25;'#13+ // light1 Ambient
'uniform vec4 VSParam26;'#13+ // ligth2 Opts
'uniform vec4 VSParam27;'#13+ // light2 Attn
'uniform vec4 VSParam28;'#13+ // light2 Pos
'uniform vec4 VSParam29;'#13+ // light2 Dir
'uniform vec4 VSParam30;'#13+ // light2 Diffuse
'uniform vec4 VSParam31;'#13+ // light2 Specular
'uniform vec4 VSParam32;'#13+ // light2 Ambient
'uniform vec4 VSParam33;'#13+ // ligth3 Opts
'uniform vec4 VSParam34;'#13+ // light3 Attn
'uniform vec4 VSParam35;'#13+ // light3 Pos
'uniform vec4 VSParam36;'#13+ // light3 Dir
'uniform vec4 VSParam37;'#13+ // light3 Diffuse
'uniform vec4 VSParam38;'#13+ // light3 Specular
'uniform vec4 VSParam39;'#13+ // light3 Ambient
'uniform vec4 VSParam40;'#13+ // ligth4 Opts
'uniform vec4 VSParam41;'#13+ // light4 Attn
'uniform vec4 VSParam42;'#13+ // light4 Pos
'uniform vec4 VSParam43;'#13+ // light4 Dir
'uniform vec4 VSParam44;'#13+ // light4 Diffuse
'uniform vec4 VSParam45;'#13+ // light4 Specular
'uniform vec4 VSParam46;'#13+ // light4 Ambient
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void Lighting(vec3 normal, vec3 eyeDir, vec3 lightDir, vec4 lightColor, vec4 lightSpecularColor, float atten) {'#13+
' float NdotL = max(0.0, dot(normal, lightDir));'#13+
' DiffuseLight += lightColor * NdotL * atten;'#13+
' if (NdotL > 0.0) {'#13+
' vec3 halfVector = normalize(lightDir + eyeDir);'#13+
' float NdotH = max(0.0, dot(normal, halfVector));'#13+
' float specular = pow(NdotH, VSParam18.x);'#13+
' SpecularLight += lightSpecularColor * specular * atten;'#13+
' }'#13+
'}'#13+
'void DirectionalLight(vec3 normal, vec3 vertexPos, vec4 LDir, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' Lighting(-normal, eyeDir, LDir.xyz, LDiffuse, LSpecular, 1.0);'#13+
'}'#13+
'void PointLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LAttn, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 vp = vertexPos - LPos.xyz;'#13+
' float d = length(vp);'#13+
' vec3 lightDir = -normalize(vp);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void SpotLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LDir, vec4 LAttn, vec4 LOpts, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 VP = vertexPos - LPos.xyz;'#13+
' float d = length(VP);'#13+
' vec3 lightDir = -normalize(VP);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float spotDot = dot(-lightDir, LDir.xyz);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' float spotattenuation;'#13+
' if (spotDot > LOpts.z) {'#13+
' spotattenuation = pow(spotDot, LOpts.w);'#13+
' } else {'#13+
' spotattenuation = 0.0;'#13+
' }'#13+
' attenuation *= spotattenuation;'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' DiffuseLight = vec4(0.0);'#13+
' SpecularLight = vec4(0.0);'#13+
' AmbientLight = vec4(0.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' }'#13+
' } else {'#13+
' vec3 normal = normalize((VSParam8 * vec4(a_normal, 0)).xyz);'#13+
' vec3 ecPosition = (VSParam4 * vec4(a_position, 1.0)).xyz;'#13+
// light 1
' if (VSParam19.x > 0.0) {'#13+
' if (VSParam19.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam22, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam21, VSParam20, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam21, VSParam22, VSParam20, VSParam19, VSParam23, VSParam24);'#13+
' AmbientLight += VSParam25;'#13+
' }'#13+
// light 2
' if (VSParam26.x > 0.0) {'#13+
' if (VSParam26.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam29, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam28, VSParam27, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam28, VSParam29, VSParam27, VSParam26, VSParam30, VSParam31);'#13+
' AmbientLight += VSParam32;'#13+
' }'#13+
// light 3
' if (VSParam33.x > 0.0) {'#13+
' if (VSParam33.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam36, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam35, VSParam34, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam35, VSParam36, VSParam34, VSParam33, VSParam37, VSParam38);'#13+
' AmbientLight += VSParam39;'#13+
' }'#13+
// light 4
' if (VSParam40.x > 0.0) {'#13+
' if (VSParam40.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam43, VSParam44, VSParam45);'#13+
' if (VSParam40.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam42, VSParam41, VSParam44, VSParam45);'#13+
' if (VSParam40.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam42, VSParam43, VSParam41, VSParam40, VSParam44, VSParam45);'#13+
' AmbientLight += VSParam46;'#13+
' }'#13+
' COLOR0 = vec4(VSParam17.xyz, 1.0);'#13+
' COLOR0 += (AmbientLight * VSParam16);'#13+
' COLOR0 += (DiffuseLight * VSParam14);'#13+
' COLOR0 += (SpecularLight * VSParam15);'#13+
' COLOR0 = clamp(COLOR0, 0.0, 1.0 );'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
GLES_GLSLV_Full: PAnsiChar =
'attribute vec3 a_position;'#13+
'attribute vec3 a_normal;'#13+
'attribute vec4 a_color;'#13+
'attribute vec2 a_texcoord0;'#13+
'varying vec4 COLOR0;'#13+
'varying vec4 TEX0;'#13+
'uniform mat4 VSParam0;'#13+ // MPVMatrix
'uniform mat4 VSParam4;'#13+ // ModelView
'uniform mat4 VSParam8;'#13+ // ModelViewIT
'uniform vec4 VSParam12;'#13+ // options
'uniform vec4 VSParam13;'#13+ // reserver
'uniform vec4 VSParam14;'#13+ // material diffuse
'uniform vec4 VSParam15;'#13+ // material specular
'uniform vec4 VSParam16;'#13+ // material ambient
'uniform vec4 VSParam17;'#13+ // material emission
'uniform vec4 VSParam18;'#13+ // material opts
'uniform vec4 VSParam19;'#13+ // ligth1 Opts
'uniform vec4 VSParam20;'#13+ // light1 Attn
'uniform vec4 VSParam21;'#13+ // light1 Pos
'uniform vec4 VSParam22;'#13+ // light1 Dir
'uniform vec4 VSParam23;'#13+ // light1 Diffuse
'uniform vec4 VSParam24;'#13+ // light1 Specular
'uniform vec4 VSParam25;'#13+ // light1 Ambient
'uniform vec4 VSParam26;'#13+ // ligth2 Opts
'uniform vec4 VSParam27;'#13+ // light2 Attn
'uniform vec4 VSParam28;'#13+ // light2 Pos
'uniform vec4 VSParam29;'#13+ // light2 Dir
'uniform vec4 VSParam30;'#13+ // light2 Diffuse
'uniform vec4 VSParam31;'#13+ // light2 Specular
'uniform vec4 VSParam32;'#13+ // light2 Ambient
'uniform vec4 VSParam33;'#13+ // ligth3 Opts
'uniform vec4 VSParam34;'#13+ // light3 Attn
'uniform vec4 VSParam35;'#13+ // light3 Pos
'uniform vec4 VSParam36;'#13+ // light3 Dir
'uniform vec4 VSParam37;'#13+ // light3 Diffuse
'uniform vec4 VSParam38;'#13+ // light3 Specular
'uniform vec4 VSParam39;'#13+ // light3 Ambient
'uniform vec4 VSParam40;'#13+ // ligth4 Opts
'uniform vec4 VSParam41;'#13+ // light4 Attn
'uniform vec4 VSParam42;'#13+ // light4 Pos
'uniform vec4 VSParam43;'#13+ // light4 Dir
'uniform vec4 VSParam44;'#13+ // light4 Diffuse
'uniform vec4 VSParam45;'#13+ // light4 Specular
'uniform vec4 VSParam46;'#13+ // light4 Ambient
'uniform vec4 VSParam47;'#13+ // ligth5 Opts
'uniform vec4 VSParam48;'#13+ // light5 Attn
'uniform vec4 VSParam49;'#13+ // light5 Pos
'uniform vec4 VSParam50;'#13+ // light5 Dir
'uniform vec4 VSParam51;'#13+ // light5 Diffuse
'uniform vec4 VSParam52;'#13+ // light5 Specular
'uniform vec4 VSParam53;'#13+ // light5 Ambient
'uniform vec4 VSParam54;'#13+ // ligth6 Opts
'uniform vec4 VSParam55;'#13+ // light6 Attn
'uniform vec4 VSParam56;'#13+ // light6 Pos
'uniform vec4 VSParam57;'#13+ // light6 Dir
'uniform vec4 VSParam58;'#13+ // light6 Diffuse
'uniform vec4 VSParam59;'#13+ // light6 Specular
'uniform vec4 VSParam60;'#13+ // light6 Ambient
'uniform vec4 VSParam61;'#13+ // ligth7 Opts
'uniform vec4 VSParam62;'#13+ // light7 Attn
'uniform vec4 VSParam63;'#13+ // light7 Pos
'uniform vec4 VSParam64;'#13+ // light7 Dir
'uniform vec4 VSParam65;'#13+ // light7 Diffuse
'uniform vec4 VSParam66;'#13+ // light7 Specular
'uniform vec4 VSParam67;'#13+ // light7 Ambient
'uniform vec4 VSParam68;'#13+ // ligth8 Opts
'uniform vec4 VSParam69;'#13+ // light8 Attn
'uniform vec4 VSParam70;'#13+ // light8 Pos
'uniform vec4 VSParam71;'#13+ // light8 Dir
'uniform vec4 VSParam72;'#13+ // light8 Diffuse
'uniform vec4 VSParam73;'#13+ // light8 Specular
'uniform vec4 VSParam74;'#13+ // light8 Ambient
'vec4 DiffuseLight;'#13+
'vec4 SpecularLight;'#13+
'vec4 AmbientLight;'#13+
'void Lighting(vec3 normal, vec3 eyeDir, vec3 lightDir, vec4 lightColor, vec4 lightSpecularColor, float atten) {'#13+
' float NdotL = max(0.0, dot(normal, lightDir));'#13+
' DiffuseLight += lightColor * NdotL * atten;'#13+
' if (NdotL > 0.0) {'#13+
' vec3 halfVector = normalize(lightDir + eyeDir);'#13+
' float NdotH = max(0.0, dot(normal, halfVector));'#13+
' float specular = pow(NdotH, VSParam18.x);'#13+
' SpecularLight += lightSpecularColor * specular * atten;'#13+
' }'#13+
'}'#13+
'void DirectionalLight(vec3 normal, vec3 vertexPos, vec4 LDir, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' Lighting(-normal, eyeDir, LDir.xyz, LDiffuse, LSpecular, 1.0);'#13+
'}'#13+
'void PointLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LAttn, vec4 LDiffuse, vec4 LSpecular){'#13+
' vec3 vp = vertexPos - LPos.xyz;'#13+
' float d = length(vp);'#13+
' vec3 lightDir = -normalize(vp);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void SpotLight(vec3 normal, vec3 vertexPos, vec4 LPos, vec4 LDir, vec4 LAttn, vec4 LOpts, vec4 LDiffuse, vec4 LSpecular) {'#13+
' vec3 VP = vertexPos - LPos.xyz;'#13+
' float d = length(VP);'#13+
' vec3 lightDir = -normalize(VP);'#13+
' vec3 eyeDir = -normalize(vertexPos);'#13+
' float spotDot = dot(-lightDir, LDir.xyz);'#13+
' float attenuation = 1.0 / (LAttn.x + LAttn.y * d + LAttn.z * d * d);'#13+
' float spotattenuation;'#13+
' if (spotDot > LOpts.z) {'#13+
' spotattenuation = pow(spotDot, LOpts.w);'#13+
' } else {'#13+
' spotattenuation = 0.0;'#13+
' }'#13+
' attenuation *= spotattenuation;'#13+
' Lighting(normal, eyeDir, lightDir, LDiffuse, LSpecular, attenuation);'#13+
'}'#13+
'void main() {'#13+
' gl_Position = VSParam0 * vec4(a_position, 1.0);'#13+
' DiffuseLight = vec4(0.0);'#13+
' SpecularLight = vec4(0.0);'#13+
' AmbientLight = vec4(0.0);'#13+
' if (VSParam12.x == 0.0) {'#13+
' if (VSParam12.y == 1.0) {'#13+
' COLOR0 = a_color * VSParam14;'#13+
' } else {'#13+
' COLOR0 = VSParam14;'#13+
' }'#13+
' } else'#13+
' {'#13+
' vec3 normal = normalize((VSParam8 * vec4(a_normal, 0)).xyz);'#13+
' vec3 ecPosition = (VSParam4 * vec4(a_position, 1.0)).xyz;'#13+
// light 1
' if (VSParam19.x > 0.0) {'#13+
' if (VSParam19.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam22, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam21, VSParam20, VSParam23, VSParam24);'#13+
' if (VSParam19.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam21, VSParam22, VSParam20, VSParam19, VSParam23, VSParam24);'#13+
' AmbientLight += VSParam25;'#13+
' }'#13+
// light 2
' if (VSParam26.x > 0.0) {'#13+
' if (VSParam26.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam29, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam28, VSParam27, VSParam30, VSParam31);'#13+
' if (VSParam26.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam28, VSParam29, VSParam27, VSParam26, VSParam30, VSParam31);'#13+
' AmbientLight += VSParam32;'#13+
' }'#13+
// light 3
' if (VSParam33.x > 0.0) {'#13+
' if (VSParam33.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam36, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam35, VSParam34, VSParam37, VSParam38);'#13+
' if (VSParam33.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam35, VSParam36, VSParam34, VSParam33, VSParam37, VSParam38);'#13+
' AmbientLight += VSParam39;'#13+
' }'#13+
// light 4
' if (VSParam40.x > 0.0) {'#13+
' if (VSParam40.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam43, VSParam44, VSParam45);'#13+
' if (VSParam40.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam42, VSParam41, VSParam44, VSParam45);'#13+
' if (VSParam40.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam42, VSParam43, VSParam41, VSParam40, VSParam44, VSParam45);'#13+
' AmbientLight += VSParam46;'#13+
' }'#13+
// light 5
' if (VSParam47.x > 0.0) {'#13+
' if (VSParam47.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam50, VSParam51, VSParam52);'#13+
' if (VSParam47.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam49, VSParam48, VSParam51, VSParam52);'#13+
' if (VSParam47.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam49, VSParam50, VSParam48, VSParam47, VSParam51, VSParam52);'#13+
' AmbientLight += VSParam53;'#13+
' }'#13+
// light 6
' if (VSParam54.x > 0.0) {'#13+
' if (VSParam54.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam57, VSParam58, VSParam59);'#13+
' if (VSParam54.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam56, VSParam55, VSParam58, VSParam59);'#13+
' if (VSParam54.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam56, VSParam57, VSParam55, VSParam54, VSParam58, VSParam59);'#13+
' AmbientLight += VSParam60;'#13+
' }'#13+
// light 7
' if (VSParam61.x > 0.0) {'#13+
' if (VSParam61.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam64, VSParam65, VSParam66);'#13+
' if (VSParam61.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam63, VSParam62, VSParam65, VSParam66);'#13+
' if (VSParam61.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam63, VSParam64, VSParam62, VSParam61, VSParam65, VSParam66);'#13+
' AmbientLight += VSParam67;'#13+
' }'#13+
// light 8
' if (VSParam68.x > 0.0) {'#13+
' if (VSParam68.y == 0.0)'#13+
' DirectionalLight(normal, ecPosition, VSParam71, VSParam72, VSParam73);'#13+
' if (VSParam68.y == 1.0)'#13+
' PointLight(normal, ecPosition, VSParam70, VSParam69, VSParam72, VSParam73);'#13+
' if (VSParam68.y == 2.0)'#13+
' SpotLight(normal, ecPosition, VSParam70, VSParam71, VSParam69, VSParam68, VSParam72, VSParam73);'#13+
' AmbientLight += VSParam74;'#13+
' }'#13+
' COLOR0 = vec4(VSParam17.xyz, 1.0);'#13+
' COLOR0 += (AmbientLight * VSParam16);'#13+
' COLOR0 += (DiffuseLight * VSParam14);'#13+
' COLOR0 += (SpecularLight * VSParam15);'#13+
' COLOR0 = clamp(COLOR0, 0.0, 1.0 );'#13+
' }'#13+
' TEX0 = vec4(a_texcoord0, 0, 0);'#13+
'}';
DX9PS2BIN: array [0..411] of byte = (
$00, $02, $FF, $FF, $FE, $FF, $29, $00, $43, $54, $41, $42, $1C, $00, $00, $00, $7B, $00, $00, $00, $00, $02, $FF, $FF, $02, $00, $00, $00, $1C, $00, $00, $00, $00, $01, $00, $20, $74, $00, $00, $00,
$44, $00, $00, $00, $02, $00, $00, $00, $01, $00, $02, $00, $48, $00, $00, $00, $00, $00, $00, $00, $58, $00, $00, $00, $03, $00, $00, $00, $01, $00, $02, $00, $64, $00, $00, $00, $00, $00, $00, $00,
$6D, $6F, $00, $AB, $01, $00, $03, $00, $01, $00, $04, $00, $01, $00, $00, $00, $00, $00, $00, $00, $74, $65, $78, $74, $75, $72, $65, $30, $00, $AB, $AB, $AB, $04, $00, $0C, $00, $01, $00, $01, $00,
$01, $00, $00, $00, $00, $00, $00, $00, $70, $73, $5F, $32, $5F, $30, $00, $4D, $69, $63, $72, $6F, $73, $6F, $66, $74, $20, $28, $52, $29, $20, $44, $33, $44, $58, $39, $20, $53, $68, $61, $64, $65,
$72, $20, $43, $6F, $6D, $70, $69, $6C, $65, $72, $20, $00, $51, $00, $00, $05, $01, $00, $0F, $A0, $00, $00, $80, $BF, $00, $00, $00, $C0, $00, $00, $00, $00, $00, $00, $00, $00, $1F, $00, $00, $02,
$00, $00, $00, $80, $00, $00, $0F, $90, $1F, $00, $00, $02, $00, $00, $00, $80, $00, $00, $03, $B0, $1F, $00, $00, $02, $00, $00, $00, $90, $00, $08, $0F, $A0, $42, $00, $00, $03, $00, $00, $0F, $80,
$00, $00, $E4, $B0, $00, $08, $E4, $A0, $01, $00, $00, $02, $01, $00, $08, $80, $00, $00, $00, $A0, $02, $00, $00, $03, $01, $00, $01, $80, $01, $00, $FF, $80, $01, $00, $55, $A0, $05, $00, $00, $03,
$01, $00, $01, $80, $01, $00, $00, $80, $01, $00, $00, $80, $02, $00, $00, $03, $01, $00, $02, $80, $01, $00, $FF, $80, $01, $00, $00, $A0, $05, $00, $00, $03, $01, $00, $02, $80, $01, $00, $55, $80,
$01, $00, $55, $80, $58, $00, $00, $04, $02, $00, $0F, $80, $01, $00, $55, $81, $00, $00, $E4, $80, $00, $00, $E4, $90, $05, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $80, $00, $00, $E4, $90,
$58, $00, $00, $04, $00, $00, $0F, $80, $01, $00, $00, $81, $00, $00, $E4, $80, $02, $00, $E4, $80, $05, $00, $00, $03, $00, $00, $0F, $80, $00, $00, $E4, $80, $00, $00, $55, $A0, $01, $00, $00, $02,
$00, $08, $0F, $80, $00, $00, $E4, $80, $FF, $FF, $00, $00
);
ARBFP1: PAnsiChar =
'!!ARBfp1.0'#13+
'PARAM c[3] = { program.local[0..1],'#13+
' { 2, 1 } };'#13+
'TEMP R0;'#13+
'TEMP R1;'#13+
'TEMP R2;'#13+
'MOV R2.xy, c[2];'#13+
'ABS R1.x, c[0];'#13+
'CMP R1, -R1.x, R0, fragment.color.primary;'#13+
'ADD R2.y, -R2, c[0].x;'#13+
'ADD R2.x, -R2, c[0];'#13+
'TEX R0, fragment.texcoord[0], texture[0], 2D;'#13+
'ABS R2.y, R2;'#13+
'CMP R1, -R2.y, R1, R0;'#13+
'MUL R0, fragment.color.primary, R0;'#13+
'ABS R2.x, R2;'#13+
'CMP R0, -R2.x, R1, R0;'#13+
'MUL result.color, R0, c[0].y;'#13+
'END';
GLES_GLSLF: PAnsiChar =
'uniform sampler2D texture0;'+
'uniform vec4 PSParam0;'+
'varying vec4 COLOR0;'+
'varying vec4 TEX0;'+
'void main() {'+
' if (PSParam0.x == 0.0)'+
' gl_FragColor = COLOR0;'+
' if (PSParam0.x == 1.0)'+
' gl_FragColor = texture2D(texture0, TEX0.xy);'+
' if (PSParam0.x == 2.0)'+
' gl_FragColor = COLOR0 * texture2D(texture0, TEX0.xy);'+
' gl_FragColor *= PSParam0.y;'+
'}';
procedure TContext3D.CreateDefaultShaders;
begin
FDefaultVS_NoLight := CreateVertexShader(@DX9VS2BIN_NoLight, ARBVP1_NoLight, GLES_GLSLV_NoLight);
FDefaultVS_1Light := CreateVertexShader(@DX9VS2BIN_1Light, ARBVP1_1Light, GLES_GLSLV_1Light);
FDefaultVS_2Light := CreateVertexShader(@DX9VS2BIN_2Light, ARBVP1_2Light, GLES_GLSLV_2Light);
FDefaultVS_3Light := CreateVertexShader(@DX9VS2BIN_3Light, ARBVP1_3Light, GLES_GLSLV_3Light);
FDefaultVS_4Light := CreateVertexShader(@DX9VS2BIN_4Light, ARBVP1_4Light, GLES_GLSLV_4Light);
FDefaultVS_Full := CreateVertexShader(@DX9VS2BIN_Full, ARBVP1_Full, GLES_GLSLV_Full);
FDefaultPS := CreatePixelShader(@DX9PS2BIN, ARBFP1, GLES_GLSLF);
end;
procedure TContext3D.FreeDefaultShaders;
begin
DestroyPixelShader(FDefaultPS);
DestroyVertexShader(FDefaultVS_NoLight);
DestroyVertexShader(FDefaultVS_1Light);
DestroyVertexShader(FDefaultVS_2Light);
DestroyVertexShader(FDefaultVS_3Light);
DestroyVertexShader(FDefaultVS_4Light);
DestroyVertexShader(FDefaultVS_Full);
end;
procedure TContext3D.SetParams;
type
TOptions = packed record
Lighting: Single;
ColoredVertices: Single;
z, w: Single;
end;
TLightOpts = packed record
Enabled: Single;
Kind: Single;
SpotCosCutoff: Single;
SpotExponent: Single;
end;
TPixelOpts = packed record
Modulation: Single;
Opacity: Single;
z, w: Single;
end;
var
MVP, ModelView: TMatrix3D;
Options: TOptions;
LightOpts: TLightOpts;
PixelOpts: TPixelOpts;
I, CLight: integer;
begin
// vertex shader
if (FCurrentVS = FDefaultVS_NoLight) or (FCurrentVS = FDefaultVS_1Light) or (FCurrentVS = FDefaultVS_2Light) or
(FCurrentVS = FDefaultVS_3Light) or (FCurrentVS = FDefaultVS_4Light) or (FCurrentVS = FDefaultVS_Full) then
begin
// matrix
ModelView := FCurrentMatrix;
if FCurrentStates[TContextState.cs3DScene] then
MVP := Matrix3DMultiply(CurrentCameraMatrix, CurrentPojectionMatrix)
else
MVP := CurrentScreenMatrix;
MVP := Matrix3DMultiply(ModelView, MVP);
// MVP
SetVertexShaderMatrix(0, MVP);
// ModelView
SetVertexShaderMatrix(4, ModelView);
InvertMatrix(ModelView);
TransposeMatrix3D(ModelView);
// ModelView inverse transpose
SetVertexShaderMatrix(8, ModelView);
// Options
if FCurrentStates[TContextState.csLightOn] then
Options.Lighting := 1;
if FCurrentStates[TContextState.csLightOff] then
Options.Lighting := 0;
if FCurrentColoredVertices then
Options.ColoredVertices := 1
else
Options.ColoredVertices := 0;
Options.z := 0;
Options.w := 0;
SetVertexShaderVector(12, TVector3D(Options));
SetVertexShaderVector(13, Vector3D(0, 0, 0, 0));
// material
SetVertexShaderVector(14, ColorToVector3D(FCurrentDiffuse));
SetVertexShaderVector(15, ColorToVector3D(FCurrentSpecular));
SetVertexShaderVector(16, ColorToVector3D(FCurrentAmbient));
SetVertexShaderVector(17, ColorToVector3D(FCurrentEmissive));
SetVertexShaderVector(18, Vector3D(FCurrentShininess, 0, 0, 0)); // x - shininess
// lights
if FCurrentStates[TContextState.csLightOn] then
begin
CLight := 0;
for i := 0 to Min(MaxLights, FLights.Count) - 1 do
if TLight(FLights[i]).Enabled then
with TLight(FLights[i]) do
begin
LightOpts.Enabled := 1;
LightOpts.Kind := Integer(LightType);
LightOpts.SpotCosCutoff := cos(DegToRad(SpotCutoff));
LightOpts.SpotExponent := SpotExponent;
SetVertexShaderVector(19 + (CLight * 7), TVector3D(LightOpts)); // options
SetVertexShaderVector(20 + (CLight * 7), Vector3D(ConstantAttenuation, LinearAttenuation, QuadraticAttenuation, 0)); // attn
SetVertexShaderVector(21 + (CLight * 7), AbsolutePosition); // pos
SetVertexShaderVector(22 + (CLight * 7), AbsoluteDirection); // dir
SetVertexShaderVector(23 + (CLight * 7), ColorToVector3D(Diffuse)); // diffuse color
SetVertexShaderVector(24 + (CLight * 7), ColorToVector3D(Specular)); // specular color
SetVertexShaderVector(25 + (CLight * 7), ColorToVector3D(Ambient)); // ambient color
Inc(CLight);
end;
if CLight < MaxLights then
for i := CLight to MaxLights - 1 do
SetVertexShaderVector(19 + (i * 7), Vector3D(0, 0, 0, 0)); // disable
end;
end;
// pixel shader
if FCurrentPS = FDefaultPS then
begin
// modulation, opacity
if FCurrentStates[TContextState.csTexDisable] then
PixelOpts.Modulation := 0;
if FCurrentStates[TContextState.csTexReplace] then
PixelOpts.Modulation := 1;
if FCurrentStates[TContextState.csTexModulate] then
PixelOpts.Modulation := 2;
PixelOpts.Opacity := FCurrentOpacity;
PixelOpts.z := 0;
PixelOpts.w := 0;
SetPixelShaderVector(0, TVector3D(PixelOpts));
end;
end;
function TContext3D.DoBeginScene: Boolean;
var
I, LCount: Integer;
begin
Result := True;
Fillchar(FCurrentStates, SizeOf(FCurrentStates), 0);
// apply default shaders
FCurrentColoredVertices := False;
FCurrentOpacity := 1;
FCurrentShininess := 30;
// set default shaders
LCount := 0;
for I := 0 to FLights.Count - 1 do
if TLight(FLights[i]).Enabled then
LCount := LCount + 1;
case LCount of
0: SetVertexShader(FDefaultVS_NoLight);
1: SetVertexShader(FDefaultVS_1Light);
2: SetVertexShader(FDefaultVS_2Light);
3: SetVertexShader(FDefaultVS_3Light);
4: SetVertexShader(FDefaultVS_4Light);
else
SetVertexShader(FDefaultVS_Full);
end;
SetPixelShader(FDefaultPS);
end;
procedure TContext3D.ResetScene;
begin
SetContextState(TContextState.csGouraud);
SetContextState(TContextState.cs3DScene);
SetContextState(TContextState.csZTestOn);
SetContextState(TContextState.csZWriteOn);
SetContextState(TContextState.csFrontFace);
SetContextState(TContextState.csAlphaBlendOn);
SetContextState(TContextState.csAlphaTestOn);
SetColor(TMaterialColor.mcAmbient, DefaultAmbient);
SetColor(TMaterialColor.mcDiffuse, DefaultDiffuse);
SetColor(TMaterialColor.mcSpecular, DefaultSpecular);
SetColor(TMaterialColor.mcEmissive, 0);
end;
procedure TContext3D.DoEndScene(const CopyTarget: Boolean = True);
begin
end;
procedure TContext3D.AssignTo(Dest: TPersistent);
begin
if Dest is TBitmap then
AssignToBitmap(TBitmap(Dest))
else
inherited;
end;
function TContext3D.BeginScene: Boolean;
begin
if FBeginSceneCount = 0 then
Result := DoBeginScene
else
Result := FBeginSceneCount > 0;
if Result then
inc(FBeginSceneCount);
end;
procedure TContext3D.EndScene(const CopyTarget: Boolean);
begin
if FBeginSceneCount = 1 then
DoEndScene(CopyTarget);
if FBeginSceneCount > 0 then
dec(FBeginSceneCount);
end;
procedure TContext3D.SetMaterial(const AMaterial: TMaterial);
begin
SetColor(TMaterialColor.mcDiffuse, AMaterial.Diffuse);
SetColor(TMaterialColor.mcAmbient, AMaterial.Ambient);
SetColor(TMaterialColor.mcSpecular, AMaterial.Specular);
SetColor(TMaterialColor.mcEmissive, AMaterial.Emissive);
FCurrentShininess := AMaterial.Shininess;
if (AMaterial.Texture.ResourceBitmap <> nil) then
begin
SetTextureUnit(0, AMaterial.Texture.ResourceBitmap);
if AMaterial.Modulation = TTextureMode.tmReplace then
SetContextState(TContextState.csTexReplace)
else
SetContextState(TContextState.csTexModulate);
if AMaterial.TextureFiltering = TTextureFiltering.tfNearest then
SetContextState(TContextState.csTexNearest)
else
SetContextState(TContextState.csTexLinear);
end
else
if (not AMaterial.Texture.IsEmpty) then
begin
SetTextureUnit(0, AMaterial.Texture);
if AMaterial.Modulation = TTextureMode.tmReplace then
SetContextState(TContextState.csTexReplace)
else
SetContextState(TContextState.csTexModulate);
if AMaterial.TextureFiltering = TTextureFiltering.tfNearest then
SetContextState(TContextState.csTexNearest)
else
SetContextState(TContextState.csTexLinear);
end
else
begin
SetTextureUnit(0, nil);
SetTextureMatrix(0, IdentityMatrix);
SetContextState(TContextState.csTexDisable);
end;
if AMaterial.ShadeMode = TShadeMode.smFlat then
SetContextState(TContextState.csFlat)
else
SetContextState(TContextState.csGouraud);
if AMaterial.FillMode = TFillMode.fmSolid then
SetContextState(TContextState.csSolid)
else
SetContextState(TContextState.csFrame);
if AMaterial.Lighting then
SetContextState(TContextState.csLightOn)
else
SetContextState(TContextState.csLightOff);
end;
procedure TContext3D.SetCamera(const Camera: TCamera);
begin
FCurrentCamera := Camera;
if (FCurrentCamera = nil) then Exit;
{ if (FCurrentCamera.Target <> nil) then
begin
FCurrentCameraMatrix := MatrixLookAtDirRH(Camera.AbsoluteMatrix.M[3],
Vector3DSubtract(Camera.Target.AbsolutePosition, Camera.AbsolutePosition), Camera.AbsoluteMatrix.M[2]);
end
else}
FCurrentCameraMatrix := MatrixLookAtDirRH(Camera.AbsolutePosition, Vector3DScale(Camera.AbsoluteDirection, -1),
Vector3DScale(Camera.AbsoluteUp, -1));
FCurrentCameraInvMatrix := FCurrentCameraMatrix;
InvertMatrix(FCurrentCameraInvMatrix);
end;
procedure TContext3D.SetColor(const AMaterialColor: TMaterialColor; AColor: TAlphaColor);
begin
if AMaterialColor = TMaterialColor.mcSpecular then
FCurrentSpecular := AColor;
if AMaterialColor = TMaterialColor.mcDiffuse then
FCurrentDiffuse := AColor;
if AMaterialColor = TMaterialColor.mcAmbient then
FCurrentAmbient := AColor;
if AMaterialColor = TMaterialColor.mcEmissive then
FCurrentEmissive := AColor;
end;
procedure TContext3D.SetContextState(const State: TContextState);
begin
if not FCurrentStates[State] then
begin
FCurrentStates[State] := True;
case State of
TContextState.cs2DScene:
FCurrentStates[TContextState.cs3DScene] := False;
TContextState.cs3DScene:
FCurrentStates[TContextState.cs2DScene] := False;
TContextState.csLightOn:
FCurrentStates[TContextState.csLightOff] := False;
TContextState.csLightOff:
FCurrentStates[TContextState.csLightOn] := False;
TContextState.csZTestOn:
FCurrentStates[TContextState.csZTestOff] := False;
TContextState.csZTestOff:
FCurrentStates[TContextState.csZTestOn] := False;
TContextState.csZWriteOn:
FCurrentStates[TContextState.csZWriteOff] := False;
TContextState.csZWriteOff:
FCurrentStates[TContextState.csZWriteOn] := False;
TContextState.csAlphaTestOn:
FCurrentStates[TContextState.csAlphaTestOff] := False;
TContextState.csAlphaTestOff:
FCurrentStates[TContextState.csAlphaTestOn] := False;
TContextState.csAlphaBlendOn:
FCurrentStates[TContextState.csAlphaBlendOff] := False;
TContextState.csAlphaBlendOff:
FCurrentStates[TContextState.csAlphaBlendOn] := False;
TContextState.csStencilOn:
FCurrentStates[TContextState.csStencilOff] := False;
TContextState.csStencilOff:
FCurrentStates[TContextState.csStencilOn] := False;
TContextState.csColorWriteOn:
FCurrentStates[TContextState.csColorWriteOff] := False;
TContextState.csColorWriteOff:
FCurrentStates[TContextState.csColorWriteOn] := False;
TContextState.csFrontFace:
begin
FCurrentStates[TContextState.csBackFace] := False;
FCurrentStates[TContextState.csAllFace] := False;
end;
TContextState.csBackFace:
begin
FCurrentStates[TContextState.csAllFace] := False;
FCurrentStates[TContextState.csFrontFace] := False;
end;
TContextState.csAllFace:
begin
FCurrentStates[TContextState.csBackFace] := False;
FCurrentStates[TContextState.csFrontFace] := False;
end;
{ Blending }
TContextState.csBlendAdditive:
FCurrentStates[TContextState.csBlendNormal] := False;
TContextState.csBlendNormal:
FCurrentStates[TContextState.csBlendAdditive] := False;
{ Tex stretch }
TContextState.csTexNearest:
FCurrentStates[TContextState.csTexLinear] := False;
TContextState.csTexLinear:
FCurrentStates[TContextState.csTexNearest] := False;
{ Tex modulation }
TContextState.csTexDisable:
begin
FCurrentStates[TContextState.csTexModulate] := False;
FCurrentStates[TContextState.csTexReplace] := False;
end;
TContextState.csTexReplace:
begin
FCurrentStates[TContextState.csTexModulate] := False;
FCurrentStates[TContextState.csTexDisable] := False;
end;
TContextState.csTexModulate:
begin
FCurrentStates[TContextState.csTexDisable] := False;
FCurrentStates[TContextState.csTexReplace] := False;
end;
{ Fill }
TContextState.csFrame:
FCurrentStates[TContextState.csSolid] := False;
TContextState.csSolid:
FCurrentStates[TContextState.csFrame] := False;
{ Shade }
TContextState.csFlat:
FCurrentStates[TContextState.csGouraud] := False;
TContextState.csGouraud:
FCurrentStates[TContextState.csFlat] := False;
end;
ApplyContextState(State);
end;
end;
procedure TContext3D.SetSize(const AWidth, AHeight: Integer);
begin
if (FWidth <> AWidth) or (FHeight <> AHeight) then
begin
FreeBuffer;
FWidth := AWidth;
FHeight := AHeight;
if FWidth < 1 then FWidth := 1;
if FHeight < 1 then FHeight := 1;
Resize;
// clear matrix state
FCurrentStates[TContextState.cs2DScene] := False;
FCurrentStates[TContextState.cs3DScene] := False;
//
CreateBuffer;
end;
end;
procedure TContext3D.SetMultisample(const Multisample: TMultisample);
begin
if FMultisample <> Multisample then
begin
FreeBuffer;
FMultisample := Multisample;
CreateBuffer;
end;
end;
procedure TContext3D.SetMatrix(const M: TMatrix3D);
begin
FCurrentMatrix := M;
end;
procedure TContext3D.Pick(X, Y: Single; const AProj: TProjection; var RayPos, RayDir: TVector3D);
var
matProj: TMatrix3D;
vPos, vNear: TVector3D;
begin
if AProj = TProjection.pjCamera then
begin
{ camera }
matProj := GetProjectionMatrix;
// Compute the vector of the pick ray in screen space
vPos := Vector3D(0, 0, 0);
vNear := Vector3D((1.0 - (2.0 * (X / FWidth))) / matProj.m11, -(1.0 - (2.0 * (Y / FHeight))) / matProj.m22, 1);
// Get the inverse view matrix
if FCurrentCamera <> nil then
begin
// Transform the screen space pick ray into 3D space
vPos := Vector3DTransform(vPos, FCurrentCameraInvMatrix);
vNear := Vector3DTransform(vNear, FCurrentCameraInvMatrix);
end;
RayPos := vPos;
RayDir := Vector3DNormalize(Vector3DSubtract(vPos, vNear));
end
else
begin
{ screen }
matProj := GetScreenMatrix;
InvertMatrix(matProj);
vPos := Vector3D(0, 0, 0);
vPos := Vector3DTransform(vPos, matProj);
// Old behavior
vPos := Vector3D(FWidth / 2, FHeight / 2, vPos.Z * 2);
vNear := Vector3D(X, Y, 0);
RayPos := vPos;
RayDir := Vector3DNormalize(Vector3DSubtract(vNear, vPos));
end;
end;
function TContext3D.WorldToScreen(const AProj: TProjection; const P: TPoint3D): TPoint3D;
var
matProj: TMatrix3D;
begin
if AProj = TProjection.pjCamera then
begin
{ camera }
matProj := FCurrentCameraMatrix;
Result := Point3D(Vector3DTransform(Vector3D(P), matProj));
matProj := GetProjectionMatrix;
if Result.Z <> 0 then
begin
Result.X := -((Result.X / Result.Z) * matProj.m11 - 1) * FWidth / 2;
Result.Y := ((Result.Y / Result.Z) * matProj.m22 + 1) * FHeight / 2;
end;
end
else
begin
{ screen }
matProj := GetScreenMatrix;
Result := P;
end;
end;
procedure TContext3D.DrawCube(const Center, Size: TVector3D; const Opacity: Single);
var
i: Integer;
a, b: TVector3D;
Pts: array [0 .. 24] of TVector3D;
begin
a := Vector3DAdd(Center, Vector3DScale(Size, -0.5));
b := Vector3DAdd(Center, Vector3DScale(Size, 0.5));
begin
Pts[0] := Vector3D(a.X, a.Y, b.Z);
Pts[1] := Vector3D(b.X, a.Y, b.Z);
Pts[2] := Vector3D(a.X, a.Y, a.Z);
Pts[3] := Vector3D(b.X, a.Y, a.Z);
Pts[4] := Vector3D(a.X, b.Y, b.Z);
Pts[5] := Vector3D(b.X, b.Y, b.Z);
Pts[6] := Vector3D(a.X, b.Y, a.Z);
Pts[7] := Vector3D(b.X, b.Y, a.Z);
Pts[8] := Vector3D(a.X, a.Y, a.Z);
Pts[9] := Vector3D(a.X, b.Y, a.Z);
Pts[10] := Vector3D(a.X, a.Y, b.Z);
Pts[11] := Vector3D(a.X, b.Y, b.Z);
Pts[12] := Vector3D(b.X, a.Y, a.Z);
Pts[13] := Vector3D(b.X, b.Y, a.Z);
Pts[14] := Vector3D(b.X, a.Y, b.Z);
Pts[15] := Vector3D(b.X, b.Y, b.Z);
Pts[16] := Vector3D(a.X, a.Y, a.Z);
Pts[17] := Vector3D(a.X, a.Y, b.Z);
Pts[18] := Vector3D(b.X, a.Y, a.Z);
Pts[19] := Vector3D(b.X, a.Y, b.Z);
Pts[20] := Vector3D(a.X, b.Y, a.Z);
Pts[21] := Vector3D(a.X, b.Y, b.Z);
Pts[22] := Vector3D(b.X, b.Y, a.Z);
Pts[23] := Vector3D(b.X, b.Y, b.Z);
end;
for i := 0 to 11 do
DrawLine(Pts[i * 2], Pts[i * 2 + 1], Opacity);
end;
procedure TContext3D.DrawLine(const StartPoint, EndPoint: TVector3D;
const Opacity: Single);
var
Ver: TVertexBuffer;
Idx: TIndexBuffer;
begin
Ver := TVertexBuffer.Create([TVertexFormat.vfVertex], 2);
Ver.Vertices[0] := Point3D(StartPoint);
Ver.Vertices[1] := Point3D(EndPoint);
Idx := TIndexBuffer.Create(2);
Idx[0] := 0;
Idx[1] := 1;
DrawLinesList(Ver, Idx, Opacity);
Idx.Free;
Ver.Free;
end;
procedure TContext3D.FillCube(const Center, Size: TVector3D; const Opacity: Single);
var
Ver: TVertexBuffer;
Idx: TIndexBuffer;
tx1, ty1, tx2, ty2: Single;
a, b, n: TVector3D;
i: Integer;
begin
a := Vector3DAdd(Center, Vector3DScale(Size, -0.5));
b := Vector3DAdd(Center, Vector3DScale(Size, 0.5));
tx1 := 0;
ty1 := 0;
tx2 := 1;
ty2 := 1;
{ front }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(a.X, a.Y, b.Z), Vector3D(b.X, a.Y, b.Z)),
Vector3DSubtract(Vector3D(a.X, a.Y, b.Z), Vector3D(b.X, a.Y, a.Z)));
n := Vector3DScale(n, -1);
Ver := TVertexBuffer.Create([TVertexFormat.vfVertex, TVertexFormat.vfNormal, TVertexFormat.vfTexCoord0], 24);
Ver.Vertices[0] := Point3D(a.X, a.Y, b.Z); Ver.Normals[0] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[0] := PointF(tx1, ty1);
Ver.Vertices[1] := Point3D(b.X, a.Y, b.Z); Ver.Normals[1] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[1] := PointF(tx2, ty1);
Ver.Vertices[2] := Point3D(b.X, a.Y, a.Z); Ver.Normals[2] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[2] := PointF(tx2, ty2);
Ver.Vertices[3] := Point3D(a.X, a.Y, a.Z); Ver.Normals[3] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[3] := PointF(tx1, ty2);
{ right }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(b.X, a.Y, b.Z), Vector3D(b.X, b.Y, b.Z)),
Vector3DSubtract(Vector3D(b.X, a.Y, b.Z), Vector3D(b.X, b.Y, a.Z)));
n := Vector3DScale(n, -1);
Ver.Vertices[4] := Point3D(b.X, a.Y, b.Z); Ver.Normals[4] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[4] := PointF(tx1, ty1);
Ver.Vertices[5] := Point3D(b.X, b.Y, b.Z); Ver.Normals[5] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[5] := PointF(tx2, ty1);
Ver.Vertices[6] := Point3D(b.X, b.Y, a.Z); Ver.Normals[6] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[6] := PointF(tx2, ty2);
Ver.Vertices[7] := Point3D(b.X, a.Y, a.Z); Ver.Normals[7] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[7] := PointF(tx1, ty2);
{ left }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(a.X, b.Y, b.Z), Vector3D(a.X, a.Y, b.Z)),
Vector3DSubtract(Vector3D(a.X, b.Y, b.Z), Vector3D(a.X, a.Y, a.Z)));
n := Vector3DScale(n, -1);
Ver.Vertices[8] := Point3D(a.X, b.Y, b.Z); Ver.Normals[8] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[8] := PointF(tx1, ty1);
Ver.Vertices[9] := Point3D(a.X, a.Y, b.Z); Ver.Normals[9] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[9] := PointF(tx2, ty1);
Ver.Vertices[10] := Point3D(a.X, a.Y, a.Z); Ver.Normals[10] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[10] := PointF(tx2, ty2);
Ver.Vertices[11] := Point3D(a.X, b.Y, a.Z); Ver.Normals[11] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[11] := PointF(tx1, ty2);
{ back }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(b.X, b.Y, b.Z), Vector3D(a.X, b.Y, b.Z)),
Vector3DSubtract(Vector3D(b.X, b.Y, b.Z), Vector3D(a.X, b.Y, a.Z)));
n := Vector3DScale(n, -1);
Ver.Vertices[12] := Point3D(b.X, b.Y, b.Z); Ver.Normals[12] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[12] := PointF(tx1, ty1);
Ver.Vertices[13] := Point3D(a.X, b.Y, b.Z); Ver.Normals[13] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[13] := PointF(tx2, ty1);
Ver.Vertices[14] := Point3D(a.X, b.Y, a.Z); Ver.Normals[14] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[14] := PointF(tx2, ty2);
Ver.Vertices[15] := Point3D(b.X, b.Y, a.Z); Ver.Normals[15] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[15] := PointF(tx1, ty2);
{ top }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(a.X, b.Y, b.Z), Vector3D(b.X, b.Y, b.Z)),
Vector3DSubtract(Vector3D(a.X, b.Y, b.Z), Vector3D(b.X, a.Y, b.Z)));
n := Vector3DScale(n, -1);
Ver.Vertices[16] := Point3D(a.X, b.Y, b.Z); Ver.Normals[16] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[16] := PointF(tx1, ty1);
Ver.Vertices[17] := Point3D(b.X, b.Y, b.Z); Ver.Normals[17] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[17] := PointF(tx2, ty1);
Ver.Vertices[18] := Point3D(b.X, a.Y, b.Z); Ver.Normals[18] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[18] := PointF(tx2, ty2);
Ver.Vertices[19] := Point3D(a.X, a.Y, b.Z); Ver.Normals[19] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[19] := PointF(tx1, ty2);
{ bottom }
n := Vector3DCrossProduct(Vector3DSubtract(Vector3D(a.X, a.Y, a.Z), Vector3D(b.X, a.Y, a.Z)),
Vector3DSubtract(Vector3D(a.X, a.Y, a.Z), Vector3D(b.X, b.Y, a.Z)));
n := Vector3DScale(n, -1);
Ver.Vertices[20] := Point3D(a.X, a.Y, a.Z); Ver.Normals[20] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[20] := PointF(tx1, ty1);
Ver.Vertices[21] := Point3D(b.X, a.Y, a.Z); Ver.Normals[21] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[21] := PointF(tx2, ty1);
Ver.Vertices[22] := Point3D(b.X, b.Y, a.Z); Ver.Normals[22] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[22] := PointF(tx2, ty2);
Ver.Vertices[23] := Point3D(a.X, b.Y, a.Z); Ver.Normals[23] := Point3D(n.X, n.Y, n.Z); Ver.TexCoord0[23] := PointF(tx1, ty2);
{ indexs }
Idx := TIndexBuffer.Create(36);
for i := 0 to 5 do
begin
Idx[i * 6 + 0] := (i * 4) + 0;
Idx[i * 6 + 1] := (i * 4) + 1;
Idx[i * 6 + 2] := (i * 4) + 3;
Idx[i * 6 + 3] := (i * 4) + 3;
Idx[i * 6 + 4] := (i * 4) + 1;
Idx[i * 6 + 5] := (i * 4) + 2;
end;
DrawTrianglesList(Ver, Idx, Opacity);
Idx.Free;
Ver.Free;
end;
procedure TContext3D.FillMesh(const Center, Size: TVector3D; const MeshData: TMeshData; const Opacity: Single);
var
SaveMatrix, M: TMatrix3D;
begin
if MeshData.VertexBuffer.Size = 0 then
Exit;
if MeshData.IndexBuffer.Size = 0 then
Exit;
M := Matrix3DMultiply(CreateScaleMatrix3D(Size), CreateTranslateMatrix3D(Vector3D(Center.X, Center.Y, Center.Z)));
SaveMatrix := FCurrentMatrix;
FCurrentMatrix := Matrix3DMultiply(M, FCurrentMatrix);
DrawTrianglesList(MeshData.FVertexBuffer, MeshData.IndexBuffer, Opacity);
SetMatrix(SaveMatrix);
end;
procedure TContext3D.FillRect(const Rect: TRectF; const Depth, Opacity: Single);
var
P: TPolygon;
begin
SetLength(P, 5);
P[0] := Rect.TopLeft;
P[1] := PointF(Rect.Right, Rect.Top);
P[2] := Rect.BottomRight;
P[3] := PointF(Rect.Left, Rect.Bottom);
P[4] := Rect.TopLeft;
FillPolygon(Vector3D((Rect.Left + Rect.Right) / 2, (Rect.Top + Rect.Bottom) / 2, 0),
Vector3D(RectWidth(Rect), RectHeight(Rect), Depth), Rect, P, Opacity);
end;
procedure TContext3D.FillPolygon(const Center, Size: TVector3D; const Rect: TRectF;
const Points: TPolygon; const Opacity: Single; Front: Boolean = True; Back: Boolean = True;
Left: Boolean = True);
var
Ver: TVertexBuffer;
Idx: TIndexBuffer;
MeshData: TMeshData;
a, b: TVector3D;
C: TAlphaColor;
i, j: Integer;
//Flags: cardinal;
startIndex: Integer;
leftLen, curPos: Single;
begin
if Length(Points) = 0 then
Exit;
{ calc bounds }
a := Vector3D($FFFF, $FFFF, 0);
b := Vector3D(-$FFFF, -$FFFF, 0);
leftLen := 0;
for i := 0 to High(Points) do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
continue;
with Points[i] do
begin
if X < a.X then
a.X := X;
if Y < a.Y then
a.Y := Y;
if X > b.X then
b.X := X;
if Y > b.Y then
b.Y := Y;
if Left and (i > 0) then
begin
if Points[i - 1].X >= $FFFF then
begin
leftLen := leftLen + VectorLength(Vector(X - Points[i - 2].X, Y - Points[i - 2].Y));
end
else
begin
leftLen := leftLen + VectorLength(Vector(X - Points[i - 1].X, Y - Points[i - 1].Y));
end;
end;
end;
end;
if not IsRectEmpty(Rect) then
begin
if Rect.Left < a.X then
a.X := Rect.Left;
if Rect.Top < a.Y then
a.Y := Rect.Top;
if Rect.Right > b.X then
b.X := Rect.Right;
if Rect.Bottom > b.Y then
b.Y := Rect.Bottom;
end;
Ver := TVertexBuffer.Create([TVertexFormat.vfVertex, TVertexFormat.vfNormal, TVertexFormat.vfTexCoord0], 0);
Idx := TIndexBuffer.Create(0);
{ Front face }
if Front then
begin
Ver.Length := Length(Points);
{ set vertices }
for i := 0 to High(Points) do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
continue;
with Point3D((Points[i].X - a.X) / Abs(b.X - a.X), (Points[i].Y - a.Y) / Abs(b.Y - a.Y), 1) do
Ver.Vertices[i] := Point3D(Center.X - (Size.X / 2) + (X * Size.X),
Center.Y - (Size.Y / 2) + (Y * Size.Y), Center.Z - (Size.Z / 2) + (Z * Size.Z));
Ver.Normals[i] := Point3D(0, 0, 1);
Ver.TexCoord0[i] := PointF(0.02 + (X * 0.96), 0.02 + (Y * 0.96));
end;
{ Set indices }
Idx.Length := High(Points) * 3;
startIndex := 0;
j := 0;
for i := 0 to High(Points) - 1 do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
begin
startIndex := i + 1;
continue;
end;
Idx[(j * 3) + 0] := startIndex;
Idx[(j * 3) + 1] := i + 1;
Idx[(j * 3) + 2] := i;
Inc(j);
end;
Idx.Length := (j - 1) * 3;
{ write to stencil }
SetContextState(TContextState.csStencilOn);
Clear([TClearTarget.ctStencil], 0, 0, 0);
SetContextState(TContextState.csColorWriteOff);
SetContextState(TContextState.csZWriteOff);
SetStencilFunc(TStencilFunc.sfAlways, 0, $FF);
SetStencilOp(TStencilOp.soKeep, TStencilOp.soKeep, TStencilOp.soInvert);
SetContextState(TContextState.csAllFace);
DrawTrianglesList(Ver, Idx, 1);
SetContextState(TContextState.csZWriteOn);
SetContextState(TContextState.csColorWriteOn);
{ just paint rect using stencil }
Ver.Length := 4;
Ver.Vertices[0] := Point3D(Center.X - (Size.X / 2), Center.Y - (Size.Y / 2), Center.Z + (Size.Z / 2));
Ver.Normals[0] := Point3D(0, 0, 1);
Ver.TexCoord0[0] := PointF(0, 0);
Ver.Vertices[1] := Point3D(Center.X + (Size.X / 2), Center.Y - (Size.Y / 2), Center.Z + (Size.Z / 2));
Ver.Normals[1] := Point3D(0, 0, 1);
Ver.TexCoord0[1] := PointF(1, 0);
Ver.Vertices[2] := Point3D(Center.X + (Size.X / 2), Center.Y + (Size.Y / 2), Center.Z + (Size.Z / 2));
Ver.Normals[2] := Point3D(0, 0, 1);
Ver.TexCoord0[2] := PointF(1, 1);
Ver.Vertices[3] := Point3D(Center.X - (Size.X / 2), Center.Y + (Size.Y / 2), Center.Z + (Size.Z / 2));
Ver.Normals[3] := Point3D(0, 0, 1);
Ver.TexCoord0[3] := PointF(0, 1);
{ indexs }
Idx.Length := 6;
Idx[0] := 0;
Idx[1] := 3;
Idx[2] := 1;
Idx[3] := 1;
Idx[4] := 3;
Idx[5] := 2;
SetStencilFunc(TStencilFunc.sfNotEqual, 0, $FF);
SetStencilOp(TStencilOp.soKeep, TStencilOp.soKeep, TStencilOp.soKeep);
SetContextState(TContextState.csFrontFace);
DrawTrianglesList(Ver, Idx, Opacity);
SetContextState(TContextState.csStencilOff);
end;
{ Back Face }
if Back then
begin
Ver.Length := Length(Points);
{ set vertices }
for i := 0 to High(Points) do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
continue;
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
continue;
with Point3D((Points[i].X - a.X) / Abs(b.X - a.X), (Points[i].Y - a.Y) / Abs(b.Y - a.Y), 0) do
Ver.Vertices[i] := Point3D(Center.X - (Size.X / 2) + (X * Size.X),
Center.Y - (Size.Y / 2) + (Y * Size.Y), Center.Z - (Size.Z / 2) + (Z * Size.Z));
Ver.Normals[i] := Point3D(0, 0, -1);
Ver.TexCoord0[i] := PointF(0.02 + (X * 0.96), 0.02 + (Y * 0.96));
end;
{ Set indices }
Idx.Length := (High(Points)) * 3;
startIndex := 0;
j := 0;
for i := 0 to High(Points) - 1 do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
begin
startIndex := i + 1;
continue;
end;
Idx[(j * 3) + 0] := startIndex;
Idx[(j * 3) + 1] := i + 1;
Idx[(j * 3) + 2] := i;
Inc(j);
end;
Idx.Length := (j - 1) * 3;
{ write to stencil }
SetContextState(TContextState.csStencilOn);
Clear([TClearTarget.ctStencil], 0, 0, 0);
SetContextState(TContextState.csColorWriteOff);
SetContextState(TContextState.csZWriteOff);
SetStencilFunc(TStencilFunc.sfAlways, 0, $FF);
SetStencilOp(TStencilOp.soKeep, TStencilOp.soKeep, TStencilOp.soInvert);
SetContextState(TContextState.csAllFace);
DrawTrianglesList(Ver, Idx, 1);
SetContextState(TContextState.csZWriteOn);
SetContextState(TContextState.csColorWriteOn);
{ just paint rect using stencil }
Ver.Length := 4;
Ver.Vertices[0] := Point3D(Center.X - (Size.X / 2), Center.Y - (Size.Y / 2), Center.Z - (Size.Z / 2));
Ver.Normals[0] := Point3D(0, 0, -1);
Ver.TexCoord0[0] := PointF(0, 0);
Ver.Vertices[1] := Point3D(Center.X + (Size.X / 2), Center.Y - (Size.Y / 2), Center.Z - (Size.Z / 2));
Ver.Normals[1] := Point3D(0, 0, -1);
Ver.TexCoord0[1] := PointF(1, 0);
Ver.Vertices[2] := Point3D(Center.X + (Size.X / 2), Center.Y + (Size.Y / 2), Center.Z - (Size.Z / 2));
Ver.Normals[2] := Point3D(0, 0, -1);
Ver.TexCoord0[2] := PointF(1, 1);
Ver.Vertices[3] := Point3D(Center.X - (Size.X / 2), Center.Y + (Size.Y / 2), Center.Z - (Size.Z / 2));
Ver.Normals[3] := Point3D(0, 0, -1);
Ver.TexCoord0[3] := PointF(0, 1);
{ indexs }
Idx.Length := 6;
Idx[0] := 0;
Idx[1] := 1;
Idx[2] := 3;
Idx[3] := 1;
Idx[4] := 2;
Idx[5] := 3;
SetStencilFunc(TStencilFunc.sfNotEqual, 0, $FF);
SetStencilOp(TStencilOp.soKeep, TStencilOp.soKeep, TStencilOp.soKeep);
SetContextState(TContextState.csFrontFace);
DrawTrianglesList(Ver, Idx, Opacity);
SetContextState(TContextState.csStencilOff);
end;
{ sides }
if Left and (leftLen > 0) then
begin
Ver.Length := Length(Points) * 2;
{ set vertices }
curPos := 0;
for i := 0 to High(Points) do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
continue;
if (i > 0) then
begin
if Points[i - 1].X >= $FFFF then
curPos := curPos + VectorLength(Vector(Points[i].X - Points[i - 2].X,
Points[i].Y - Points[i - 2].Y))
else
curPos := curPos + VectorLength(Vector(Points[i].X - Points[i - 1].X,
Points[i].Y - Points[i - 1].Y));
end;
with Point3D((Points[i].X - a.X) / Abs(b.X - a.X), ((Points[i].Y - a.Y) / Abs(b.Y - a.Y)), 1) do
Ver.Vertices[i] := Point3D(Center.X - (Size.X / 2) + (X * Size.X),
Center.Y - (Size.Y / 2) + (Y * Size.Y), Center.Z - (Size.Z / 2) + Z * Size.Z);
Ver.TexCoord0[i] := PointF(0, curPos / leftLen);
with Point3D((Points[i].X - a.X) / Abs(b.X - a.X), ((Points[i].Y - a.Y) / Abs(b.Y - a.Y)), 0) do
Ver.Vertices[Length(Points) + i] := Point3D(Center.X - (Size.X / 2) + (X * Size.X),
Center.Y - (Size.Y / 2) + (Y * Size.Y), Center.Z - (Size.Z / 2) + Z * Size.Z);
Ver.TexCoord0[Length(Points) + i] := PointF(1, curPos / leftLen);
end;
{ set indices }
Idx.Length := (High(Points)) * 6;
j := 0;
for i := 0 to High(Points) - 1 do
begin
if (Points[i].X >= $FFFF) and (Points[i].Y >= $FFFF) then
begin
continue;
end;
if (Points[i + 1].X >= $FFFF) and (Points[i + 1].X >= $FFFF) then
begin
continue;
end;
Idx[(j * 6) + 0] := i;
Idx[(j * 6) + 2] := Length(Points) + i;
Idx[(j * 6) + 1] := Length(Points) + i + 1;
Idx[(j * 6) + 3] := Length(Points) + i + 1;
Idx[(j * 6) + 5] := i + 1;
Idx[(j * 6) + 4] := i;
Inc(j);
end;
Idx.Length := (j - 0) * 6;
{ calc normals }
MeshData := TMeshData.Create;
MeshData.VertexBuffer.Assign(Ver);
MeshData.IndexBuffer.Assign(Idx);
MeshData.CalcNormals;
Ver.Assign(MeshData.VertexBuffer);
MeshData.Free;
{ draw }
DrawTrianglesList(Ver, Idx, Opacity);
end;
{ free }
Ver.Free;
Idx.Free;
end;
{ TControl3D }
constructor TControl3D.Create(AOwner: TComponent);
begin
inherited;
FCursor := crDefault;
FShowContextMenu := True;
FCanResize := True;
FCanRotate := True;
FOpacity := 1;
FZWrite := True;
FLocalMatrix := IdentityMatrix3D;
FQuaternion := IdentityQuaternion;
FPosition := TPosition3D.Create(Point3D(0, 0, 0));
FPosition.OnChange := MatrixChanged;
FScale := TPosition3D.Create(Point3D(1, 1, 1));
FScale.OnChange := MatrixChanged;
FSkew := TPosition3D.Create(Point3D(0, 0, 0));
FSkew.OnChange := MatrixChanged;
FRotationAngle := TPosition3D.Create(Point3D(0, 0, 0));
FRotationAngle.OnChangeX := RotateXChanged;
FRotationAngle.OnChangeY := RotateYChanged;
FRotationAngle.OnChangeZ := RotateZChanged;
FRotationCenter := TPosition3D.Create(Point3D(0, 0, 0));
FRotationCenter.OnChange := MatrixChanged;
FWidth := 1;
FLastWidth := FWidth;
FHeight := 1;
FLastHeight := FHeight;
FDepth := 1;
FLastDepth := FDepth;
FVisible := True;
FHitTest := True;
FRecalcAbsolute := True;
FRecalcOpacity := True;
FDesignVisible := True;
FAcceptsControls := True;
end;
destructor TControl3D.Destroy;
begin
FAbsoluteOpacity := 0;
FVisible := False;
FRotationCenter.Free;
FRotationAngle.Free;
FScale.Free;
FSkew.Free;
FPosition.Free;
inherited;
end;
procedure TControl3D.Loaded;
begin
inherited;
MatrixChanged(Self);
end;
procedure TControl3D.AddObject(AObject: TFmxObject);
begin
inherited;
if AObject = nil then
Exit;
if (AObject is TControl3D) then
begin
TControl3D(AObject).SetNewViewport(FViewport);
if TempContext <> nil then
TControl3D(AObject).TempContext := TempContext;
TControl3D(AObject).RecalcOpacity;
TControl3D(AObject).RecalcAbsolute;
end;
end;
procedure TControl3D.RemoveObject(AObject: TFmxObject);
begin
inherited;
if (AObject is TControl3D) then
begin
TControl3D(AObject).Repaint;
TControl3D(AObject).SetNewViewport(nil);
end;
end;
procedure TControl3D.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('Quanternion', ReadQuaternion, WriteQuaternion, (FQuaternion.ImagPart.X <> 0) or
(FQuaternion.ImagPart.Y <> 0) or (FQuaternion.ImagPart.Z <> 0) or (FQuaternion.RealPart <> 0));
end;
procedure TControl3D.ReadQuaternion(Reader: TReader);
var
S: AnsiString;
begin
S := Reader.ReadString;
try
GetToken(S, ',()');
FQuaternion.ImagPart.X := StrToFloat(GetToken(S, ',()'), USFormatSettings);
FQuaternion.ImagPart.Y := StrToFloat(GetToken(S, ',()'), USFormatSettings);
FQuaternion.ImagPart.Z := StrToFloat(GetToken(S, ',()'), USFormatSettings);
FQuaternion.ImagPart.W := 0;
FQuaternion.RealPart := StrToFloat(GetToken(S, ',()'), USFormatSettings);
except
end;
end;
procedure TControl3D.WriteQuaternion(Writer: TWriter);
var
S: WideString;
begin
S := '(' + FloatToStr(FQuaternion.ImagPart.X, USFormatSettings) + ',' + FloatToStr(FQuaternion.ImagPart.Y,
USFormatSettings) + ',' + FloatToStr(FQuaternion.ImagPart.Z, USFormatSettings) + ',' +
FloatToStr(FQuaternion.RealPart, USFormatSettings) + ')';
Writer.WriteString(S);
end;
{ matrix }
procedure TControl3D.RotateXChanged(Sender: TObject);
var
q: TQuaternion3D;
a: Single;
begin
a := NormalizeAngle(RotationAngle.FX - RotationAngle.FSave.X);
if a <> 0 then
begin
q := QuaternionFromAngleAxis(a, Vector3D(1, 0, 0) { AbsoluteRight } );
FQuaternion := QuaternionMultiply(FQuaternion, q);
MatrixChanged(Sender);
RotationAngle.FX := NormalizeAngle(RotationAngle.FX);
RotationAngle.FSave.X := RotationAngle.FX;
end;
end;
procedure TControl3D.RotateYChanged(Sender: TObject);
var
q: TQuaternion3D;
a: Single;
begin
a := NormalizeAngle(RotationAngle.FY - RotationAngle.FSave.Y);
if a <> 0 then
begin
q := QuaternionFromAngleAxis(a, Vector3D(0, 1, 0) { AbsoluteDirection } );
FQuaternion := QuaternionMultiply(FQuaternion, q);
MatrixChanged(Sender);
RotationAngle.FY := NormalizeAngle(RotationAngle.FY);
RotationAngle.FSave.Y := RotationAngle.FY;
end;
end;
procedure TControl3D.RotateZChanged(Sender: TObject);
var
q: TQuaternion3D;
a: Single;
begin
a := NormalizeAngle(RotationAngle.FZ - RotationAngle.FSave.Z);
if a <> 0 then
begin
q := QuaternionFromAngleAxis(a, Vector3D(0, 0, 1) { AbsoluteUp } );
FQuaternion := QuaternionMultiply(FQuaternion, q);
MatrixChanged(Sender);
RotationAngle.FZ := NormalizeAngle(RotationAngle.FZ);
RotationAngle.FSave.Z := RotationAngle.FZ;
end;
end;
procedure TControl3D.ResetRotationAngle;
begin
FQuaternion := IdentityQuaternion;
MatrixChanged(Self);
RotationAngle.FZ := 0;
RotationAngle.FSave.Z := 0;
RotationAngle.FY := 0;
RotationAngle.FSave.Y := 0;
RotationAngle.FX := 0;
RotationAngle.FSave.X := 0;
end;
procedure TControl3D.MatrixChanged(Sender: TObject);
var
LeftVector, DirectionVector, UpVector: TVector3D;
rotMatrix: TMatrix3D;
begin
UpVector := Vector3D(0, 1, 0);
DirectionVector := Vector3D(0, 0, 1);
if (FRotationAngle.X <> 0) or (FRotationAngle.Y <> 0) or (FRotationAngle.Z <> 0) then
begin
rotMatrix := QuaternionToMatrix(FQuaternion);
UpVector := Vector3DTransform(UpVector, rotMatrix);
DirectionVector := Vector3DTransform(DirectionVector, rotMatrix);
end
else
begin
RotationAngle.FSave := Vector3D(0, 0, 0);
FQuaternion := IdentityQuaternion;
end;
LeftVector := Vector3DCrossProduct(UpVector, DirectionVector);
FLocalMatrix.M[0] := Vector3DScale(LeftVector, Scale.X);
FLocalMatrix.m14 := 0;
FLocalMatrix.M[1] := Vector3DScale(UpVector, Scale.Y);
FLocalMatrix.m24 := 0;
FLocalMatrix.M[2] := Vector3DScale(DirectionVector, Scale.Z);
FLocalMatrix.m34 := 0;
FLocalMatrix.m41 := FPosition.X;
FLocalMatrix.m42 := FPosition.Y;
FLocalMatrix.m43 := FPosition.Z;
RecalcAbsolute;
Repaint;
end;
procedure TControl3D.Resize3D;
begin
end;
function TControl3D.GetAbsoluteMatrix: TMatrix3D;
begin
if FRecalcAbsolute then
begin
if (FParent <> nil) and (FParent is TControl3D) then
FAbsoluteMatrix := Matrix3DMultiply(FLocalMatrix, TControl3D(FParent).AbsoluteMatrix)
else
FAbsoluteMatrix := FLocalMatrix;
Result := FAbsoluteMatrix;
FInvAbsoluteMatrix := FAbsoluteMatrix;
InvertMatrix(FInvAbsoluteMatrix);
FRecalcAbsolute := False;
Repaint;
end
else
begin
Result := FAbsoluteMatrix;
end;
end;
function TControl3D.GetInvertAbsoluteMatrix: TMatrix3D;
begin
AbsoluteMatrix; // require this call to force recalulation if need
Result := FInvAbsoluteMatrix;
end;
function TControl3D.GetDesignInteractive: Boolean;
begin
Result := False;
end;
function TControl3D.GetAbsoluteDirection: TVector3D;
begin
Result := AbsoluteMatrix.M[2];
end;
function TControl3D.GetAbsoluteLeft: TVector3D;
begin
Result := AbsoluteMatrix.M[0];
end;
function TControl3D.GetAbsoluteUp: TVector3D;
begin
Result := AbsoluteMatrix.M[1];
end;
function TControl3D.GetAbsolutePosition: TVector3D;
begin
Result := AbsoluteMatrix.M[3];
end;
function TControl3D.ScreenToLocal(P: TPointF): TPointF;
begin
if (FViewport <> nil) then
P := FViewport.ScreenToLocal(P);
Result := P;
end;
function TControl3D.LocalToScreen(P: TPointF): TPointF;
begin
Result := P;
if (FViewport <> nil) then
P := FViewport.LocalToScreen(P);
end;
procedure TControl3D.SetAbsolutePosition(Value: TVector3D);
begin
if (Parent <> nil) and (Parent is TControl3D) then
Position.Vector := Vector3D(AbsoluteToLocal3D(Point3D(Value)))
else
Position.Vector := Value;
end;
function TControl3D.GetLocked: Boolean;
begin
Result := FLocked;
end;
function TControl3D.GetParent: TFmxObject;
begin
Result := Parent;
end;
function TControl3D.GetScreenBounds: TRectF;
var
Pts: array [0 .. 7] of TPoint3D;
a, b: TPoint3D;
i: Integer;
begin
if Context = nil then
begin
Result := RectF(0, 0, 0, 0);
Exit;
end;
Pts[0] := Point3D(Width / 2, Height / 2, Depth / 2);
Pts[1] := Point3D(-Width / 2, Height / 2, Depth / 2);
Pts[2] := Point3D(-Width / 2, -Height / 2, Depth / 2);
Pts[3] := Point3D(-Width / 2, -Height / 2, -Depth / 2);
Pts[4] := Point3D(Width / 2, -Height / 2, Depth / 2);
Pts[5] := Point3D(Width / 2, Height / 2, -Depth / 2);
Pts[6] := Point3D(Width / 2, -Height / 2, -Depth / 2);
Pts[7] := Point3D(-Width / 2, Height / 2, -Depth / 2);
for i := 0 to High(Pts) do
Pts[i] := Context.WorldToScreen(Projection, LocalToAbsolute3D(Pts[i]));
{ normalize }
a := Point3D($FFFF, $FFFF, $FFFF);
b := Point3D(-$FFFF, -$FFFF, -$FFFF);
for i := 0 to High(Pts) do
begin
If Pts[i].X < a.X then
a.X := Pts[i].X;
If Pts[i].Y < a.Y then
a.Y := Pts[i].Y;
If Pts[i].X > b.X then
b.X := Pts[i].X;
If Pts[i].Y > b.Y then
b.Y := Pts[i].Y;
end;
Result := RectF(a.X, a.Y, b.X, b.Y);
end;
procedure TControl3D.RecalcAbsolute;
var
i: Integer;
Child: TControl3D;
begin
FRecalcAbsolute := True;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
begin
if not(Children[i] is TControl3D) then
Continue;
Child := FChildren[i];
TControl3D(Child).RecalcAbsolute;
end;
end;
function TControl3D.AbsoluteToLocalVector(P: TVector3D): TVector3D;
begin
Result := Vector3DTransform(P, InvertAbsoluteMatrix);
end;
function TControl3D.LocalToAbsoluteVector(P: TVector3D): TVector3D;
begin
Result := Vector3DTransform(P, AbsoluteMatrix);
end;
function TControl3D.AbsoluteToLocal(P: TPointF): TPointF;
begin
Result := P;
end;
function TControl3D.AbsoluteToLocal3D(P: TPoint3D): TPoint3D;
var
V: TVector3D;
begin
V := Vector3D(P.X, P.Y, P.Z);
V := Vector3DTransform(V, InvertAbsoluteMatrix);
Result := Point3D(V.X, V.Y, V.Z);
end;
function TControl3D.LocalToAbsolute3D(P: TPoint3D): TPoint3D;
var
V: TVector3D;
begin
V := Vector3D(P.X, P.Y, P.Z);
V := Vector3DTransform(V, AbsoluteMatrix);
Result := Point3D(V.X, V.Y, V.Z);
end;
{ Opacity }
function TControl3D.GetAbsoluteOpacity: Single;
begin
if FRecalcOpacity then
begin
if (FParent <> nil) and (FParent is TControl3D) then
FAbsoluteOpacity := FOpacity * TControl3D(FParent).AbsoluteOpacity
else
FAbsoluteOpacity := FOpacity;
Result := FAbsoluteOpacity;
FRecalcOpacity := False;
end
else
begin
Result := FAbsoluteOpacity;
end;
end;
procedure TControl3D.RecalcOpacity;
var
i: Integer;
Child: TControl3D;
begin
FRecalcOpacity := True;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
begin
if not(Children[i] is TControl3D) then
Continue;
Child := TControl3D(Children[i]);
TControl3D(Child).RecalcOpacity;
end;
end;
procedure TControl3D.SetLocked(const Value: Boolean);
begin
FLocked := Value;
end;
procedure TControl3D.SetNewViewport(AViewport: IViewport3D);
var
i: Integer;
begin
FViewport := AViewport;
if (FChildren <> nil) and (FChildren.Count > 0) then
for i := 0 to FChildren.Count - 1 do
if TFmxObject(FChildren[i]) is TControl3D then
TControl3D(FChildren[i]).SetNewViewport(FViewport);
end;
{ methods }
function TControl3D.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
var
INear, IFar: TVector3D;
begin
Result := RayCastCuboidIntersect(RayPos, RayDir, Vector3D(0,0,0), Width, Height, Depth, INear, IFar) > 0;
if Result then
Intersection := LocalToAbsoluteVector(INear);
end;
function TControl3D.CheckForAllowFocus: Boolean;
begin
Result := Visible and CanFocus;
end;
function TControl3D.CheckHitTest(const AHitTest: Boolean): Boolean;
begin
Result := FHitTest;
if (csDesigning in ComponentState) then
Result := True;
if (csDesigning in ComponentState) and FLocked then
Result := False;
if (csDesigning in ComponentState) and not FDesignVisible then
Result := False;
if (csDesigning in ComponentState) and FDesignLocked then
Result := False;
end;
function TControl3D.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
IP, rPos, rDir: TVector3D;
begin
Result := nil;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
Result := NewObj;
end;
if (Result = nil) and (Context <> nil) and (Visible) and (GlobalProjection = Projection) then
begin
if FViewport <> nil then
P := FViewport.ScreenToLocal(P);
Context.Pick(P.X, P.Y, FProjection, rPos, rDir);
if CheckHitTest(HitTest) and RayCastIntersect(AbsoluteToLocalVector(rPos), Vector3DNormalize(AbsoluteToLocalVector(rDir)), IP) then
begin
if (Projection = TProjection.pjScreen) and (Vector3DLength(Vector3DSubtract(IP, rPos)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, rPos));
Result := Self;
end;
if (Projection = TProjection.pjCamera) and (Context.FCurrentCamera <> nil) and
(Vector3DLength(Vector3DSubtract(IP, Context.FCurrentCamera.AbsolutePosition)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, Context.FCurrentCamera.AbsolutePosition));
Result := Self;
end;
end;
end;
end;
function TControl3D.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
IP, rPos, rDir: TVector3D;
Accept: Boolean;
begin
Result := nil;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
Result := NewObj;
end;
if (Result = nil) and (Context <> nil) then
begin
if FViewport <> nil then
P := FViewport.ScreenToLocal(P);
Context.Pick(P.X, P.Y, FProjection, rPos, rDir);
if CheckHitTest(HitTest) and RayCastIntersect(AbsoluteToLocalVector(rPos),
Vector3DNormalize(AbsoluteToLocalVector(rDir)), IP) and (GlobalProjection = Projection) then
begin
if (Projection = TProjection.pjScreen) and (Vector3DLength(Vector3DSubtract(IP, rPos)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, rPos));
Accept := False;
DragOver(Data, P, Accept);
if Accept then
Result := Self;
end;
if (Projection = TProjection.pjCamera) and (Context.FCurrentCamera <> nil) and
(Vector3DLength(Vector3DSubtract(IP, Context.FCurrentCamera.AbsolutePosition)) < GlobalDistance) then
begin
GlobalDistance := Vector3DLength(Vector3DSubtract(IP, Context.FCurrentCamera.AbsolutePosition));
Accept := False;
DragOver(Data, P, Accept);
if Accept then
Result := Self;
end;
end;
end;
end;
function TControl3D.GetObject: TFmxObject;
begin
Result := Self;
end;
function TControl3D.GetContext: TContext3D;
begin
if FTempContext <> nil then
Result := FTempContext
else if FViewport <> nil then
Result := FViewport.GetContext
else
Result := nil;
end;
function TControl3D.GetCursor: TCursor;
begin
Result := FCursor;
end;
function TControl3D.GetDragMode: TDragMode;
begin
Result := FDragMode;
end;
function TControl3D.GetHitTest: Boolean;
begin
Result := FHitTest;
end;
function TControl3D.GetAcceptsControls: boolean;
begin
Result := FAcceptsControls;
end;
procedure TControl3D.BeginAutoDrag;
var
S, B: TBitmap;
begin
S := TBitmap.Create(0, 0);
try
B := TBitmap.Create(48, 48);
try
PaintToBitmap(S, 128, 128, 0, False, TMultisample.msNone);
if B.Canvas.BeginScene then
try
B.Canvas.DrawBitmap(S, RectF(0, 0, S.Width, S.Height), RectF(0, 0, B.Width, B.Height), 0.7);
finally
B.Canvas.EndScene;
end;
FRoot.BeginInternalDrag(Self, B);
finally
B.Free;
end;
finally
S.Free;
end;
end;
procedure TControl3D.Apply;
begin
if FZWrite then
Context.SetContextState(TContextState.csZWriteOn)
else
Context.SetContextState(TContextState.csZWriteOff);
if Projection = TProjection.pjCamera then
Context.SetContextState(TContextState.cs3DScene)
else
Context.SetContextState(TContextState.cs2DScene);
if TwoSide then
Context.SetContextState(TContextState.csAllFace)
else
Context.SetContextState(TContextState.csFrontFace);
Context.SetMatrix(AbsoluteMatrix);
Context.SetContextState(TContextState.csSolid);
end;
procedure TControl3D.Render;
begin
end;
procedure TControl3D.DoRender;
begin
Apply;
Render;
if Assigned(FOnRender) then
begin
FOnRender(Self, Context);
end;
UnApply;
if not FDisableDragHighlight and (IsDragOver) then
begin
Context.SetMatrix(AbsoluteMatrix);
Context.Setcolor(TMaterialColor.mcDiffuse, $B2005ACC);
Context.SetContextState(TContextState.csGouraud);
Context.SetContextState(TContextState.csZWriteOn);
Context.SetContextState(TContextState.csLightOff);
Context.SetContextState(TContextState.csTexDisable);
Context.FillCube(Vector3D(0, 0, 0), Vector3D(Width + 0.01, Height + 0.01, Depth + 0.01), 0.4);
end;
RenderChildren;
end;
procedure TControl3D.RenderChildren;
var
i: Integer;
begin
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if Children[i] is TControl3D and ((TControl3D(FChildren[i]).Visible) or
(not TControl3D(FChildren[i]).Visible and (csDesigning in ComponentState) and not TControl3D(FChildren[i]).Locked)) then
begin
with TControl3D(FChildren[i]) do
begin
if (csDesigning in ComponentState) and not FDesignVisible then
Continue;
DoRender;
end;
end;
end;
procedure TControl3D.UnApply;
begin
end;
procedure TControl3D.PaintToBitmap(ABitmap: TBitmap; AWidth, AHeight: Integer; ClearColor: TAlphaColor;
AutoFit: Boolean = False; const AMultisample: TMultisample = TMultisample.msNone);
var
B: TBitmap;
FillR, R: TRectF;
i, j: Integer;
ratio: single;
FitR: TRectF;
S, t: TMatrix3D;
Scale: Single;
BitmapContext: TContext3D;
begin
if AutoFit then
begin
{ Render to bitmap }
B := TBitmap.Create(0, 0);
try
PaintToBitmap(b, AWidth, AHeight, 0, False, TMultisample.msNone); // - render with alpha
{ calc best size }
R := RectF(b.Width, b.Height, 0, 0);
for i := 0 to b.Width - 1 do
for j := 0 to b.Height - 1 do
begin
if TColorRec(b.Scanline[j][i]).a > 0 then
begin
if i < R.Left then
R.Left := i;
if j < R.Top then
R.Top := j;
if i > R.Right then
R.Right := i;
if j > R.Bottom then
R.Bottom := j;
end;
end;
FillR := R;
ratio := FitRect(R, RectF(0, 0, AWidth, AHeight));
if (ratio > 0) and (ratio < 1) then
begin
ABitmap.SetSize(AWidth, AHeight);
// render again to better size
PaintToBitmap(b, Round(AWidth / ratio), Round(AHeight / ratio), 0, False, TMultisample.msNone);
{ calc again }
R := RectF(b.Width, b.Height, 0, 0);
for i := 0 to b.Width - 1 do
for j := 0 to b.Height - 1 do
begin
if TColorRec(b.Scanline[j][i]).a > 0 then
begin
if i < R.Left then
R.Left := i;
if j < R.Top then
R.Top := j;
if i > R.Right then
R.Right := i;
if j > R.Bottom then
R.Bottom := j;
end;
end;
FillR := R;
FitRect(FillR, RectF(0, 0, AWidth, AHeight));
ABitmap.Clear(CorrectColor(ClearColor));
ABitmap.Canvas.DrawBitmap(b, RectF(R.Left, R.Top, R.Left + RectWidth(R), R.Top + RectHeight(FillR)),
FillR, 1, True);
end;
finally
B.Free;
end;
end
else
begin
R := ScreenBounds;
if IsRectEmpty(R) then
Exit;
FitR := R;
if AWidth > MaxBitmapSize then
AWidth := MaxBitmapSize;
if AHeight > MaxBitmapSize then
AHeight := MaxBitmapSize;
Scale := 1 / FitRect(FitR, RectF(0, 0, AWidth, AHeight));
ABitmap.SetSize(Round(RectWidth(R) * Scale), Round(RectHeight(R) * Scale));
BitmapContext := DefaultContextClass.CreateFromBitmap(ABitmap, AMultisample, True);
if Assigned(FViewport) then
begin
S := IdentityMatrix3D;
S.m11 := FViewport.GetContext.Height / RectHeight(R);
S.m22 := S.m11;
t := IdentityMatrix3D;
t.m41 := ( { OffsetX + } ((FViewport.GetContext.Width / 2) - ((R.Left + R.Right) / 2))) / RectWidth(R) * 2;
t.m42 := -( { OffsetY + } ((FViewport.GetContext.Height / 2) - ((R.Top + R.Bottom) / 2))) / RectHeight(R) * 2;
BitmapContext.FPaintToMatrix := Matrix3DMultiply(S, t);
end;
TempContext := BitmapContext;
try
if Assigned(FViewport) then
begin
Context.FCurrentCameraMatrix := FViewport.Context.FCurrentCameraMatrix;
Context.FCurrentCameraInvMatrix := FViewport.Context.FCurrentCameraInvMatrix;
end;
// copy lights
for i := 0 to FViewport.Context.FLights.Count - 1 do
Context.FLights.Add(FViewport.Context.FLights[i]);
// render
if Context.BeginScene then
try
Context.ResetScene;
Context.Clear([TClearTarget.ctColor, TClearTarget.ctDepth], ClearColor, 1.0, 0);
Apply;
DoRender;
UnApply;
RenderChildren;
finally
Context.EndScene;
end;
finally
TempContext := nil;
end;
BitmapContext.Free;
end;
end;
procedure TControl3D.CreateTileSnapshot(ABitmap: TBitmap; AWidth, AHeight, OffsetX, OffsetY: Integer;
Scale: Single; ClearColor: TAlphaColor);
var
i: Integer;
FitR, R: TRectF;
S, t: TMatrix3D;
BitmapContext: TContext3D;
begin
R := ScreenBounds;
if IsRectEmpty(R) then Exit;
FitR := RectF(R.left * Scale, R.Top * Scale, R.Right * Scale, R.Bottom * Scale);
if AWidth > MaxBitmapSize then AWidth := MaxBitmapSize;
if AHeight > MaxBitmapSize then AHeight := MaxBitmapSize;
RectCenter(FitR, RectF(0, 0, AWidth, AHeight));
ABitmap.SetSize(AWidth, AHeight);
BitmapContext := DefaultContextClass.CreateFromBitmap(ABitmap, TMultisample.msNone, True);
if Assigned(FViewport) and (FViewport.Context <> nil) then
begin
S := IdentityMatrix3D;
S.m11 := Min(FViewport.Context.Height / AHeight, (FViewport.Context.Width / AWidth)) * Scale;
S.m22 := S.m11;
T := IdentityMatrix3D;
T.m41 := (((-FitR.Left - offsetx) / Scale) + ((FViewport.Context.Width / 2) - ((R.Left + R.Right) / 2))) / AWidth * 2 * Scale;
T.m42 := -(((-FitR.Top - offsety) / Scale) + ((FViewport.Context.Height / 2) - ((R.Top + R.Bottom) / 2))) / AHeight * 2 * Scale;
TempContext := BitmapContext;
try
TempContext.FPaintToMatrix := Matrix3DMultiply(S, T);
if Assigned(FViewport) then
begin
{ clone camera and lights }
Context.ResetScene;
{ set matrix and camera }
Context.FCurrentCameraMatrix := FViewport.Context.FCurrentCameraMatrix;
Context.FCurrentCameraInvMatrix := FViewport.Context.FCurrentCameraInvMatrix;
{ copy lights }
for i := 0 to FViewport.Context.FLights.Count - 1 do
Context.FLights.Add(FViewport.Context.FLights[i]);
end;
// render
if Context.BeginScene then
try
Context.ResetScene;
Context.Clear([TClearTarget.ctColor, TClearTarget.ctDepth], ClearColor, 1.0, 0);
Apply;
DoRender;
UnApply;
RenderChildren;
finally
Context.EndScene;
end;
finally
TempContext := nil;
end;
end;
BitmapContext.Free;
end;
procedure TControl3D.CreateHighMultisampleSnapshot(ABitmap: TBitmap; AWidth, AHeight: Integer; ClearColor: TAlphaColor;
Multisample: Integer);
const
TileSize = 512;
var
i, j: Integer;
Sample: TBitmap;
Tile: TBitmap;
R, FitR, TileR: TRectF;
factor: Single;
begin
if Multisample < 1 then Multisample := 1;
if Multisample > 16 then Multisample := 16;
R := ScreenBounds;
FitR := R;
factor := FitRect(FitR, RectF(0, 0, AWidth, AHeight));
if factor < 1 then
begin
R := RectF(R.Left / factor, R.Top / factor, R.Right / factor, R.Bottom / factor);
RectCenter(R, RectF(0, 0, AWidth, AHeight));
end
else
R := FitR;
Sample := TBitmap.Create(round(RectWidth(R) * Multisample), round(RectHeight(R) * Multisample));
Tile := TBitmap.Create(TileSize, TileSize);
try
if Sample.Canvas.BeginScene then
try
for i := 0 to Sample.Width div TileSize do
for j := 0 to Sample.Height div TileSize do
begin
CreateTileSnapshot(Tile, TileSize, TileSize, i * TileSize, j * TileSize, Multisample / factor, ClearColor);
TileR := RectF(0, 0, TileSize, TileSize);
OffsetRect(TileR, i * TileSize, j * TileSize);
Sample.Canvas.DrawBitmap(Tile, RectF(0, 0, TileSize, TileSize), TileR, 1, True);
end;
finally
Sample.Canvas.EndScene;
end;
ABitmap.SetSize(AWidth, AHeight);
if ABitmap.Canvas.BeginScene then
try
ABitmap.Canvas.DrawBitmap(Sample, RectF(0, 0, Sample.Width, Sample.Height), R, 1);
finally
ABitmap.Canvas.EndScene;
end;
finally
Tile.Free;
Sample.Free;
end;
end;
procedure TControl3D.Repaint;
begin
if not Visible then
Exit;
if FViewport = nil then
Exit;
if csDestroying in ComponentState then
Exit;
FViewport.NeedRender;
end;
procedure TControl3D.Lock;
var
i: Integer;
begin
Locked := True;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if Children[i] is TControl3D then
TControl3D(FChildren[i]).Lock;
end;
{ bounds }
procedure TControl3D.DesignSelect;
begin
end;
procedure TControl3D.DesignClick;
begin
end;
{ events }
procedure TControl3D.DialogKey(var Key: Word; Shift: TShiftState);
begin
end;
procedure TControl3D.KeyDown(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
begin
if Assigned(FOnKeyDown) then
FOnKeyDown(Self, Key, KeyChar, Shift);
end;
procedure TControl3D.KeyUp(var Key: Word; var KeyChar: System.WideChar; Shift: TShiftState);
begin
if Assigned(FOnKeyUp) then
FOnKeyUp(Self, Key, KeyChar, Shift);
end;
procedure TControl3D.Capture;
begin
if (Root <> nil) then
Root.SetCaptured(Self);
end;
procedure TControl3D.ReleaseCapture;
begin
if (Root <> nil) then
Root.SetCaptured(nil);
end;
procedure TControl3D.DoMouseEnter;
begin
FIsMouseOver := True;
StartTriggerAnimation(Self, 'IsMouseOver');
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self);
end;
procedure TControl3D.DoMouseLeave;
begin
FIsMouseOver := False;
StartTriggerAnimation(Self, 'IsMouseOver');
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self);
end;
procedure TControl3D.DoEnter;
begin
FIsFocused := True;
StartTriggerAnimation(Self, 'IsFocused');
end;
procedure TControl3D.DoExit;
begin
FIsFocused := False;
Repaint;
StartTriggerAnimation(Self, 'IsFocused');
end;
procedure TControl3D.SetFocus;
begin
if not FIsFocused and (Root <> nil) then
Root.SetFocused(Self);
end;
procedure TControl3D.UpdateTabOrder(Value: TTabOrder);
var
CurIndex, Count: Integer;
begin
CurIndex := GetTabOrder;
if (CurIndex >= 0) and (Parent <> nil) and (TOpenObject(Parent).FTabList <> nil) then
begin
Count := TOpenObject(Parent).FTabList.Count;
if Value < 0 then
Value := 0;
if Value >= Count then
Value := Count - 1;
if Value <> CurIndex then
begin
TOpenObject(Parent).FTabList.Delete(CurIndex);
TOpenObject(Parent).FTabList.Insert(Value, Pointer(AsIControl));
end;
end;
end;
function TControl3D.GetTabOrder: TTabOrder;
begin
if (Parent <> nil) and (TOpenObject(Parent).FTabList <> nil) then
Result := TOpenObject(Parent).FTabList.IndexOf(Pointer(AsIControl))
else
Result := -1;
end;
function TControl3D.GetTabOrderValue: TTabOrder;
begin
Result := FTabOrder;
end;
function TControl3D.GetVisible: Boolean;
begin
Result := Visible;
end;
procedure TControl3D.ContextMenu(const ScreenPosition: TPoint3D);
begin
{ if FPopupMenu <> nil then
begin
FPopupMenu.PopupComponent := Self;
FPopupMenu.Popup(round(ScreenPosition.X), round(ScreenPosition.Y));
end; }
end;
procedure TControl3D.CopyRotationFrom(const AObject: TControl3D);
begin
FRotationAngle.SetPoint3DNoChange(AObject.RotationAngle.Point);
FQuaternion := AObject.FQuaternion;
MatrixChanged(Self);
end;
procedure TControl3D.Click;
begin
if Assigned(FOnClick) then
FOnClick(Self);
end;
procedure TControl3D.DblClick;
begin
if Assigned(FOnDblClick) then
FOnDblClick(Self);
end;
procedure TControl3D.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
RayDir, RayPos: TVector3D;
begin
if not (csDesigning in ComponentState) and not FIsFocused and (FRoot <> nil) and
(((FRoot.GetFocused <> nil) and (FRoot.GetFocused.GetObject <> Self)) or (FRoot.GetFocused = nil)) then
SetFocus;
P := PointF(X, Y);
Context.Pick(P.X, P.Y, FProjection, RayPos, RayDir);
RayPos := AbsoluteToLocalVector(RayPos);
RayDir := Vector3DNormalize(AbsoluteToLocalVector(RayDir));
MouseDown3D(Button, Shift, P.X, P.Y, RayPos, RayDir);
end;
procedure TControl3D.MouseMove(Shift: TShiftState; X, Y: Single);
var
P: TPointF;
RayDir, RayPos: TVector3D;
begin
P := PointF(X, Y);
Context.Pick(P.X, P.Y, FProjection, RayPos, RayDir);
RayPos := AbsoluteToLocalVector(RayPos);
RayDir := Vector3DNormalize(AbsoluteToLocalVector(RayDir));
MouseMove3D(Shift, P.X, P.Y, RayPos, RayDir);
end;
procedure TControl3D.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
var
P: TPointF;
RayDir, RayPos: TVector3D;
begin
P := PointF(X, Y);
Context.Pick(P.X, P.Y, FProjection, RayPos, RayDir);
RayPos := AbsoluteToLocalVector(RayPos);
RayDir := Vector3DNormalize(AbsoluteToLocalVector(RayDir));
MouseUp3D(Button, Shift, P.X, P.Y, RayPos, RayDir);
end;
procedure TControl3D.MouseDown3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single;
RayPos, RayDir: TVector3D);
//var
// P: TPoint3D;
// VP: TPoint3D;
begin
if not(csDesigning in ComponentState) and CanFocus and not FIsFocused then
SetFocus;
if Assigned(FOnMouseDown) then
FOnMouseDown(Self, Button, Shift, X, Y, RayPos, RayDir);
{if (Button = TMouseButton.mbRight) and FShowContextMenu then
begin
VP := LocalToAbsolute(Point3D(X, Y, 0));
P := Point(Trunc(VP.X), Trunc(VP.Y));
P := Scene.ClientToScreen(P);
ContextMenu(PointF(P.X, P.Y));
Exit;
end; }
if FAutoCapture then
Capture;
if (ssDouble in Shift) then
begin
FPressed := True;
FDoubleClick := True;
end
else if Button = TMouseButton.mbLeft then
begin
FPressed := True;
end;
end;
procedure TControl3D.MouseMove3D(Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D);
begin
if Assigned(FOnMouseMove) then
FOnMouseMove(Self, Shift, X, Y, RayPos, RayDir);
end;
procedure TControl3D.MouseUp3D(Button: TMouseButton; Shift: TShiftState; X, Y: Single; RayPos, RayDir: TVector3D);
begin
if FAutoCapture then
ReleaseCapture;
if FPressed and not (FDoubleClick) and (FIsMouseOver) then
begin
FPressed := False;
Click;
end
else if FPressed and (FDoubleClick) and (FIsMouseOver) then
begin
FDoubleClick := False;
FPressed := False;
DblClick;
end;
if Assigned(FOnMouseUp) then
FOnMouseUp(Self, Button, Shift, X, Y, RayPos, RayDir);
end;
procedure TControl3D.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
begin
if Assigned(FOnMouseWheel) then
FOnMouseWheel(Self, Shift, WheelDelta, Handled);
end;
procedure TControl3D.DragEnter(const Data: TDragObject; const Point: TPointF);
begin
FIsDragOver := True;
Repaint;
StartTriggerAnimation(Self, 'IsDragOver');
if Assigned(OnDragEnter) then
OnDragEnter(Self, Data, NullPoint3D);
end;
procedure TControl3D.DragLeave;
begin
FIsDragOver := False;
Repaint;
StartTriggerAnimation(Self, 'IsDragOver');
if Assigned(OnDragLeave) then
OnDragLeave(Self);
end;
procedure TControl3D.DragEnd;
begin
// Call mouse up - for effects - inside control
if DragMode = TDragMode.dmAutomatic then
MouseUp3D(TMouseButton.mbLeft, [ssLeft], $FFFF, $FFFF, Vector3D($FFFF, $FFFF, 0), Vector3D(1, 0, 0));
if Assigned(OnDragEnd) then
OnDragEnd(Self);
end;
procedure TControl3D.DragOver(const Data: TDragObject; const Point: TPointF; var Accept: Boolean);
begin
if Assigned(OnDragOver) then
OnDragOver(Self, Data, NullPoint3D, Accept);
end;
procedure TControl3D.DragDrop(const Data: TDragObject; const Point: TPointF);
begin
FIsDragOver := False;
Repaint;
StartTriggerAnimation(Self, 'IsDragOver');
if Assigned(OnDragDrop) then
OnDragDrop(Self, Data, NullPoint3D);
end;
{ properties }
procedure TControl3D.SetTabOrder(const Value: TTabOrder);
begin
end;
procedure TControl3D.SetTempContext(const Value: TContext3D);
var
i: Integer;
begin
FTempContext := Value;
if (FChildren <> nil) and (FChildren.Count > 0) then
for i := 0 to FChildren.Count - 1 do
if (Children[i] is TControl3D) then
TControl3D(FChildren[i]).TempContext := Value;
end;
procedure TControl3D.SetHitTest(const Value: Boolean);
begin
FHitTest := Value;
end;
procedure TControl3D.SetAcceptsControls(const Value: boolean);
begin
FAcceptsControls := Value;
end;
procedure TControl3D.SetClipChildren(const Value: Boolean);
begin
if FClipChildren <> Value then
begin
FClipChildren := Value;
Repaint;
end;
end;
procedure TControl3D.SetProjection(const Value: TProjection);
const
Fit: single = 25;
var
i: Integer;
begin
if FProjection <> Value then
begin
FProjection := Value;
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
if (Children[i] is TControl3D) then
TControl3D(FChildren[i]).Projection := Value;
if not (csLoading in ComponentState) then
begin
if FProjection = TProjection.pjScreen then
begin
SetSize(Fit * Width, Fit * Height, Fit * Depth);
if (FViewport <> nil) and (FViewport.Context <> nil) then
Position.Point := Point3D(FViewport.Context.Width / 2, FViewport.Context.Height / 2, 0);
end
else
begin
SetSize(Width / Fit, Height / Fit, Depth / Fit);
Position.Point := Point3D(0, 0, 0);
end;
Repaint;
end;
end;
end;
procedure TControl3D.SetSize(const AWidth, AHeight, ADepth: single);
begin
Width := AWidth;
Height := AHeight;
Depth := ADepth;
end;
procedure TControl3D.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
if FVisible then
Repaint;
FVisible := Value;
if FVisible then
Repaint;
if FVisible then
StartTriggerAnimation(Self, 'IsVisible')
else if FIsFocused then
FRoot.SetFocused(nil);
end;
end;
procedure TControl3D.SetHeight(const Value: Single);
begin
if FHeight <> Value then
begin
FHeight := Value;
Resize3D;
if (FHeight < 0) and (csDesigning in ComponentState) then
begin
FHeight := abs(FHeight);
FScale.Y := -FScale.Y;
end;
if not (csLoading in ComponentState) then
begin
Repaint;
end;
end;
end;
procedure TControl3D.SetWidth(const Value: Single);
begin
if FWidth <> Value then
begin
FWidth := Value;
Resize3D;
if (FWidth < 0) and (csDesigning in ComponentState) then
begin
FWidth := abs(FWidth);
FScale.X := -FScale.X;
end;
if not(csLoading in ComponentState) then
begin
Repaint;
end;
end;
end;
procedure TControl3D.SetDepth(const Value: Single);
begin
if FDepth <> Value then
begin
FDepth := Value;
Resize3D;
if (FDepth < 0) and (csDesigning in ComponentState) then
begin
FDepth := abs(FDepth);
FScale.Z := -FScale.Z;
end;
if not (csLoading in ComponentState) then
begin
Repaint;
end;
end;
end;
function TControl3D.IsOpacityStored: Boolean;
begin
//Result := FOpacity <> 1;
Result := True;
end;
procedure TControl3D.SetZWrite(const Value: Boolean);
begin
if FZWrite <> Value then
begin
FZWrite := Value;
Repaint;
end;
end;
procedure TControl3D.SetDesignVisible(const Value: Boolean);
begin
if FDesignVisible <> Value then
begin
FDesignVisible := Value;
if (csDesigning in ComponentState) then
Repaint;
end;
end;
procedure TControl3D.SetDragMode(const ADragMode: TDragMode);
begin
FDragMode := ADragMode;
end;
procedure TControl3D.SetOpacity(const Value: Single);
begin
if FOpacity <> Value then
begin
FOpacity := Value;
if FOpacity < 0 then
FOpacity := 0;
if FOpacity > 1 then
FOpacity := 1;
RecalcOpacity;
Repaint;
end;
end;
{ TCamera }
constructor TCamera.Create(AOwner: TComponent);
begin
inherited;
HitTest := False;
FCanResize := False;
Position.Point := Point3D(0, 0, -5);
end;
destructor TCamera.Destroy;
begin
inherited;
end;
procedure TCamera.DesignClick;
begin
inherited;
if FViewport <> nil then
begin
if FSaveCamera = nil then
begin
FSaveCamera := FViewport.DesignCamera;
FViewport.DesignCamera := Self;
Repaint;
end
else
begin
FViewport.DesignCamera := FSaveCamera;
FSaveCamera := nil;
end;
end;
end;
procedure TCamera.Render;
begin
if Tag = $FFFE then
Exit;
if (csDesigning in ComponentState) then
begin
Context.SetContextState(TContextState.csLightOff);
Context.SetContextState(TContextState.csTexDisable);
Context.SetColor(TMaterialColor.mcDiffuse, $FF60A799);
Context.FillCube(Vector3D(0, 0, 0), Vector3D(0.8, 0.8, 0.8), 1);
Context.SetColor(TMaterialColor.mcDiffuse, $FF9C60A7);
Context.FillCube(Vector3D(0, 0, 0.5), Vector3D(0.3, 0.3, 1.4), 1);
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3D(0, 0, 1), 1000), 1);
end;
end;
function TCamera.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
begin
Result := False;
if (csDesigning in ComponentState) then
Result := inherited;
end;
procedure TCamera.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FTarget) then
begin
FTarget := nil;
MatrixChanged(Self);
end;
end;
procedure TCamera.SetTarget(const Value: TControl3D);
begin
FTarget := Value;
end;
{ TLight }
constructor TLight.Create(AOwner: TComponent);
begin
inherited;
HitTest := False;
FEnabled := True;
FCanResize := False;
FSpotCutOff := 180;
FSpotExponent := 0;
FConstantAttenuation := 1;
FQuadraticAttenuation := 0;
FLinearAttenuation := 0;
FAmbient := $FF202020;
FSpecular := $FFFFFFFF;
FDiffuse := $FFA0A0A0;
end;
destructor TLight.Destroy;
begin
inherited;
end;
procedure TLight.Render;
var
i: Integer;
begin
if (csDesigning in ComponentState) then
begin
Context.SetContextState(TContextState.csTexDisable);
Context.SetContextState(TContextState.csLightOff);
Context.SetColor(TMaterialColor.mcDiffuse, TAlphaColors.Yellow);
Context.FillCube(Vector3D(0, 0, 0), Vector3DScale(Vector3D(Width, Height, Depth), 0.8), 1);
Context.SetColor(TMaterialColor.mcDiffuse, TAlphaColors.Navy);
Context.DrawCube(Vector3D(0, 0, 0), Vector3DScale(Vector3D(Width, Height, Depth), 0.8), 1);
case LightType of
TLightType.ltDirectional:
begin
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3D(0, 0, 1), Width * 5), 1);
end;
TLightType.ltPoint:
begin
for i := 1 to 18 do
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3D(cos(DegToRad(i * 20)), sin(DegToRad(i * 20)),
0), Width * 2), 1);
for i := 1 to 18 do
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3D(cos(DegToRad(i * 20)), 0,
sin(DegToRad(i * 20))), Width * 2), 1);
end;
TLightType.ltSpot:
begin
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3DNormalize(Vector3D(0.2, -0.2, 1)), Width * 5), 1);
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3DNormalize(Vector3D(0.2, 0.2, 1)), Width * 5), 1);
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3DNormalize(Vector3D(-0.2, 0.2, 1)), Width * 5), 1);
Context.DrawLine(Vector3D(0, 0, 0), Vector3DScale(Vector3DNormalize(Vector3D(-0.2, -0.2, 1)), Width * 5), 1);
end;
end;
end;
end;
function TLight.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
begin
Result := False;
if (csDesigning in ComponentState) then
Result := inherited;
end;
procedure TLight.SetDepth(const Value: Single);
begin
if Projection = TProjection.pjCamera then
inherited SetDepth(1)
else
inherited SetDepth(25);
end;
procedure TLight.SetDiffuse(const Value: TAlphaColor);
begin
if FDiffuse <> Value then
begin
FDiffuse := Value;
end;
end;
procedure TLight.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
if (FViewport <> nil) then
FViewport.NeedRender;
end;
end;
procedure TLight.SetHeight(const Value: Single);
begin
if Projection = TProjection.pjCamera then
inherited SetHeight(1)
else
inherited SetHeight(25);
end;
procedure TLight.SetLightType(const Value: TLightType);
begin
if FLightType <> Value then
begin
FLightType := Value;
case FLightType of
TLightType.ltPoint:
begin
SpotCutOff := 180;
SpotExponent := 0;
end;
TLightType.ltSpot:
begin
SpotCutOff := 60;
SpotExponent := 4;
end;
end;
end;
end;
procedure TLight.SetAmbient(const Value: TAlphaColor);
begin
if FAmbient <> Value then
begin
FAmbient := Value;
end;
end;
procedure TLight.SetConstantAttenuation(const Value: Single);
begin
if FConstantAttenuation <> Value then
begin
FConstantAttenuation := Value;
end;
end;
procedure TLight.SetLinearAttenuation(const Value: Single);
begin
if FLinearAttenuation <> Value then
begin
FLinearAttenuation := Value;
end;
end;
procedure TLight.SetQuadraticAttenuation(const Value: Single);
begin
if FQuadraticAttenuation <> Value then
begin
FQuadraticAttenuation := Value;
end;
end;
procedure TLight.SetSpecular(const Value: TAlphaColor);
begin
if FSpecular <> Value then
begin
FSpecular := Value;
end;
end;
procedure TLight.SetSpotCutOff(const Value: Single);
begin
if FSpotCutOff <> Value then
begin
FSpotCutOff := Value;
end;
end;
procedure TLight.SetSpotExponent(const Value: Single);
begin
if FSpotExponent <> Value then
begin
FSpotExponent := Value;
end;
end;
procedure TLight.SetNewViewport(AViewport: IViewport3D);
begin
if (FViewport <> nil) and (FViewport.Context <> nil) then
FViewport.Context.DeleteLight(Self);
inherited;
if (FViewport <> nil) and (FViewport.Context <> nil) then
FViewport.Context.AddLight(Self);
end;
procedure TLight.SetWidth(const Value: Single);
begin
if Projection = TProjection.pjCamera then
inherited SetWidth(1)
else
inherited SetWidth(25);
end;
{ TDummy }
constructor TDummy.Create(AOwner: TComponent);
begin
inherited;
HitTest := False;
end;
destructor TDummy.Destroy;
begin
inherited;
end;
procedure TDummy.Render;
begin
if Tag = $FFFE then
Exit;
if (csDesigning in ComponentState) and not Locked then
begin
Context.SetColor(TMaterialColor.mcDiffuse, $8060A799);
Context.DrawCube(Vector3D(0, 0, 0), Vector3D(Width, Height, Depth), AbsoluteOpacity);
end;
end;
function TDummy.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
begin
Result := False;
if (csDesigning in ComponentState) then
Result := inherited;
end;
{ TProxyObject }
constructor TProxyObject.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TProxyObject.Destroy;
begin
inherited;
end;
procedure TProxyObject.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FSourceObject) then
SourceObject := nil;
end;
procedure TProxyObject.Render;
var
SaveM: TMatrix3D;
SaveS: TVector3D;
begin
if FSourceObject <> nil then
begin
SaveM := FSourceObject.FAbsoluteMatrix;
SaveS.X := FSourceObject.FWidth;
SaveS.Y := FSourceObject.FHeight;
SaveS.Z := FSourceObject.FDepth;
FSourceObject.FAbsoluteMatrix := AbsoluteMatrix;
FSourceObject.FWidth := FWidth;
FSourceObject.FHeight := FHeight;
FSourceObject.FDepth := FDepth;
// FSourceObject.RecalcAbsolute;
FSourceObject.Apply;
FSourceObject.Render;
FSourceObject.UnApply;
FSourceObject.RenderChildren;
FSourceObject.FAbsoluteMatrix := SaveM;
FSourceObject.FWidth := SaveS.X;
FSourceObject.FHeight := SaveS.Y;
FSourceObject.FDepth := SaveS.Z;
// FSourceObject.RecalcAbsolute;
end;
end;
function TProxyObject.RayCastIntersect(const RayPos, RayDir: TVector3D; var Intersection: TVector3D): Boolean;
begin
Result := inherited;
end;
procedure TProxyObject.SetSourceObject(const Value: TControl3D);
begin
if (FSourceObject <> Value) and (Value <> Self) then
begin
FSourceObject := Value;
Repaint;
end;
end;
{ TViewport3D }
constructor TViewport3D.Create(AOwner: TComponent);
begin
inherited;
AutoCapture := True;
ShowHint := True;
Width := 100;
Height := 100;
FMultisample := TMultisample.ms4Samples;
FBuffer := TBitmap.Create(100, 100);
FContext := DefaultContextClass.CreateFromBitmap(FBuffer, FMultisample, True);
FLights := TList.Create;
FUsingDesignCamera := True;
FFill := TAlphaColors.White;
FDesignCameraZ := TDummy.Create(Self);
with FDesignCameraZ do
begin
Tag := $FFFE;
Locked := True;
Stored := False;
end;
AddObject(FDesignCameraZ);
FDesignCameraX := TDummy.Create(Self);
with FDesignCameraX do
begin
Tag := $FFFE;
Parent := FDesignCameraZ;
Locked := True;
Stored := False;
RotationAngle.X := -20;
end;
FDesignCamera := TCamera.Create(Self);
with FDesignCamera do
begin
Tag := $FFFE;
Parent := FDesignCameraX;
Locked := True;
Stored := False;
Position.Point := Point3D(0, 0, -20);
end;
end;
destructor TViewport3D.Destroy;
begin
DeleteChildren;
FLights.Free;
if (FContext <> nil) then
FreeAndNil(FContext);
if (FBuffer <> nil) then
FreeAndNil(FBuffer);
if FChildren <> nil then
FreeAndNil(FChildren);
FreeAndNil(FContext);
inherited;
end;
procedure TViewport3D.Paint;
var
R: TRectF;
i: Integer;
begin
if (csDesigning in ComponentState) then
begin
R := LocalRect;
InflateRect(R, -0.5, -0.5);
Canvas.StrokeThickness := 1;
Canvas.StrokeDash := TStrokeDash.sdDash;
Canvas.Stroke.Kind := TBrushKind.bkSolid;
Canvas.Stroke.color := $A0909090;
Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity);
Canvas.StrokeDash := TStrokeDash.sdSolid;
end;
if Context = nil then Exit;
if FDrawing then Exit;
FDrawing := True;
try
if Context.BeginScene then
try
{ set matrix and camera }
if Camera <> nil then
Context.SetCamera(Camera);
{ Design Camera }
if (csDesigning in ComponentState) or FUsingDesignCamera then
Context.SetCamera(FDesignCamera);
{ set states }
Context.ResetScene;
{ start }
Context.Clear([TClearTarget.ctColor, TClearTarget.ctDepth], FFill, 1.0, 0);
{ reset }
if FChildren <> nil then
for i := 0 to FChildren.Count - 1 do
begin
if not (TFmxObject(FChildren[i]) is TControl3D) then Continue;
if TControl3D(FChildren[i]).Visible or (not TControl3D(FChildren[i]).Visible and (csDesigning in TControl3D(FChildren[i]).ComponentState) and not TControl3D(FChildren[i]).Locked) then
begin
if not(TObject(FChildren[i]) is TControl3D) then
Continue;
if (csDesigning in ComponentState) and not TControl3D(FChildren[i]).DesignVisible then
Continue;
TControl3D(FChildren[i]).DoRender;
end;
end;
finally
Context.EndScene;
end;
finally
{ off flag }
FDrawing := False;
end;
{ draw }
inherited Canvas.DrawBitmap(FBuffer, RectF(0, 0, FBuffer.Width, FBuffer.Height),
RectF(0, 0, FBuffer.Width, FBuffer.Height), AbsoluteOpacity, True);
end;
procedure TViewport3D.AddObject(AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
begin
TControl3D(AObject).SetNewViewport(Self);
TControl3D(AObject).Repaint;
end;
if (csDesigning in ComponentState) and (AObject is TCamera) and (AObject.Tag <> $FFFE) then
Camera := TCamera(AObject);
end;
procedure TViewport3D.RemoveObject(AObject: TFmxObject);
begin
inherited;
if AObject is TControl3D then
TControl3D(AObject).SetNewViewport(nil);
end;
procedure TViewport3D.Realign;
begin
inherited;
if (Context <> nil) then
begin
FBuffer.SetSize(Trunc(Width), Trunc(Height));
Context.SetSize(Trunc(Width), Trunc(Height));
AlignObjects(Self, Margins, FBuffer.Width, FBuffer.Height, FLastWidth, FLastHeight, FDisableAlign);
end;
end;
procedure TViewport3D.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FCamera) then
FCamera := nil;
end;
function TViewport3D.ObjectAtPoint(P: TPointF): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
NewObj := inherited ObjectAtPoint(P);
if NewObj = nil then Exit;
NewObj := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
Result := NewObj;
end;
if Result = nil then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.GetVisible and not(csDesigning in ComponentState) then
Continue;
NewObj := NewObj.ObjectAtPoint(P);
if NewObj <> nil then
Result := NewObj;
end;
end;
if Result = nil then
Result := inherited ObjectAtPoint(P);
end;
function TViewport3D.FindTarget(P: TPointF; const Data: TDragObject): IControl;
var
i: Integer;
Obj: TFmxObject;
NewObj: IControl;
begin
Result := nil;
// first screen projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjScreen;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then
Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
Result := NewObj;
end;
if Result = nil then
begin
// second camera projection
GlobalDistance := $FFFF;
GlobalProjection := TProjection.pjCamera;
for i := ChildrenCount - 1 downto 0 do
begin
Obj := Children[i];
if IInterface(Obj).QueryInterface(IControl, NewObj) <> 0 then
Continue;
if not NewObj.Visible then
Continue;
NewObj := NewObj.FindTarget(P, Data);
if NewObj <> nil then
Result := NewObj;
end;
end;
if Result = nil then
Result := inherited FindTarget(P, Data);
end;
function TViewport3D.GetFill: TAlphaColor;
begin
Result := FFill;
end;
procedure TViewport3D.SetFill(const Value: TAlphaColor);
begin
if FFill <> Value then
begin
FFill := Value;
Repaint;
end;
end;
procedure TViewport3D.SetMultisample(const Value: TMultisample);
begin
if FMultisample <> Value then
begin
FMultisample := Value;
if Context <> nil then
Context.SetMultisample(FMultisample);
end;
end;
{ IViewport3D }
function TViewport3D.GetObject: TFmxObject;
begin
Result := Self;
end;
function TViewport3D.GetContext: TContext3D;
begin
Result := FContext;
end;
function TViewport3D.GetScene: IScene;
begin
Result := Scene;
end;
function TViewport3D.GetDesignCamera: TCamera;
begin
Result := FDesignCamera;
end;
procedure TViewport3D.SetDesignCamera(const ACamera: TCamera);
begin
FDesignCamera := ACamera;
end;
procedure TViewport3D.NeedRender;
begin
Repaint;
UpdateEffects;
end;
initialization
RegisterFmxClasses([TPosition3D, TMeshData, TMaterial, TCamera, TLight, TDummy,
TProxyObject, TViewport3D], [TPosition3D, TMeshData, TMaterial]);
end.
|
unit MediaProcessing.Convertor.RGB.MJPEG;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global;
type
TPerformance = (pBestQuality, pBestSpeed);
TMediaProcessor_Convertor_Rgb_MJpeg=class (TMediaProcessor,IMediaProcessor_Convertor_Rgb_MJpeg)
protected
FCompressionQuality: integer;
FPerformance: TPerformance;
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses Controls,uBaseClasses,MediaProcessing.Convertor.RGB.MJPEG.SettingsDialog;
{ TMediaProcessor_Convertor_Rgb_MJpeg }
constructor TMediaProcessor_Convertor_Rgb_MJpeg.Create;
begin
inherited;
FCompressionQuality:=50;
FPerformance:=pBestSpeed;
end;
destructor TMediaProcessor_Convertor_Rgb_MJpeg.Destroy;
begin
inherited;
end;
function TMediaProcessor_Convertor_Rgb_MJpeg.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_Convertor_Rgb_MJpeg.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_Rgb_MJpeg;
result.Name:='Конвертор RGB->MJPG';
result.Description:='Преобразует видеокадры формата RGB в формат Motion Jpeg';
result.SetInputStreamType(stRGB);
result.OutputStreamType:=stMJpeg;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_Convertor_Rgb_MJpeg.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FCompressionQuality:=aReader.ReadInteger('CompressionQuality',FCompressionQuality);
FPerformance:=TPerformance(aReader.ReadInteger('Performance',integer(FPerformance)));
end;
procedure TMediaProcessor_Convertor_Rgb_MJpeg.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteInteger('CompressionQuality',FCompressionQuality);
aWriter.WriteInteger('Performance',integer(FPerformance));
end;
procedure TMediaProcessor_Convertor_Rgb_MJpeg.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsRgb_MJpeg;
begin
aDialog:=TfmMediaProcessingSettingsRgb_MJpeg.Create(nil);
try
aDialog.cbCompression.ItemIndex:=aDialog.cbCompression.Items.IndexOfData(FCompressionQuality);
if aDialog.cbCompression.ItemIndex=-1 then
aDialog.cbCompression.ItemIndex:=0;
aDialog.buPerformanceSpeed.Checked:=FPerformance=pBestSpeed;
aDialog.buPerformanceQuality.Checked:=FPerformance=pBestQuality;
if aDialog.ShowModal=mrOK then
begin
FCompressionQuality:=aDialog.cbCompression.CurrentItemData;
if aDialog.buPerformanceSpeed.Checked then
FPerformance:=pBestSpeed
else
FPerformance:=pBestQuality;
end;
finally
aDialog.Free;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_Rgb_MJpeg);
end.
|
unit PascalCoin.FMX.Strings;
interface
resourcestring
SPleaseGiveThisNodeAName = 'Please give this node a name';
STheURLEnteredIsNotValid = 'The URL entered is not valid';
SEnablingThisWillAllowYouToAutoma =
'Enabling this will allow you to automatically send from multiple accounts if one account does not contain enough PASC';
STheAccountNumberIsInvalid =
'The account number is invalid, check that the main part only contains digits and that the correct checksum has been used';
SUnlockWallet = 'Unlock Wallet';
SFailedToUnlockYourWallet = 'Failed to unlock your wallet';
SLockWallet = 'Lock Wallet';
SPleaseUnlockYourWalletFirst = 'Please unlock your wallet first';
SItHasNotBeenPossibleToChangeYour =
'it has not been possible to change your password';
SItHasBeenNotPossibleToEncryptYou =
'it has been not possible to encrypt you password';
SYourPasswordHasBeenChanged = 'Your password has been changed';
SYourWalletHasBeenEncrypted = 'Your wallet has been encrypted';
SChangeYourPassword = 'Change your password';
SSetAPassword = 'Set a password';
SUnableToUnlockYourWallet = 'Unable to unlock your wallet';
SThisDoesnTMatchThePasswordAlread =
'this doesn''t match the password already set';
STheWalletIsNotEncrypted = 'the wallet is not encrypted';
SThisIsTheSameAsTheExistingName = 'This is the same as the existing name';
SYouHavenTEneteredAName = 'You haven''t enetered a name';
SPublicKeyCopiedToClipboard = 'Public Key copied to clipboard';
yourWalletIs = 'Your wallet is';
statePlainText = 'Unencrypted';
stateEncrypted = 'Encrypted';
stateDecrypted = 'Decrypted';
implementation
end.
|
unit SHL_Progress; // SemVersion: 0.1.0
// Contains ...
// Changelog:
// 0.1.0 - test version
// TODO:
//
interface // SpyroHackingLib is licensed under WTFPL
uses
SysUtils, Classes, SHL_Types;
type
TConsoleProgress = class(TObject)
constructor Create(MaxValue: Integer; MinValue: Integer = 0; Timeout: Integer = 1000);
private
FTimeout: Integer;
FOldValue, FOldPrint, FRealValue: Integer;
FOldTime: TDateTime;
FMinimal: Integer;
FBody: Double;
public
procedure Show(Current: Integer);
procedure Step(Count: Integer = 1);
procedure Success();
end;
implementation
uses
DateUtils;
constructor TConsoleProgress.Create(MaxValue: Integer; MinValue: Integer = 0; Timeout: Integer = 1000);
begin
FTimeout := Timeout;
FOldValue := Integer($80000000);
FOldPrint := FOldValue;
FMinimal := MinValue;
FBody := (MaxValue - MinValue);
Show(0);
end;
procedure TConsoleProgress.Show(Current: Integer);
var
Time: TDateTime;
Print: Integer;
begin
FRealValue := Current;
if Current = FOldValue then
Exit;
Print := Round((Current - FMinimal) / FBody * 100);
if Print = FOldPrint then
Exit;
Time := Now();
if MilliSecondsBetween(Time, FOldTime) < FTimeout then
Exit;
if Print < 0 then
Print := 0
else if Print > 100 then
Print := 100;
Write(#9, Print, ' % ', #9#13);
FOldValue := Current;
FOldPrint := Print;
FOldTime := Time;
end;
procedure TConsoleProgress.Step(Count: Integer = 1);
begin
Show(FRealValue + Count);
end;
procedure TConsoleProgress.Success();
begin
WriteLn(#9, '100 %');
end;
end.
|
unit UnDespesas;
{Verificado
-.edit;
}
interface
uses
Db, DBTables, Classes, sysUtils,SQLExpr, Tabela;
type
TFuncoesDespesas = class
AUX : TSQLQuery;
AUX1,
CAD : TSQL;
VprBaseDados : TSqlConnection;
private
Campos: TStringList;
procedure CarregaMOV(VpaTstringMOV: TStringList);
procedure CarregaCAD(VpaTstringCAD: TStringList);
public
constructor Criar( Aowner : TComponent; VpaBaseDados : TSqlConnection);
destructor Destroy;
function GeraDespesasFixas(TituloAPagar: Integer): Boolean;
function AtualizaDespesas: Boolean;
procedure GeraNovaDespesa(VpaValor: Double; VpaDiaVencimento,
VpaQtdMesesInc: Integer; VpaDespesa: string);
function BuscaValorDias(VpaDataInicio, VpaDespesa: string;
var VpaValor: Double; var VpaDias: Integer): boolean;
function ExisteDespesaPeriodo(VpaDespesa: string;
VpaDataInicio, VpaDataFim: TDateTime): Integer;
procedure AlteraDespesa(VpaLancamento: Integer;
VpaNovaDataVencimento: TDateTime; VpaValor:Double);
end;
implementation
uses Constantes, fundata, funstring, funsql, ConstMsg;
{ ****************** Na criação da classe ******************************** }
constructor TFuncoesDespesas.Criar( Aowner : TComponent; VpaBaseDados : TSqlConnection);
begin
inherited;
Campos := TStringList.Create;
VprBaseDados := VpaBaseDados;
Aux := TSQLQuery.Create(nil);
Aux.SQLConnection := VpaBaseDados;
Cad := TSQL.Create(nil);
Cad.ASQLConnection := VpaBaseDados;
AUX1 := TSQL.Create(nil);
AUX1.ASQLConnection := VpaBaseDados;
end;
{ ******************* Quando destroy a classe ****************************** }
destructor TFuncoesDespesas.Destroy;
begin
Campos.Free;
AUX.Destroy;
AUX1.Destroy;
CAD.Destroy;
inherited;
end;
{ ***** gera as despesas novas quando vira o mes ***** }
function TFuncoesDespesas.AtualizaDespesas: Boolean;
var
VpfValor: Double;
VpfDias: Integer;
begin
// Seleciona as despesas fixas ativas.
AdicionaSQLAbreTabela(CAD, ' SELECT * FROM CADDESPESAS, ' +
' WHERE I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) +
' AND UPPER(C_ATI_DES) = ''S''');
if (not CAD.EOF) then
begin
CAD.First;
while (not CAD.EOF) do
begin
// Data inicial da média;
if BuscaValorDias(DataToStrFormato(AAAAMMDD,DecMes(Date,
CAD.FieldByName('I_MES_MED').AsInteger),'/'),
Trim(CAD.FieldByName('I_COD_DES').AsString),
VpfValor,
VpfDias) then
GeraNovaDespesa(VpfValor,
VpfDias,
CAD.FieldByName('I_MES_GER').AsInteger,
CAD.FieldByName('I_COD_DES').AsString);
CAD.Next;
end;
end;
end;
function TFuncoesDespesas.BuscaValorDias(VpaDataInicio, VpaDespesa: string;
var VpaValor: Double; var VpaDias: Integer): boolean;
var
VpfDataFim: string;
begin
VpfDataFim:=DataToStrFormato(AAAAMMDD, UltimoDiaMesAnterior, '/');
// Retorna o novo valor de cadastro e o dia de vencimento.
AdicionaSQLAbreTabela(AUX, ' SELECT ISNULL(SUM(N_VLR_DUP)/ COUNT(*),0) AS VALOR ,' +
' ISNULL(SUM(DAY(D_DAT_VEN)) / COUNT(*),0) AS DIA ' +
' FROM CADCONTASAPAGAR CP KEY JOIN MOVCONTASAPAGAR MCP ' +
' WHERE MCP.D_DAT_VEN BETWEEN ''' + VpaDataInicio + ''' AND ''' + VpfDataFim + '''' +
' AND CP.I_COD_DES = ' + VpaDespesa);
VpaValor:=AUX.FieldByName('VALOR').AsFloat;
VpaDias:=AUX.FieldByName('DIA').AsInteger;
Result:=(VpaValor > 0);
end;
{ ***** gera a nova despesa deste lancamento para o próximo mês ***** }
procedure TFuncoesDespesas.GeraNovaDespesa(VpaValor: Double;
VpaDiaVencimento, VpaQtdMesesInc: Integer; VpaDespesa: string);
var
I,
X,
VpfProximoTitulo,
VpfLancamento : Integer;
VpfDataIni,
VpfDataFim,
VpfNovaDataVencimento: TDateTime;
begin
// Posiciona no último título a ser copiado.
AdicionaSQLAbreTabela(AUX, ' SELECT * FROM CADCONTASAPAGAR CP, MOVCONTASAPAGAR MCP, CADDESPESAS DSP ' +
' WHERE CP.I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) +
' AND CP.I_COD_DES = ' + VpaDespesa +
' AND CP.I_EMP_FIL = MCP.I_EMP_FIL ' +
' AND CP.I_EMP_FIL = DSP.I_EMP_FIL ' +
' AND CP.I_LAN_APG = MCP.I_LAN_APG ' +
' AND CP.I_COD_DES = DSP.I_COD_DES ' +
' ORDER BY CP.I_EMP_FIL, CP.I_LAN_APG DESC ');
// Se existir a despesa.
if (not AUX.EOF) then
begin
AUX.First; // Posiciona no último pois é DESC.
// Acha o primeiro e o último dia do proximo mês.
VpfDataIni:=PrimeiroDiaProximoMes;
VpfDataFim:=UltimoDiaMes(VpfDataIni);
for X:=1 to VpaQtdMesesInc do
begin
// Nova data de vencimento das parcelas posteriores.
VpfNovaDataVencimento:=IncDia(VpfDataIni, (VpaDiaVencimento - 1));
VpfLancamento := ExisteDespesaPeriodo(VpaDespesa, VpfDataIni, VpfDataFim);
// Se achar atualizar a data de vencimento e o valor, senão, criar com estes valores.
if ( VpfLancamento > 0) then
begin
if Config.AtualizarDespesas then // Atualiza todas as depesas fixas que não foram baixas.
AlteraDespesa(VpfLancamento, VpfNovaDataVencimento, VpaValor);
end
else
begin
// Criar a despesa com o novo valor e data de vencimento
// Acha o próximo código a ser escolhido.
VpfProximoTitulo:=ProximoCodigoFilial('CadContasAPagar', 'I_LAN_APG', 'I_EMP_FIL', Varia.CodigoEmpFil,VprBaseDados );
// TABELA DE CABEÇALHO.
AdicionaSQLAbreTabela(AUX1,' SELECT * FROM CADCONTASAPAGAR ');
InserirReg(AUX1);
CarregaCAD(Campos);
for I := 0 to (Campos.Count - 1) do
AUX1.FieldByName(Campos.Strings[I]).Value := AUX.fieldByName(Campos.Strings[I]).Value;
AUX1.FieldByName('I_LAN_APG').AsInteger:=VpfProximoTitulo;
AUX1.FieldByName('C_FLA_DES').AsString:='S'; // Identifica como despesa fixa.
//atualiza a data de alteracao para poder exportar
AUX1.FieldByName('D_ULT_ALT').AsDateTime := Date;
GravaReg(AUX1);
// TABELA DE MOVIMENTAÇÃO.
AdicionaSQLAbreTabela(AUX1,' SELECT * FROM MOVCONTASAPAGAR ');
InserirReg(AUX1);
CarregaMOV(Campos);
for I := 0 to Campos.Count - 1 do
AUX1.FieldByName(Campos.Strings[I]).Value := AUX.fieldByName(Campos.Strings[I]).Value;
AUX1.FieldByName('I_LAN_APG').AsInteger:=VpfProximoTitulo;
// Valor Média.
AUX1.FieldByName('N_VLR_DUP').AsFloat:=VpaValor;
// Nova data de vencimento.
AUX1.FieldByName('D_DAT_VEN').AsDateTime:=VpfNovaDataVencimento;
//atualiza a data de alteracao para poder exportar
AUX1.FieldByName('D_ULT_ALT').AsDateTime := Date;
GravaReg(AUX1);
end;
// IMCREMENTAR O PERÍODO.
VpfDataIni:=IncMes(VpfDataIni, 1); // Muda para o próximo mês;
VpfDataFim:=UltimoDiaMes(VpfDataIni);
end;
end;
end;
{ ***** Atualizar a despesa com o novo valor e data de vencimento ***** }
procedure TFuncoesDespesas.AlteraDespesa(VpaLancamento: Integer;
VpaNovaDataVencimento: TDateTime; VpaValor:Double);
begin
LimpaSQLTabela(AUX1);
AdicionaSQLTabela(AUX1,
' UPDATE MOVCONTASAPAGAR SET ' +
' D_DAT_VEN = ''' + DataToStrFormato(AAAAMMDD, VpaNovaDataVencimento, '/') + ''', ' +
' N_VLR_DUP = ' + SubstituiStr(FloatToStr(VpaValor),',','.') +
' , D_ULT_ALT = '+ SQLTextoDataAAAAMMMDD(DATE)+
' WHERE I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) +
' AND I_LAN_APG = ' + IntToStr(VpaLancamento));
AUX1.ExecSQL;
end;
{ ***** verifica se existe uma despesa no período informado ***** }
function TFuncoesDespesas.ExisteDespesaPeriodo(VpaDespesa: string;
VpaDataInicio, VpaDataFim: TDateTime): Integer;
begin
AdicionaSQLAbreTabela(AUX1,
' SELECT CP.I_LAN_APG FROM CADCONTASAPAGAR CP KEY JOIN MOVCONTASAPAGAR MCP ' +
' WHERE CP.I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) +
' AND CP.I_COD_DES = ' + VpaDespesa +
' AND MCP.D_DAT_VEN BETWEEN ''' + DataToStrFormato(AAAAMMDD, VpaDataInicio, '/') +
''' AND ''' + DataToStrFormato(AAAAMMDD, VpaDataFim, '/') + '''');
Result:=AUX1.FieldByName('I_LAN_APG').AsInteger;
end;
{ ***** gera as despesas futuras ***** }
function TFuncoesDespesas.GeraDespesasFixas(TituloAPagar: Integer): Boolean;
var
I,
VpfMeses,
VpfQuantidade,
VpfProximoTitulo : Integer;
VpfDataVencimento : TDateTime;
begin
Result:=True;
AdicionaSQLAbreTabela(AUX, ' SELECT * FROM CADCONTASAPAGAR CP, MOVCONTASAPAGAR MCP, CADDESPESAS DSP ' +
' WHERE CP.I_EMP_FIL = ' + IntToStr(Varia.CodigoEmpFil) +
' AND CP.I_LAN_APG = ' + IntToStr(TituloAPagar) +
' AND CP.I_EMP_FIL = MCP.I_EMP_FIL ' +
' AND CP.I_EMP_FIL = DSP.I_EMP_FIL ' +
' AND CP.I_LAN_APG = MCP.I_LAN_APG ' +
' AND CP.I_COD_DES = DSP.I_COD_DES ');
if (not AUX.EOF) then
begin
VpfMeses := AUX.FieldByName('I_MES_GER').AsInteger;
VpfDataVencimento:=AUX.FieldByName('D_DAT_VEN').AsDateTime;
for VpfQuantidade := 1 to VpfMeses do
begin
// Incrementa em 1 mês a data de vencimento.
VpfDataVencimento:=IncMes(VpfDataVencimento, 1);
// Acha o próximo código a ser escolhido.
VpfProximoTitulo:=ProximoCodigoFilial('CadContasAPagar', 'I_LAN_APG', 'I_EMP_FIL', Varia.CodigoEmpFil,VprBaseDados);
// TABELA DE CABEÇALHO.
// Aqui contém um erro que deve ser achado ...
CAD.close;
AdicionaSQLAbreTabela(CAD,' SELECT * FROM CADCONTASAPAGAR ');
InserirReg(CAD);
//atualiza a data de alteracao para poder exportar
CAD.FieldByName('D_ULT_ALT').AsDateTime := Date;
CAD.FieldByName('I_LAN_APG').AsInteger := VpfProximoTitulo;
CarregaCAD(Campos);
for I := 0 to (Campos.Count - 1) do
CAD.FieldByName(Campos.Strings[I]).Value := AUX.fieldByName(Campos.Strings[I]).Value;
CAD.FieldByName('C_FLA_DES').AsString := 'S'; // Identifica como despesa fixa.
GravaReg(CAD);
// TABELA DE MOVIMENTAÇÃO.
AdicionaSQLAbreTabela(CAD,' SELECT * FROM MOVCONTASAPAGAR ');
InserirReg(CAD);
CarregaMOV(Campos);
for I := 0 to Campos.Count - 1 do
CAD.FieldByName(Campos.Strings[I]).Value := AUX.fieldByName(Campos.Strings[I]).Value;
CAD.FieldByName('I_LAN_APG').AsInteger:=VpfProximoTitulo;
CAD.FieldByName('D_DAT_VEN').AsDateTime:=VpfDataVencimento;
CAD.FieldByName('L_OBS_APG').AsString := AUX.FieldByName('L_OBS_APG').AsString + ' -> Despesa gerada automaticamente pelo sistema. ';
//atualiza a data de alteracao para poder exportar
CAD.FieldByName('D_ULT_ALT').AsDateTime := Date;
GravaReg(CAD);
end;
end
else Result := False;
end;
{ ***** carrega o TStringList com os campos da tabelas de movimentação ***** }
procedure TFuncoesDespesas.CarregaMOV(VpaTstringMOV: TStringList);
begin
VpaTstringMOV.Clear;
VpaTstringMOV.Add('I_EMP_FIL');
VpaTstringMOV.Add('I_NRO_PAR');
VpaTstringMOV.Add('C_NRO_CON');
VpaTstringMOV.Add('I_LAN_BAC');
VpaTstringMOV.Add('C_NRO_DUP');
VpaTstringMOV.Add('N_VLR_DUP');
VpaTstringMOV.Add('N_VLR_DES');
VpaTstringMOV.Add('N_PER_JUR');
VpaTstringMOV.Add('N_PER_MOR');
VpaTstringMOV.Add('N_PER_MUL');
VpaTstringMOV.Add('I_COD_USU');
VpaTstringMOV.Add('N_VLR_ACR');
VpaTstringMOV.Add('N_PER_DES');
VpaTstringMOV.Add('C_NRO_DOC');
VpaTstringMOV.Add('N_VLR_JUR');
VpaTstringMOV.Add('N_VLR_MOR');
VpaTstringMOV.Add('N_VLR_MUL');
VpaTstringMOV.Add('I_COD_FRM');
VpaTstringMOV.Add('D_CHE_VEN');
VpaTstringMOV.Add('C_BAI_BAN');
VpaTstringMOV.Add('C_FLA_PAR');
VpaTstringMOV.Add('I_PAR_FIL');
VpaTstringMOV.Add('C_DUP_CAN');
VpaTstringMOV.Add('I_COD_MOE');
end;
{ ***** carrega o TStringList com os campos da tabelas de cabeçalho ***** }
procedure TFuncoesDespesas.CarregaCAD(VpaTstringCAD: TStringList);
begin
VpaTstringCAD.Clear;
VpaTstringCAD.Add('I_EMP_FIL');
VpaTstringCAD.Add('I_COD_CLI');
VpaTstringCAD.Add('I_NRO_NOT');
VpaTstringCAD.Add('I_COD_DES');
VpaTstringCAD.Add('C_CLA_PLA');
VpaTstringCAD.Add('I_COD_EMP');
VpaTstringCAD.Add('D_DAT_MOV');
VpaTstringCAD.Add('D_DAT_EMI');
VpaTstringCAD.Add('N_VLR_TOT');
VpaTstringCAD.Add('I_QTD_PAR');
VpaTstringCAD.Add('I_COD_USU');
VpaTstringCAD.Add('N_VLR_MOR');
VpaTstringCAD.Add('N_VLR_JUR');
VpaTstringCAD.Add('I_SEQ_NOT');
end;
end.
|
unit Dropper;
{***********************************************}
{ }
{ TFileDropper }
{ Copyright ©1999 Lloyd Kinsella Software. }
{ }
{ Version 1.0 }
{ }
{ DO NOT MODIFY OR REMOVE THIS HEADER! }
{ }
{***********************************************}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ShellAPI;
type
TOnDrop = procedure (Sender: TObject; Filename: String) of object;
type
TFileDropper = class(TComponent)
private
{ Private declarations }
FWndProcInstance: Pointer;
FDefProc: LongInt;
FDropSite: TWinControl;
FOnDrop: TOnDrop;
FAllowDir: Boolean;
FSubFolder: Boolean;
procedure WndProc(var Message: TMessage);
procedure DropFile(Drop: HDROP);
procedure Add(Path: String);
procedure AddFolder(Path: String);
function IsDirectory(Path: String): Boolean;
protected
{ Protected declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
public
{ Public declarations }
published
{ Published declarations }
property DropSite: TWinControl read FDropSite write FDropSite;
property OnDrop: TOnDrop read FOnDrop write FOnDrop;
property AllowDir: Boolean read FAllowDir write FAllowDir;
property SubFolders: Boolean read FSubFolder write FSubFolder;
end;
procedure Register;
implementation
constructor TFileDropper.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAllowDir := False;
FSubFolder := False;
end;
destructor TFileDropper.Destroy;
begin
inherited Destroy;
end;
procedure TFileDropper.WndProc(var Message: TMessage);
begin
if Message.Msg = WM_DROPFILES then
begin
DropFile(Message.WParam);
Message.Result := 0;
end
else
Message.Result := CallWindowProc(Pointer(FDefProc),FDropSite.Handle,Message.Msg,
Message.WParam, Message.LParam);
end;
procedure TFileDropper.Loaded;
var
Wnd: HWND;
begin
inherited Loaded;
if not (csDesigning in ComponentState) and (FDropSite <> nil) then
begin
Wnd := FDropSite.Handle;
FWndProcInstance := MakeObjectInstance(WndProc);
FDefProc := SetWindowLong(Wnd,GWL_WNDPROC,LongInt(FWndProcInstance));
DragAcceptFiles (Wnd, True);
end;
end;
procedure TFileDropper.DropFile(Drop: HDROP);
var
I, NumFiles: Integer;
lpszFileName: array [0..255] of Char;
begin
NumFiles := DragQueryFile(Drop,$FFFFFFFF,nil,0);
for I := 0 to NumFiles - 1 do
begin
DragQueryFile(Drop,I,lpszFileName,SizeOf(lpszFileName));
Add(StrPas(lpszFileName));
end;
DragFinish(Drop);
end;
procedure TFileDropper.Add(Path: String);
begin
if IsDirectory(Path) = False then
begin
if Assigned(FOnDrop) then FOnDrop(Self,Path);
end
else
if AllowDir then
begin
AddFolder(Path);
end;
end;
procedure TFileDropper.AddFolder(Path: String);
var
I: Integer;
SearchRec: TSearchRec;
begin
I := FindFirst(Path + '\*.*',faAnyFile,SearchRec);
while I = 0 do
begin
if (SearchRec.Name[1] <> '.') then
begin
if IsDirectory(Path + '\' + SearchRec.Name) = False then
begin
if Assigned(FOnDrop) then FOnDrop(Self,Path + '\' + SearchRec.Name);
end
else
if FSubFolder = True then
begin
AddFolder(Path + '\' + SearchRec.Name);
end;
end;
I := FindNext(SearchRec);
end;
FindClose(SearchRec);
end;
function TFileDropper.IsDirectory(Path: String): Boolean;
begin
if (FileGetAttr(Path) and faDirectory) = 0 then
begin
Result := False;
end
else
Result := True;
end;
procedure Register;
begin
RegisterComponents('Samples', [TFileDropper]);
end;
end.
|
////////////////////////////////////////////
// Классы для опроса удаленного сервера
////////////////////////////////////////////
unit RecordsForRmSrv;
interface
uses Windows, Classes, SysUtils, Math, GMSqlQuery, GMGlobals, DateUtils;
type
TRemoteSrvRecord = class(TCollectionItem)
private
procedure CreateRequest(var bufs: TTwoBuffers);
public
ID_Prm: int;
sRemoteSrv: string;
RemotePort: int;
ID_Obj, ID_Device: int;
N_Car,
ID_DevType, DevNumber,
ID_Src, N_Src: int;
bRenewed: bool;
uDTLast: LongWord;
constructor Create(Collection: TCollection); override;
end;
TRemoteSrvRecords = class (TCollection)
private
qLst, qDT, qW: TGMSqlQuery;
iCurrentID: int;
tLastRead: TDateTime;
function GetRec(i: int): TRemoteSrvRecord;
procedure ReadInitialDT(r: TRemoteSrvRecord);
procedure AddRmSrvRecord;
procedure ClearUnused;
procedure ResetRenewed();
function AddUnique(ID_Prm: int): TRemoteSrvRecord;
public
procedure RequestNext(var bufs: TTwoBuffers);
procedure ReadRemoteRecords();
constructor Create();
destructor Destroy; override;
property Rec[i: int]: TRemoteSrvRecord read GetRec; default;
function RecByParams(N_Car, DevType, NDevice, PrmType, NPrm: int): TRemoteSrvRecord;
end;
implementation
uses GMConst, ProgramLogFile;
const
SQLConst_SelectParamDevObj =
'select * from Params p join Devices d on p.ID_Device = d.ID_Device ' +
' join Objects o on o.ID_Obj = d.ID_Obj ' +
' where p.ID_PT > 0 ';
{ TRemoteSrvRecord }
constructor TRemoteSrvRecord.Create(Collection: TCollection);
begin
inherited;
bRenewed := true;
uDTLast := 0;
end;
procedure TRemoteSrvRecord.CreateRequest(var bufs: TTwoBuffers);
begin
bufs.BufSend[0] := 231;
bufs.BufSend[1] := 180;
bufs.LengthSend := WriteUINT(bufs.BufSend, 2, N_Car);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, ID_DevType);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, DevNumber);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, ID_Src);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, N_Src);
bufs.LengthSend := WriteByte(bufs.BufSend, bufs.LengthSend, 0);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, uDTLast);
bufs.LengthSend := WriteUINT(bufs.BufSend, bufs.LengthSend, uDTLast + 3600 * 12);
end;
{ TRemoteSrvRecords }
function TRemoteSrvRecords.AddUnique(ID_Prm: int): TRemoteSrvRecord;
var i: int;
begin
for i := 0 to Count - 1 do
if Rec[i].ID_Prm = ID_Prm then
begin
Result := Rec[i];
Result.bRenewed := true;
Exit;
end;
Result := TRemoteSrvRecord(Add());
Result.ID_Prm := ID_Prm;
end;
procedure TRemoteSrvRecords.AddRmSrvRecord();
var r: TRemoteSrvRecord;
begin
r := AddUnique(qLst.FieldByName('ID_Prm').AsInteger);
r.sRemoteSrv := qLst.FieldByName('RemoteSrv').AsString;
r.RemotePort := qLst.FieldByName('RemotePort').AsInteger;
r.ID_Obj := qLst.FieldByName('ID_Obj').AsInteger;
r.ID_Device := qLst.FieldByName('ID_Device').AsInteger;
r.N_Car := qLst.FieldByName('N_Car').AsInteger;
r.ID_DevType := qLst.FieldByName('ID_DevType').AsInteger;
r.DevNumber := qLst.FieldByName('Number').AsInteger;
r.ID_Src := qLst.FieldByName('ID_Src').AsInteger;
r.N_Src := qLst.FieldByName('N_Src').AsInteger;
ReadInitialDT(r);
end;
procedure TRemoteSrvRecords.ClearUnused();
var i: int;
begin
for i := Count - 1 downto 0 do
if not Rec[i].bRenewed then
Delete(i);
end;
constructor TRemoteSrvRecords.Create();
begin
inherited Create(TRemoteSrvRecord);
qLst := TGMSqlQuery.Create();
qDT := TGMSqlQuery.Create();
qW := TGMSqlQuery.Create();
iCurrentID := 0;
tLastRead := 0;
end;
destructor TRemoteSrvRecords.Destroy;
begin
qLst.Free();
qDT.Free();
qW.Free();
inherited;
end;
function TRemoteSrvRecords.GetRec(i: int): TRemoteSrvRecord;
begin
Result := TRemoteSrvRecord(Items[i]);
end;
procedure TRemoteSrvRecords.ResetRenewed;
var i: int;
begin
for i := 0 to Count - 1 do
Rec[i].bRenewed := false;
end;
procedure TRemoteSrvRecords.ReadInitialDT(r: TRemoteSrvRecord);
begin
if r.uDTLast > 0 then Exit;
try
qDT.Close();
qDT.SQL.Text := ' select UTime from Vals ' +
' where ID_Prm = ' + IntToStr(r.ID_Prm) +
' order by UTime desc limit 1';
qDT.Open();
if not qDT.Eof then
r.uDTLast := qDT.FieldByName('UTime').AsInteger;
except
on e: Exception do
ProgramLog().AddException('TGMRemoteSrvDataThread.qDT - ' + e.Message);
end;
qDT.Close();
end;
procedure TRemoteSrvRecords.ReadRemoteRecords();
begin
ResetRenewed();
try
qLst.Close();
qLst.SQL.Text := SQLConst_SelectParamDevObj +
' and o.ObjType = ' + IntToStr(OBJ_TYPE_REMOTE_SRV) +
' order by o.ID_Obj';
qLst.Open();
while not qLst.Eof do
begin
AddRmSrvRecord();
qLst.Next();
end;
except
on e: Exception do
ProgramLog().AddException('TGMRemoteSrvDataThread.qLst - ' + e.Message);
end;
tLastRead := Now();
qLst.Close();
ClearUnused();
end;
procedure TRemoteSrvRecords.RequestNext(var bufs: TTwoBuffers);
var i: int;
function DoRequest(i: int): bool;
begin
ProgramLog().AddMessage('TRemoteSrvRecords.RequestNext - DoRequest');
Result := NowGM() - UINT(IfThen(NowIsSummer(), 3600, 0)) - Rec[i].uDTLast >= 2 * 60;
if Result then
begin
ProgramLog().AddMessage('TRemoteSrvRecords.RequestNext - CreateRequest');
Rec[i].CreateRequest(bufs);
iCurrentID := i + 1;
end;
end;
begin
if Abs(Now() - tLastRead) > 60 * OneSecond then
ReadRemoteRecords();
if Count = 0 then Exit;
if iCurrentID >= Count then
iCurrentID := 0;
bufs.LengthSend := 0;
for i := iCurrentID to Count - 1 do
if DoRequest(i) then break;
// дошли до конца, ничего не нашли, попробуем сначала
if bufs.LengthSend = 0 then
begin
for i := 0 to Count - 1 do
if DoRequest(i) then break;
end;
end;
function TRemoteSrvRecords.RecByParams(N_Car, DevType, NDevice, PrmType, NPrm: int): TRemoteSrvRecord;
var i: int;
begin
Result := nil;
for i := 0 to Count - 1 do
begin
if (Rec[i].N_Car = N_Car)
and (Rec[i].ID_DevType = DevType)
and (Rec[i].DevNumber = NDevice)
and (Rec[i].ID_Src = PrmType)
and (Rec[i].N_Src = NPrm) then
begin
Result := Rec[i];
break;
end;
end;
end;
end.
|
unit uNSM;
interface
uses
Windows, Forms, MultiMon, ExtCtrls, Classes;
type
Tfrm = class(TForm)
tim: TTimer;
procedure timTimer(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm: Tfrm;
implementation
{$R *.dfm}
var //save runtime stack & other overheads via global vars instead of passed params
prev:TPoint; //stores where the mouse was last frame, so we can see what direction it's moving in
const
hoplimit:integer=30; //if delta greater than this in 50ms then is either computer controlled or will hop anyway!
range:integer=2; //casting about from mouse position this number of pixels
procedure CheckMouse;
var
pt:TPoint; //where the mouse is, and where it's going!
m:HMONITOR; //for quick access to the active monitor's dimensions
function CheckForMove:boolean; //returns true when mouse has to move
{Pre:: m:HMONITOR; is initialised
Post:: pt:TPoint; holds new mouse position
This function is only called once, but not embedded so I can quickly "exit" the checks}
var
mi:TMonitorInfo; //get info for monitor's bounds
br:TRect; //just an alias really
function CanMove(x,y:integer):boolean; //tests if the new coords are sound,
var // on a new screen, and sets pt if it is
dp:TPoint; //storage of potential destination
dm:HMONITOR; //destination monitor, if exists and not same as current monitor
begin
result:=false; //fails until proven true
dp.X:=x; dp.Y:=y;
dm:=MonitorFromPoint(dp,MONITOR_DEFAULTTONULL); //what monitor is the projection on?
if (dm<>0) and (dm<>m) then //valid monitor and different to our current monitor
begin
pt:=dp; //we want to be here!
result:=true;
end;
end; //End CanMove
begin //Begin CheckForMove
{
//The Trevor special
if (pt.X=0) and (pt.Y<=113) then //top left
begin
pt.X:=-8;
pt.Y:=121;
result:=true;
exit;
end;
if (pt.X=0) and (pt.Y>=1193) then //bottom left
begin
pt.X:=-8;
pt.Y:=1185;
result:=true;
exit;
end;
}
{
//Alice
if (pt.X=0) and (pt.Y<=205) then //top left
begin
pt.X:=-8;
pt.Y:=213;
result:=true;
exit;
end;
if (pt.X=0) and (pt.Y>=1285) then //bottom left
begin
pt.X:=-8;
pt.Y:=1277;
result:=true;
exit;
end;
if (pt.X=2559) and (pt.Y<=347) then //top right
begin
pt.X:=2567;
pt.Y:=355;
result:=true;
exit;
end;
if (pt.X=2559) and (pt.Y>=1115) then //bottom right
begin
pt.X:=2567;
pt.Y:=1107;
result:=true;
exit;
end;
}
{
//Mine
if (pt.X=1279) and (pt.Y>=900) then //bottom left
begin
pt.X:=1280+range;
pt.Y:=900-range;
result:=true;
exit;
end;
}
//stochastic ability: it's not stuck in any corner, but see if it's approaching one
result:=(pt.X-prev.X>-hoplimit) and (pt.X-prev.X<hoplimit) and //limit hop check range
(pt.Y-prev.Y>-hoplimit) and (pt.Y-prev.Y<hoplimit) and // note short-circuit faster than abs()
CanMove(pt.X*2-prev.X,pt.Y*2-prev.Y); //on it's given trajectory, will it cross a monitor?
if result then //the check above will now cover almost all hops, but keep rest of code for completeness
exit;
//corner checks: check diagonal then horizonal then vertical.
mi.cbSize:=SizeOf(mi); //prepare destination data for next call
GetMonitorInfo(m,@mi); //get the bounds rectangle for the monitor
br:=mi.rcMonitor; //check corners first, then edges.
if pt.Y=br.Top then //at top, do corners then check above
begin
if pt.X=br.Left then //top-left
begin
result:=CanMove(br.Left-range,br.Top-range); //check diagonal hop first
if not result then
if prev.X>=pt.X then //moving left
result:=CanMove(br.Left-range,br.Top+range);
if not result then
if prev.Y>=pt.Y then //moving up
result:=CanMove(br.Left+range,br.Top-range);
exit; //whether found or not, as this condition was true then all below cannot be
end;
if pt.X=br.Right-1 then //top-right
begin //code logic repeated as above
result:=CanMove(br.Right-1+range,br.Top-range);
if not result then
if prev.X<=pt.X then //moving right
result:=CanMove(br.Right-1+range,br.Top+range);
if not result then
if prev.Y>=pt.Y then //moving up
result:=CanMove(br.Right-1-range,br.Top-range);
exit; //save CPU cycles, the quicker we escape this code-block the better
end;
if prev.y>=pt.y then //top edge and moving up
result:=CanMove(pt.x,br.Top-range);
exit; //no more "tops" to check, quit now
end;
if pt.Y=br.Bottom-1 then //at bottom
begin
if pt.X=br.Left then //bottom-left
begin
result:=CanMove(br.Left-range,br.Bottom-1+range);
if not result then
if prev.X>=pt.X then //moving left
result:=CanMove(br.Left-range,br.Bottom-range);
if not result then
if prev.Y<=pt.Y then //moving down
result:=CanMove(br.Left+range,br.Bottom-1+range);
exit;
end;
if pt.X=br.Right-1 then //bottom-right
begin
result:=CanMove(br.Right-1+range,br.Bottom-1+range);
if not result then
if prev.X<=pt.X then //moving right
result:=CanMove(br.Right-1+range,br.Bottom-1-range);
if not result then
if prev.Y<=pt.Y then //moving down
result:=CanMove(br.Right-1-range,br.Bottom-1+range);
exit;
end; //end of all corner checks, now to check below
if prev.y<=pt.y then //bottom edge and moving down
result:=CanMove(pt.x,br.Bottom-1+range);
exit;
end; //top and bottom covered its corners edges, so now only need to check sides
if (pt.x=br.Right-1) and (prev.x<=pt.x) then //right edge and moving right
begin //i am not checking if the mouse is dragging a window, just hop it anyway!
result:=CanMove(br.Right-1+range,pt.y);
exit; //note this code could be done with a list of "if then else"
end; // instead of exits - but harder to read even if shorter
if (pt.x=br.Left) and (prev.x>=pt.x) then //left edge and moving left
begin
result:=CanMove(br.Left-range,pt.y);
exit; //Superfluous exit, but here in case more code goes in below
end;
end; //End CheckForMove
begin //Begin CheckMouse
try
GetCursorPos(pt); //get where our mouse is now, var used in CheckForMove above too
if (pt.X=prev.X) and (pt.Y=prev.Y) then //mouse not moving, don't check any further
exit;
m:=MonitorFromPoint(pt,MONITOR_DEFAULTTONULL); //what monitor our mouse is on?
if m=0 then //Danger, danger, Will Robinson.
exit;
if CheckForMove then //draws from pt & m, and sets new pt if moving
SetCursorPos(pt.X,pt.Y); //something about the whole point of this application!
prev:=pt; //our current point, whether its original or where we placed it, is stored
finally //user locked screen / logged out? or just some random unhappiness
end;
end; //End CheckMouse
procedure Tfrm.timTimer(Sender: TObject);
begin
CheckMouse;
end;
procedure Tfrm.FormActivate(Sender: TObject);
begin
{$IFDEF FPC}
Hide; //hide this form
ShowInTaskBar:=stNever; //and remove off taskbar
{$ELSE}
ShowWindow(handle,sw_hide); //hide this form
ShowWindow(application.handle,sw_hide); //and remove off taskbar
{$ENDIF}
end;
end.
|
unit AServicos;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, ComCtrls, DBTables, Db, DBCtrls, Grids, DBGrids,
Buttons, Menus, formularios, PainelGradiente,
Tabela, Componentes1, LabelCorMove, Localizacao, Mask,
EditorImagem, ImgList, numericos, UnClassificacao, FMTBcd, SqlExpr, DBClient;
type
TFServicos = class(TFormularioPermissao)
Splitter1: TSplitter;
CadClassificacao: TSQL;
Imagens: TImageList;
CadServicos: TSQL;
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
Arvore: TTreeView;
PanelColor4: TPanelColor;
BAlterar: TBitBtn;
BExcluir: TBitBtn;
BServicos: TBitBtn;
BitBtn1: TBitBtn;
Localiza: TConsultaPadrao;
BClasssificao: TBitBtn;
BFechar: TBitBtn;
BConsulta: TBitBtn;
PopupMenu1: TPopupMenu;
NovaClassificao1: TMenuItem;
NovoProduto1: TMenuItem;
N1: TMenuItem;
Alterar1: TMenuItem;
Excluir1: TMenuItem;
Consultar1: TMenuItem;
Localizar1: TMenuItem;
N2: TMenuItem;
ImageList1: TImageList;
Aux: TSQLQuery;
EditColor1: TEditColor;
CAtiPro: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure ArvoreExpanded(Sender: TObject; Node: TTreeNode);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ArvoreChange(Sender: TObject; Node: TTreeNode);
procedure ArvoreCollapsed(Sender: TObject; Node: TTreeNode);
Procedure Excluir(Sender : TObject);
procedure BAlterarClick(Sender: TObject);
procedure BExcluirClick(Sender: TObject);
procedure BClasssificaoClick(Sender: TObject);
procedure BServicosClick(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure BConsultaClick(Sender: TObject);
procedure ArvoreDblClick(Sender: TObject);
procedure ArvoreKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ArvoreKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure AtiProClick(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
VprListar: Boolean;
VprQtdNiveis: Byte;
VprVetorMascara: array [1..6] of byte;
VprVetorNode: array [0..6] of TTreeNode;
VprPrimeiroNode: TTreeNode;
function DesmontaMascara(var VpaVetor: array of byte; VpaMascara: String): byte;
procedure CadastraClassificacao;
function LimpaArvore: TTreeNode;
procedure CarregaClassificacao(VpaVetorInfo : array of byte);
procedure CarregaServico(VpaNivel: Byte; VpaCodClassificacao: String; VpaNodeSelecao: TTreeNode);
procedure RecarregaLista;
procedure CadatraServico;
procedure Alterar(Sender: TObject;Alterar : Boolean);
public
end;
var
FServicos: TFServicos;
implementation
uses
APrincipal, Fundata, constantes, funObjeto, FunSql, constMsg, funstring,
ANovaClassificacao, ANovoServico;
{$R *.DFM}
{***********************No fechamento do Formulario****************************}
procedure TFServicos.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CadServicos.Close;
CadClassificacao.Close;
Action:= CaFree;
end;
{************************Quanto criado novo formulario*************************}
procedure TFServicos.FormCreate(Sender: TObject);
begin
FillChar(VprVetorMascara, SizeOf(VprVetorMascara), 0);
VprListar:= True;
CadServicos.Open;
VprQtdNiveis:= DesmontaMascara(VprVetorMascara, varia.MascaraClaSer); // busca em constantes
CarregaClassificacao(VprVetorMascara);
Arvore.Color:= EditColor1.Color;
Arvore.Font:= EditColor1.Font;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Chamadas diversas dos Tree
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*****cada deslocamento no TreeView causa uma mudança na lista da direita******}
procedure TFServicos.ArvoreChange(Sender: TObject; Node: TTreeNode);
begin
if VprListar then
begin
if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then
CarregaServico(node.Level,TClassificacao(TTreeNode(node).Data).CodClassificacao, node);
Arvore.Update;
end;
end;
{ *******************Cada vez que expandir um no*******************************}
procedure TFServicos.ArvoreExpanded(Sender: TObject; Node: TTreeNode);
begin
CarregaServico(node.Level,TClassificacao(TTreeNode(node).Data).CodClassificacao,node);
if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then
begin
Node.SelectedIndex:= 1;
Node.ImageIndex:= 1;
end;
end;
{********************Cada vez que voltar a expanção de um no*******************}
procedure TFServicos.ArvoreCollapsed(Sender: TObject; Node: TTreeNode);
begin
if TClassificacao(TTreeNode(node).Data).tipo = 'CL' then
begin
Node.SelectedIndex:=0;
Node.ImageIndex:=0;
end;
end;
{ **************** se presionar a setas naum atualiza movimentos ************ }
procedure TFServicos.ArvoreKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key in[37..40] then
VprListar := False;
end;
{ ************ apos soltar setas atualiza movimentos ************************ }
procedure TFServicos.ArvoreKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
VprListar := true;
ArvoreChange(sender,arvore.Selected);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações de localizacao do servico
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{************************ localiza o servico **********************************}
procedure TFServicos.BitBtn1Click(Sender: TObject);
var
Vpfcodigo, VpfSelect : string;
VpfSomaNivel, VpfNivelSelecao: Integer;
begin
VpfSelect:= ' Select * from cadservico ' +
' where c_nom_ser like ''@%''' +
' order by c_nom_ser ';
Localiza.info.DataBase := Fprincipal.BaseDados;
Localiza.info.ComandoSQL := VpfSelect;
Localiza.info.caracterProcura := '@';
Localiza.info.ValorInicializacao := '';
Localiza.info.CamposMostrados[0] := 'I_cod_SER';
Localiza.info.CamposMostrados[1] := 'c_nom_SER';
Localiza.info.CamposMostrados[2] := '';
Localiza.info.DescricaoCampos[0] := 'Código';
Localiza.info.DescricaoCampos[1] := 'Nome Serviço';
Localiza.info.DescricaoCampos[2] := '';
Localiza.info.TamanhoCampos[0] := 8;
Localiza.info.TamanhoCampos[1] := 40;
Localiza.info.TamanhoCampos[2] := 0;
Localiza.info.CamposRetorno[0] := 'I_cod_ser';
Localiza.info.CamposRetorno[1] := 'C_cod_cla';
Localiza.info.SomenteNumeros := false;
Localiza.info.CorFoco := FPrincipal.CorFoco;
Localiza.info.CorForm := FPrincipal.CorForm;
Localiza.info.CorPainelGra := FPrincipal.CorPainelGra;
Localiza.info.TituloForm := ' Localizar Serviços ';
if (Localiza.execute) and (localiza.retorno[0] <> '') Then
begin
VpfSomaNivel := 1;
VpfNivelSelecao := 1;
Vprlistar := false;
arvore.Selected := VprPrimeiroNode;
while VpfSomaNivel <= Length(localiza.retorno[1]) do
begin
Vpfcodigo:= copy(localiza.retorno[1], VpfSomaNivel, VprVetorMascara[VpfNivelSelecao]);
VpfSomaNivel := VpfSomaNivel + VprVetorMascara[VpfNivelSelecao];
arvore.Selected := arvore.Selected.GetNext;
while TClassificacao(arvore.Selected.Data).CodClassificacoReduzido <> VpfCodigo do
arvore.Selected := arvore.Selected.GetNextChild(arvore.selected);
inc(VpfNivelSelecao);
end;
CarregaServico(arvore.selected.Level,TClassificacao(arvore.selected.Data).CodClassificacao,arvore.selected);
arvore.Selected := arvore.Selected.GetNext;
while TClassificacao(arvore.Selected.Data).CodProduto <> localiza.retorno[0] do
arvore.Selected:= arvore.Selected.GetNextChild(arvore.selected);
end;
Vprlistar := true;
ArvoreChange(sender,arvore.Selected);
self.ActiveControl := arvore;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos da classificacao
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******Desmonata a mascara pardão para a configuração das classificações*******}
function TFServicos.DesmontaMascara(var VpaVetor: array of byte; VpaMascara: String): Byte;
var
VpfX, VpfPosicao: Byte;
begin
VpfPosicao:= 0;
VpfX:= 0;
while Pos('.', VpaMascara) > 0 do
begin
VpaVetor[VpfX]:= (Pos('.', VpaMascara)-VpfPosicao)-1;
inc(VpfX);
VpfPosicao:= Pos('.', VpaMascara);
VpaMascara[Pos('.', VpaMascara)]:= '*';
end;
VpaVetor[VpfX]:= length(VpaMascara)-VpfPosicao;
VpaVetor[VpfX+1]:= 1;
DesmontaMascara:= VpfX+1;
end;
{********************* cadastra uma nova classificacao ************************}
procedure TFServicos.CadastraClassificacao;
var
VpfDClassificacao: TClassificacao;
begin
if (VprQtdNiveis <= Arvore.Selected.Level) then //acabou os niveis para incluir a nova classificacao
begin
Erro(CT_FimInclusaoClassificacao);
Exit;
end;
VpfDClassificacao:= TClassificacao.Cria;
VpfDClassificacao.CodClassificacao:= TClassificacao(TTreeNode(arvore.Selected).Data).CodClassificacao; // envia o codigo pai para insercao;
FNovaClassificacao:= TFNovaClassificacao.CriarSDI(application,'', Fprincipal.VerificaPermisao('FNovaClassificacao'));
if FNovaClassificacao.Inseri(VpfDClassificacao, VprVetorMascara[arvore.Selected.Level+1],'S') then
begin
VpfDClassificacao.tipo := 'CL';
VpfDClassificacao.DesPathFoto := '';
Arvore.Items.AddChildObject(TTreeNode(arvore.Selected),VpfDClassificacao.CodClassificacoReduzido+' - '+
VpfDClassificacao.NomClassificacao, VpfDClassificacao);
arvore.OnChange(self,arvore.selected);
Arvore.Update;
end
else
VpfDClassificacao.free;
end;
{****************** limpa a arvore e cria o no inicial ************************}
function TFServicos.LimpaArvore : TTreeNode;
var
VpfDClassificacao: TClassificacao;
begin
Arvore.Items.Clear;
VpfDClassificacao:= TClassificacao.Cria;
VpfDClassificacao.CodClassificacao:= '';
VpfDClassificacao.CodClassificacoReduzido:= '';
VpfDClassificacao.Tipo:= 'CL';
Result:= Arvore.Items.AddObject(Arvore.Selected, 'Serviços', VpfDClassificacao);
Result.ImageIndex:= 0;
Result.SelectedIndex:= 0;
end;
{************************carrega Classificacao*********************************}
procedure TFServicos.CarregaClassificacao(VpaVetorInfo : array of byte);
var
VpfNode: TTreeNode;
VpfDClassificacao: TClassificacao;
VpfTamanho, VpfNivel: word;
VpfCodigo: String;
begin
VpfNode:= LimpaArvore; // limpa a arvore e retorna o nó inicial;
VprPrimeiroNode := VpfNode;
VprVetorNode[0]:= VpfNode;
Arvore.Update;
AdicionaSQLAbreTabela(CadClassificacao,'SELECT * FROM CADCLASSIFICACAO'+
' WHERE I_COD_EMP = '+IntToStr(varia.CodigoEmpresa)+
' AND C_TIP_CLA = ''S''' +
' ORDER BY C_COD_CLA ');
while not(CadClassificacao.EOF) do
begin
VpfTamanho:= VpaVetorInfo[0];
VpfNivel:= 0;
while Length(CadClassificacao.FieldByName('C_COD_CLA').AsString)<>VpfTamanho do
begin
inc(VpfNivel);
Vpftamanho:= VpfTamanho+VpaVetorInfo[VpfNivel];
end;
Vpfcodigo:= CadClassificacao.FieldByName('C_COD_CLA').AsString;
VpfDClassificacao:= TClassificacao.Cria;
VpfDClassificacao.CodClassificacao:= CadClassificacao.FieldByName('C_COD_CLA').AsString;
VpfDClassificacao.CodClassificacoReduzido:= copy(Vpfcodigo, (length(Vpfcodigo)-VpaVetorInfo[VpfNivel])+1, VpaVetorInfo[VpfNivel]);
VpfDClassificacao.Tipo:= 'CL';
VpfDClassificacao.ProdutosCarregados:= True;
VpfNode:= Arvore.Items.AddChildObject(VprVetorNode[VpfNivel],VpfDClassificacao.CodClassificacoReduzido+' - '+
CadClassificacao.FieldByName('C_NOM_CLA').AsString,VpfDClassificacao);
VprVetorNode[VpfNivel+1]:= VpfNode;
CadClassificacao.Next;
end;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos dos servicos
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{********************* cadastra um novo servico *******************************}
procedure TFServicos.CadatraServico;
var
VpfDClassificacao: TClassificacao;
VpfNo: TTreeNode;
VpfDescricao, VpfCodServico, VpfCodClassificacao : string;
begin
if (arvore.Selected.Level = 0) then // se estiver no no inicial nao cadastra
begin
erro(CT_ClassificacacaoServicoInvalida);
abort;
end;
if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then // se estiver selecionado um servico nao cadastra pois nao pode cadastrar um servico dentro de outro
begin
erro(CT_ErroInclusaoServico);
abort;
end;
VpfDClassificacao:= TClassificacao.Cria;
VpfCodClassificacao:= TClassificacao(TTreeNode(Arvore.selected).data).CodClassificacao;
FNovoServico := TFNovoServico.CriarSDI(application,'',FPrincipal.VerificaPermisao('FNovoServico'));
if FNovoServico.InsereNovoServico(VpfCodClassificacao, VpfCodServico,VpfDescricao, False) then
begin
VpfDClassificacao.CodClassificacao:= VpfCodClassificacao;
VpfDClassificacao.Tipo:= 'SE';
VpfDClassificacao.ProdutosCarregados := true;
VpfDClassificacao.CodProduto:= VpfCodServico;
Vpfno:= Arvore.Items.AddChildObject(TTreeNode(Arvore.Selected),VpfDClassificacao.CodProduto+' - '+
VpfDescricao, VpfDClassificacao);
Vpfno.ImageIndex := 2;
Vpfno.SelectedIndex := 2;
Arvore.OnChange(Self,arvore.selected);
Arvore.Update;
end;
end;
{**************alteração de Classificação ou o servico*************************}
procedure TFServicos.Alterar(Sender: TObject; Alterar : Boolean);
var
Vpfcodigo, VpfDescricao : string;
VpfDClassificacao: TClassificacao;
begin
if (arvore.Selected.Level=0) then // não é possível alterar o primeiro item
abort;
VpfDClassificacao:= TClassificacao(TTreeNode(arvore.Selected).Data);
if VpfDClassificacao.Tipo = 'CL' then
begin
FNovaClassificacao := TFNovaClassificacao.CriarSDI(application,'',FPrincipal.VerificaPermisao('FNovaClassificacao'));
if FNovaClassificacao.Alterar(VpfDClassificacao,'S',Alterar) then
begin
VpfCodigo:= VpfDClassificacao.CodClassificacoReduzido;
Arvore.Selected.Text:= VpfCodigo + ' - ' + VpfDClassificacao.NomClassificacao;
Arvore.OnChange(Sender,Arvore.Selected);
Arvore.Update;
end;
end
else
if VpfDClassificacao.Tipo = 'SE' then
begin
Vpfcodigo:= VpfDClassificacao.CodProduto;
VpfDescricao:= '';
FNovoServico:= TFNovoServico.CriarSDI(application, '',FPrincipal.VerificaPermisao('FNovoServico'));
if FNovoServico.AlteraServico(VpfDClassificacao.CodClassificacao, VpfCodigo,VpfDescricao, Alterar) then
Arvore.Selected.Text:= VpfCodigo + ' - ' + VpfDescricao;
end;
end;
{****************** carrega os servicos na arvore *****************************}
procedure TFServicos.CarregaServico(VpaNivel: Byte; VpaCodClassificacao: String; VpaNodeSelecao : TTreeNode);
var
VpfNode: TTreeNode;
VpfDClassificacao: TClassificacao;
VpfAtividade : String;
begin
if TClassificacao(TTreeNode(VpaNodeSelecao).Data).ProdutosCarregados then
begin
if CAtiPro.Checked Then
VpfAtividade:= ' AND C_ATI_SER = ''S'''
else
VpfAtividade:= '';
AdicionaSQLAbreTabela(CadServicos,'Select * from CadServico'+
' Where I_COD_EMP = '+IntToStr(varia.CodigoEmpresa)+
' and C_COD_CLA = '''+VpaCodClassificacao+''''+
VpfAtividade +
' Order by I_Cod_Ser');
while not CadServicos.EOF do
begin
VpfDClassificacao:= TClassificacao.Cria;
VpfDClassificacao.CodClassificacao:= VpaCodClassificacao;
VpfDClassificacao.CodProduto:= CadServicos.FieldByName('I_COD_SER').AsString;
VpfDClassificacao.ProdutosCarregados:= True;
VpfDClassificacao.Tipo:= 'SE';
VpfNode:= Arvore.Items.AddChildObject(VpaNodeSelecao, VpfDClassificacao.CodProduto + ' - ' + CadServicos.FieldByName('C_NOM_SER').AsString, VpfDClassificacao);
VprVetorNode[VpaNivel+1]:= VpfNode;
VpfNode.ImageIndex := 2;
VpfNode.SelectedIndex := 2;
CadServicos.Next;
end;
TClassificacao(TTreeNode(VpaNodeSelecao).Data).ProdutosCarregados:= False;
end;
end;
{*****************Exclusão de Classificação e produtos*************************}
procedure TFServicos.Excluir(Sender : TObject);
var
VpfNode: TTreeNode;
begin
if (arvore.Selected.Level=0) then
abort;
VpfNode:= arvore.Selected;
Vprlistar := false;
if (Arvore.Selected.HasChildren) then// Nao permite excluir se possui filhos
begin
erro(CT_ErroExclusaoClassificaca);
arvore.Selected:= VpfNode;
VprListar:= true;
abort;
end;
if confirmacao(CT_DeletarItem) then // verifica se deseja excluir
begin
if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'CL' then
try
// caso seja uma classificacao
ExecutaComandoSql(Aux,'DELETE FROM CADCLASSIFICACAO'+
' WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) +
' and C_COD_CLA='''+ TClassificacao(TTreeNode(arvore.Selected).Data).CodClassificacao+ ''''+
' and C_Tip_CLA = ''S''');
TClassificacao(TTreeNode(arvore.selected).Data).Free;
Arvore.items.Delete(arvore.Selected);
except
Erro(CT_ErroDeletaRegistroPai);
end;
// caso seja um serviço
if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then
begin
try
ExecutaComandoSql(Aux,' DELETE FROM CADSERVICO WHERE I_COD_EMP = ' + IntToStr(varia.CodigoEmpresa) +
' and I_COD_SER ='+ TClassificacao(TTreeNode(arvore.Selected).Data).CodProduto);
TClassificacao(TTreeNode(arvore.selected).Data).Free;
Arvore.items.Delete(arvore.Selected);
except
Erro(CT_ErroDeletaRegistroPai);
end;
end;
VprListar:= True;
Arvore.OnChange(sender,arvore.selected);
end;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos dos botoes
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{***************** cadastra uma nova classificacao ****************************}
procedure TFServicos.BClasssificaoClick(Sender: TObject);
begin
CadastraClassificacao;
end;
{ ***************** altera a mostra entre produtos em atividades ou naum ******}
procedure TFServicos.AtiProClick(Sender: TObject);
begin
RecarregaLista;
end;
{*************Chamada de alteração de produtos ou classificações***************}
procedure TFServicos.BConsultaClick(Sender: TObject);
begin
Alterar(sender,false); // Consulta o servico ou a classificacao
end;
{*************Chamada de alteração de produtos ou classificações***************}
procedure TFServicos.BAlterarClick(Sender: TObject);
begin
Alterar(sender,true); // chamada de alteração
end;
{***************Chama a rotina para cadastrar um novo produto******************}
procedure TFServicos.BServicosClick(Sender: TObject);
begin
CadatraServico;
end;
{****************************Fecha o Formulario corrente***********************}
procedure TFServicos.BFecharClick(Sender: TObject);
begin
Close;
end;
{************Chamada de Exclusão de produtos ou classificações*****************}
procedure TFServicos.BExcluirClick(Sender: TObject);
begin
Excluir(sender);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
eventos diversos
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{*********************** recarrega a lista ************************************}
procedure TFServicos.RecarregaLista;
begin
VprListar := false;
Arvore.Items.Clear;
VprListar := true;
CarregaClassificacao(VprVetorMascara);
end;
{************** quando se da um duplo clique na arvore ************************}
procedure TFServicos.ArvoreDblClick(Sender: TObject);
begin
if TClassificacao(TTreeNode(arvore.Selected).Data).Tipo = 'SE' then
BAlterar.Click;
end;
end.
|
unit ClientFr;
{
This is the client portion of a MIDAS demo. Make sure that you compile and
run the server project before trying to run this probject.
This project demonstrates how to set parameters for a query on the server.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBClient, StdCtrls, DBCtrls, Grids, DBGrids, ExtCtrls, MConnect;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
DBGrid1: TDBGrid;
StartDate: TEdit;
EndDate: TEdit;
DBImage1: TDBImage;
DBMemo1: TDBMemo;
Events: TClientDataSet;
EventsEventNo: TIntegerField;
EventsVenueNo: TIntegerField;
EventsEvent_Name: TStringField;
EventsEvent_Date: TDateField;
EventsEvent_Time: TTimeField;
EventsEvent_Description: TMemoField;
EventsTicket_price: TCurrencyField;
EventsEvent_Photo: TGraphicField;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
ShowEvents: TButton;
Bevel1: TBevel;
RemoteServer: TDCOMConnection;
procedure FormCreate(Sender: TObject);
procedure ShowEventsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
{ Initialize the edit controls with some dates so the user can
just click the button to see some data }
StartDate.Text := DateToStr(EncodeDate(96, 6, 19));
EndDate.Text := DateToStr(EncodeDate(96, 6, 21));
end;
procedure TForm1.ShowEventsClick(Sender: TObject);
begin
{ The query on the server looks like this:
select * from events where
Event_Date >= :Start_Date and
Event_Date <= :End_Date;
The Events ClientDataSet has the parameters from the server set up in the
Params property. At design time, you can right click on a ClientDataSet and
select "Fetch Params" to initialize the params from a TQuery or TStoredProc
on the server. At run-time you can call TClientDataSet.FetchParams to
initialize the params from the server. Or you can set the params up manually
by adding them yourself.
}
Events.Close;
Events.Params.ParamByName('Start_Date').AsDateTime := StrToDateTime(StartDate.Text);
Events.Params.ParamByName('End_Date').AsDateTime := StrToDateTime(EndDate.Text);
Events.Open;
end;
end.
|
unit Spring.Persistence.Adapters.IBX;
{******************************************************************************}
{ }
{ 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. }
{ }
{******************************************************************************}
{ }
{ Samples: }
{ https://bitbucket.org/soundvibe/marshmallow/wiki/Home }
{ }
{ Is Marshmallow and Spring.Persistence.Mapping.RttiExplorer Thread-Safe? }
{ https://bitbucket.org/sglienke/spring4d/issues/109/is-marshmallow-and }
{ https://groups.google.com/forum/#!topic/spring4d/DHocqjxty88 }
{ https://groups.google.com/forum/#!searchin/spring4d/ManyToOne|sort:date/spring4d/sNQ8_W2jPgE/vXhNDt1yDAAJ
{ https://groups.google.com/forum/#!searchin/spring4d/ManyToOne%7Csort:date
{ https://github.com/ezequieljuliano/DelphiLaboratory/blob/master/SpringAndDMVC/Client/Core/Template/Crud.Model.pas
{ https://github.com/ezequieljuliano/DelphiLaboratory/blob/master/SpringAndDMVC/Server/Persistence/DAL.Connection.pas
{ https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html
{ https://martinfowler.com/eaaCatalog/pessimisticOfflineLock.html
{ }
{******************************************************************************}
{$I Spring.inc}
interface
uses
System.SysUtils,
IBX.IB,
IBX.IBDatabase,
IBX.IBCustomDataSet,
Spring.Collections,
Spring.Persistence.Core.Base,
Spring.Persistence.Core.Exceptions,
Spring.Persistence.Core.Interfaces,
// Spring.Persistence.SQL.Generators.Ansi,
Spring.Persistence.SQL.Params;
type
EIBXAdapterException = class(EORMAdapterException);
/// <summary>
/// Represents IBX resultset.
/// </summary>
TIBXResultSetAdapter = class(TDriverResultSetAdapter<TIBDataSet>)
public
constructor Create(const dataSet: TIBDataSet; const exceptionHandler: IORMExceptionHandler);
end;
/// <summary>
/// Represents IBX statement.
/// </summary>
TIBXStatementAdapter = class(TDriverStatementAdapter<TIBDataSet>)
public
destructor Destroy; override;
procedure SetSQLCommand(const commandText: string); override;
procedure SetParam(const param: TDBParam);
procedure SetParams(const params: IEnumerable<TDBParam>); override;
function Execute: NativeUInt; override;
function ExecuteQuery(serverSideCursor: Boolean = True): IDBResultSet; override;
end;
/// <summary>
/// Represents IBX connection.
/// </summary>
TIBXConnectionAdapter = class(TDriverConnectionAdapter<TIBDataBase>)
public
constructor Create(const connection: TIBDataBase); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure Connect; override;
procedure Disconnect; override;
function IsConnected: Boolean; override;
function CreateStatement: IDBStatement; override;
function BeginTransaction: IDBTransaction; override;
end;
/// <summary>
/// Represents IBX transaction.
/// </summary>
TIBXTransactionAdapter = class(TDriverTransactionAdapter<TIBTransaction>)
protected
function InTransaction: Boolean; override;
public
constructor Create(const transaction: TIBTransaction; const exceptionHandler: IORMExceptionHandler); override;
destructor Destroy; override;
procedure Commit; override;
procedure Rollback; override;
end;
TIBXExceptionHandler = class(TORMExceptionHandler)
protected
function GetAdapterException(const exc: Exception; const defaultMsg: string): Exception; override;
end;
implementation
uses
Spring.Persistence.Core.ConnectionFactory,
Spring.Persistence.Core.ResourceStrings,
// Spring.Persistence.SQL.Generators.Firebird,
Spring.Persistence.SQL.Interfaces;
{$REGION 'TIBXResultSetAdapter'}
constructor TIBXResultSetAdapter.Create(const dataSet: TIBDataSet; const exceptionHandler: IORMExceptionHandler);
begin
// dataset.OnClose := etmStayIn; // Means, keep transaction without commit or rollback...
// Next I have to see if or how this works with IBX.
inherited Create(dataSet, exceptionHandler);
end;
{$ENDREGION}
{$REGION 'TIBXStatementAdapter'}
destructor TIBXStatementAdapter.Destroy;
begin
Statement.Free;
inherited Destroy;
end;
function TIBXStatementAdapter.Execute: NativeUInt;
begin
inherited;
try
Statement.Prepare;
Statement.ExecSQL;
Result := Statement.RowsAffected;
// if Statement.Transaction = Statement.DataBase.Transactions[0] then
// Statement.Transaction.Commit
// else
// Statement.Transaction.CommitRetaining;
except
raise HandleException;
end;
end;
function TIBXStatementAdapter.ExecuteQuery(serverSideCursor: Boolean): IDBResultSet;
var
Idx: Integer;
query: TIBDataSet;
adapter: TIBXResultSetAdapter;
begin
inherited;
query := TIBDataSet.Create(nil);
Query.Database := Statement.DataBase;
Query.Transaction := Statement.Transaction;
if not Query.Transaction.InTransaction then
Query.Transaction.StartTransaction;
query.DisableControls;
query.UniDirectional := True;
query.SelectSQL.Text := Statement.SelectSQL.Text;
for Idx := 0 to Statement.Params.Count - 1 do
query.Params[Idx].AsVariant := Statement.Params[Idx].AsVariant;
try
query.Open;
adapter := TIBXResultSetAdapter.Create(query, ExceptionHandler);
Result := adapter;
except
on E: Exception do
begin
query.Free;
raise HandleException(Format(SCannotOpenQuery, [E.Message]));
end;
end;
end;
procedure TIBXStatementAdapter.SetSQLCommand(const commandText: string);
begin
inherited;
Statement.SelectSQL.Text := commandText;
end;
procedure TIBXStatementAdapter.SetParam(const param: TDBParam);
var
paramName: string;
begin
paramName := param.Name;
// strip leading : in param name because UIB does not like them
if param.Name.StartsWith(':') then
paramName := param.Name.Substring(1);
Statement.ParamByName(paramName).AsVariant := param.ToVariant;
end;
procedure TIBXStatementAdapter.SetParams(const params: IEnumerable<TDBParam>);
begin
inherited;
params.ForEach(SetParam);
end;
{$ENDREGION}
{$REGION 'TIBXConnectionAdapter'}
constructor TIBXConnectionAdapter.Create(const connection: TIBDataBase);
var
transaction: TIBTransaction;
begin
Create(connection, TIBXExceptionHandler.Create);
if connection.TransactionCount = 0 then
begin
transaction := TIBTransaction.Create(nil);
transaction.DefaultDatabase := connection;
// Add me...
transaction.DefaultAction := TARollback;
transaction.Params.Add('concurrency');
transaction.Params.Add('nowait');
end;
end;
destructor TIBXConnectionAdapter.Destroy;
begin
// if Assigned(Connection) then
// for Idx := Connection.TransactionCount - 1 downto 0 do
// Connection.Transactions[Idx].Free;
inherited Destroy;
end;
procedure TIBXConnectionAdapter.AfterConstruction;
begin
inherited;
QueryLanguage := qlFirebird;
end;
function TIBXConnectionAdapter.BeginTransaction: IDBTransaction;
var
transaction: TIBTransaction;
begin
if Assigned(Connection) then
try
Connection.Connected := True;
transaction := TIBTransaction.Create(nil);
transaction.DefaultDatabase := Connection;
transaction.DefaultAction := TARollback;
transaction.Params.Add('concurrency');
transaction.Params.Add('nowait');
transaction.StartTransaction;
Result := TIBXTransactionAdapter.Create(transaction, ExceptionHandler);
except
raise HandleException;
end
else
Result := nil;
end;
procedure TIBXConnectionAdapter.Connect;
begin
if Assigned(Connection) then
try
Connection.Connected := True;
except
raise HandleException;
end;
end;
function TIBXConnectionAdapter.CreateStatement: IDBStatement;
var
statement: TIBDataSet;
adapter: TIBXStatementAdapter;
begin
if Assigned(Connection) then
begin
statement := TIBDataSet.Create(nil);
statement.Database := Connection;
statement.Transaction := Connection.Transactions[Connection.TransactionCount - 1];
// statement.Transaction.StartTransaction();
adapter := TIBXStatementAdapter.Create(statement, ExceptionHandler);
adapter.ExecutionListeners := ExecutionListeners;
Result := adapter;
end
else
Result := nil;
end;
procedure TIBXConnectionAdapter.Disconnect;
begin
if Assigned(Connection) then
try
Connection.Connected := False;
except
raise HandleException;
end;
end;
function TIBXConnectionAdapter.IsConnected: Boolean;
begin
Result := Assigned(Connection) and Connection.Connected;
end;
{$ENDREGION}
{$REGION 'TIBXTransactionAdapter'}
constructor TIBXTransactionAdapter.Create(const transaction: TIBTransaction; const exceptionHandler: IORMExceptionHandler);
begin
inherited Create(transaction, exceptionHandler);
// fTransaction.DefaultAction := etmRollback;
// Add me...
// transaction.DefaultDatabase := fDatabase;
transaction.DefaultAction := TARollback;
// transaction.Params.Add('concurrency');
// transaction.Params.Add('nowait');
if not InTransaction then
try
fTransaction.StartTransaction;
except
raise HandleException;
end;
end;
destructor TIBXTransactionAdapter.Destroy;
begin
fTransaction.Free;
inherited Destroy;
end;
procedure TIBXTransactionAdapter.Commit;
begin
if Assigned(fTransaction) then
try
fTransaction.Commit;
except
raise HandleException;
end;
end;
function TIBXTransactionAdapter.InTransaction: Boolean;
begin
Result := fTransaction.InTransaction;
end;
procedure TIBXTransactionAdapter.Rollback;
begin
if Assigned(fTransaction) then
try
fTransaction.RollBack;
except
raise HandleException;
end;
end;
{$ENDREGION}
{$REGION 'TIBXExceptionHandler'}
function TIBXExceptionHandler.GetAdapterException(const exc: Exception; const defaultMsg: string): Exception;
begin
// if exc is EUIBError then
// Result := EIBXAdapterException.Create(defaultMsg, EUIBError(exc).ErrorCode)
// else
// Result := nil;
if exc is EIBInterBaseError then
Result := EIBXAdapterException.Create(defaultMsg, EIBInterBaseError(exc).IBErrorCode)
else
Result := nil;
end;
{$ENDREGION}
initialization
TConnectionFactory.RegisterConnection<TIBXConnectionAdapter>(dtIBX);
end.
|
unit typename_0;
interface
implementation
var s: string;
procedure Test;
begin
s := typename(string);
end;
initialization
Test();
finalization
Assert(s = 'String');
end. |
unit ReportsView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GridFrame, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData,
cxGridCustomPopupMenu, cxGridPopupMenu, Vcl.Menus, System.Actions,
Vcl.ActnList, dxBar, cxClasses, Vcl.ComCtrls, cxGridLevel, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxGrid, ReportQuery, dxBarExtItems,
System.Generics.Collections, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, dxSkinsdxBarPainter,
cxDataControllerConditionalFormattingRulesManagerDialog, dxBarBuiltInMenu;
type
TViewReports = class(TfrmGrid)
actExportToExcelDocument: TAction;
dxbrbExportToExcelDocument: TdxBarButton;
clManufacturer: TcxGridDBBandedColumn;
clComponent: TcxGridDBBandedColumn;
clSpecification: TcxGridDBBandedColumn;
clScheme: TcxGridDBBandedColumn;
clDrawing: TcxGridDBBandedColumn;
clImage: TcxGridDBBandedColumn;
clDescription: TcxGridDBBandedColumn;
actFilterBySpecification: TAction;
dxBarButton1: TdxBarButton;
actFilterBySchema: TAction;
dxBarButton2: TdxBarButton;
dxBarManagerBar1: TdxBar;
dxBarStatic1: TdxBarStatic;
actFilterByDrawing: TAction;
dxBarButton3: TdxBarButton;
actFilterByImage: TAction;
dxBarButton4: TdxBarButton;
actClearFilters: TAction;
dxBarButton5: TdxBarButton;
actFilterByDescription: TAction;
dxBarButton6: TdxBarButton;
procedure actClearFiltersExecute(Sender: TObject);
procedure actExportToExcelDocumentExecute(Sender: TObject);
procedure actFilterByDescriptionExecute(Sender: TObject);
procedure actFilterByDrawingExecute(Sender: TObject);
procedure actFilterByImageExecute(Sender: TObject);
procedure actFilterBySchemaExecute(Sender: TObject);
procedure actFilterBySpecificationExecute(Sender: TObject);
private
FFilterFields: TList<String>;
FQueryReports: TQueryReports;
procedure FilterByColumn(const AColumn: TcxGridDBBandedColumn;
const AValue: String);
function GetFileName: string;
procedure SetQueryReports(const Value: TQueryReports);
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property QueryReports: TQueryReports read FQueryReports
write SetQueryReports;
{ Public declarations }
end;
implementation
uses DialogUnit, RepositoryDataModule, System.StrUtils;
{$R *.dfm}
constructor TViewReports.Create(AOwner: TComponent);
begin
inherited;
FFilterFields := TList<String>.Create;
end;
destructor TViewReports.Destroy;
begin
FFilterFields.Clear;
FreeAndNil(FFilterFields);
inherited;
end;
procedure TViewReports.actClearFiltersExecute(Sender: TObject);
begin
MainView.DataController.Filter.Root.Clear;
actClearFilters.Checked := True;
actClearFilters.Checked := False;
end;
procedure TViewReports.actExportToExcelDocumentExecute(Sender: TObject);
var
AFileName: String;
begin
Application.Hint := '';
if not TDialog.Create.ShowDialog(TExcelFileSaveDialog, '', GetFileName,
AFileName) then
Exit;
ExportViewToExcel(MainView, AFileName);
end;
procedure TViewReports.actFilterByDescriptionExecute(Sender: TObject);
begin
if not actFilterByDescription.Checked then
begin
FilterByColumn(MainView.GetColumnByFieldName('Описание'), 'отсутствует');
actFilterByDescription.Checked := True;
end;
end;
procedure TViewReports.actFilterByDrawingExecute(Sender: TObject);
begin
if not actFilterByDrawing.Checked then
begin
FilterByColumn(MainView.GetColumnByFieldName('Чертёж'), 'отсутствует');
actFilterByDrawing.Checked := True;
end;
end;
procedure TViewReports.actFilterByImageExecute(Sender: TObject);
begin
if not actFilterByImage.Checked then
begin
FilterByColumn(MainView.GetColumnByFieldName('Изображение'), 'отсутствует');
actFilterByImage.Checked := True;
end;
end;
procedure TViewReports.actFilterBySchemaExecute(Sender: TObject);
begin
if not actFilterBySchema.Checked then
begin
FilterByColumn(MainView.GetColumnByFieldName('Схема'), 'отсутствует');
actFilterBySchema.Checked := True;
end;
end;
procedure TViewReports.actFilterBySpecificationExecute(Sender: TObject);
begin
if not actFilterBySpecification.Checked then
begin
FilterByColumn(MainView.GetColumnByFieldName('Спецификация'),
'отсутствует');
actFilterBySpecification.Checked := True;
end;
end;
procedure TViewReports.FilterByColumn(const AColumn: TcxGridDBBandedColumn;
const AValue: String);
var
ci: TcxFilterCriteriaItem;
r: TcxFilterCriteriaItemList;
s: string;
begin
r := MainView.DataController.Filter.Root;
// r.Clear;
// Снимаем фильтры с других полей
for s in FFilterFields do
begin
ci := r.Criteria.FindItemByItemLink(MainView.GetColumnByFieldName(s));
if ci <> nil then
ci.free;
end;
r.AddItem(AColumn, foEqual, AValue, AValue);
MainView.DataController.Filter.Active := True;
end;
function TViewReports.GetFileName: string;
var
AColumn: TcxGridDBBandedColumn;
AManufacturer: String;
s: string;
begin
s := '';
AColumn := MainView.GetColumnByFieldName('Производитель');
if AColumn.DataBinding.Filtered then
AManufacturer := AColumn.DataBinding.FilterCriteriaItem.Value
else
AManufacturer := 'Все производители';
if MainView.GetColumnByFieldName('Описание').DataBinding.Filtered then
s := String.Format('%s,%s', [s, 'Краткое описание']);
if MainView.GetColumnByFieldName('Спецификация').DataBinding.Filtered then
s := String.Format('%s,%s', [s, 'Спецификация']);
if MainView.GetColumnByFieldName('Схема').DataBinding.Filtered then
s := String.Format('%s,%s', [s, 'Схема']);
if MainView.GetColumnByFieldName('Чертёж').DataBinding.Filtered then
s := String.Format('%s,%s', [s, 'Чертёж']);
if MainView.GetColumnByFieldName('Изображение').DataBinding.Filtered then
s := String.Format('%s,%s', [s, 'Изображение']);
s := s.Trim([',']);
if s.IsEmpty then
s := 'Все документы';
Result := String.Format('%s (%s) %s',
[AManufacturer, s, FormatDateTime('dd-mm-yyyy', Date)]);
end;
procedure TViewReports.SetQueryReports(const Value: TQueryReports);
begin
if FQueryReports <> Value then
begin
FQueryReports := Value;
if FQueryReports <> nil then
begin
FFilterFields.Clear;
FFilterFields.Add(QueryReports.W.Описание.FieldName);
FFilterFields.Add(QueryReports.W.Спецификация.FieldName);
FFilterFields.Add(QueryReports.W.Схема.FieldName);
FFilterFields.Add(QueryReports.W.Чертёж.FieldName);
FFilterFields.Add(QueryReports.W.Изображение.FieldName);
MainView.DataController.DataSource := FQueryReports.W.DataSource;
end;
end;
end;
end.
|
unit PIC;
interface
uses Classes;
Const
Tab = #$09;
Type
TReverseCALM = class(TObject)
private
FProcessor : string; { nom du processeur }
FWordBits : integer; { nombre de bits par mots }
FWordLen : word; { longeur d'un mot en mémoire }
FMemorySize : longint; { taille mémoire }
FRegisterCount : word;
FMnemonicList : TStringList; // Mnémonics
FRegisterList : TStringList; // Registres du processeur
FLabelList : TStringList; // Labels prédéfinis
FSymbolList : TStringList; // Table de Symbols
protected
function ID_Label(Addrs : longint) : string;
function ID_Symbol(Reg : word) : string;
function GetWord(var Buffer; Addrs : longint) : pointer; virtual; abstract;
procedure AddLabel(Addrs : longint; Name : string);
function GetLabel(Addrs : longint; MustCreate : boolean) : string;
procedure AddRegister(Reg : word; Name : string);
procedure AddSymbol(Reg : word; Name : string);
function GetSymbol(Reg : word; MustCreate : boolean) : string;
public
constructor Create;
procedure SetProcessor(ProcName : string); virtual; abstract;
function GetMnemonic(var X) : string; virtual; abstract;
function GetCALM(var Buffer; Addrs : longint) : string;
procedure BuildHeader(Dest : TStrings);
procedure BuildSymbolTable(Dest : TStrings);
procedure BuildSourceCALM(var Buffer; BufferSize : longint; Dest : TStrings);
published
property Processor : string read FProcessor write SetProcessor;
property WordBits : integer read FWordBits;
property WordLen : word read FWordLen;
property MemorySize : longint read FMemorySize;
property Mnemonics : TStringList read FMnemonicList write FMnemonicList;
property Labels : TStringList read FLabelList write FLabelList;
property Symbols : TStringList read FSymbolList write FSymbolList;
property Registers : TStringList read FRegisterList write FRegisterList;
end;
Type
PReversePicFamily = ^TReversePicFamily;
TReversePicFamily = class(TReverseCALM)
private
protected
function GetWord(var Buffer; Addrs : longint) : pointer; override;
procedure AddMnemonic(Name, Operands, Code : string);
public
procedure SetProcessor(ProcName : string); override;
function GetMnemonic(var X) : string; override;
end;
var
ReverseCALM : TReverseCALM;
implementation
uses Windows, SysUtils, Math, Inifiles;
Const { CALM }
opNoOperand = 0; {Pas d'operand}
opLabel = 1; {Etiquette pour Call, Jump, etc }
opLiteral = 2; {Literal}
opByteOriented = 3; {Opération sur octet}
opBitOriented = 4; {Opération sur bit}
opError = 255;
accNo = 0; { Pas d'accumulator }
accOnly = 1; { uniquement accumulator }
accSource = 2; { Accumulator comme source }
accDest = 3; { Accumulator comme dest }
Type
TMnemonicCALM = class(TObject)
end;
PPicFamilyMnemonic = ^TPicFamilyMnemonic;
TPicFamilyMnemonic = class(TMnemonicCALM)
private
FMnemonic : string;
FOpCode : word;
FOperationType : word;
FAccumulatorPos : integer;
FOpcodeMask : word;
FRegisterMask : word;
FBitMask : word;
FPosBitAddress : word;
FLiteralMask : word;
ReverseOwner : TReversePicFamily;
protected
function GetBitAddress(Reg : word; BitAddress : byte) : string;
function GetAccumulator(Acc : word) : string;
function GetOperationType(S : string) : integer;
function GetAccumulatorPos(S : string) : integer;
public
constructor Create(AOwner : TReversePicFamily; Name, Operands, Code : String);
function GetMnemonic(W : word; var Mnemonic : string) : boolean;
end;
Var
IniFile : TIniFile;
Function UnQuote(S : String) : string;
Var
P : PChar;
begin
S := S+#0;
P := @S[1];
Result := AnsiExtractQuotedStr(P, '"');
end;
procedure SetBitW(var W : word; Bit : integer);
begin
W := W or (1 shl Bit);
end;
procedure ClearBitW(var W : word; Bit : integer);
begin
W := W and not (1 shl Bit);
end;
function IntToBin(L : longint; digits : integer) : string;
var
i : integer;
begin
Result := '';
for i := 0 to pred(digits) do
If (L and (1 shl i)) = (1 shl i) then
Result := '1' + Result
else
Result := '0' + Result;
end;
function IntToAscii(B : Byte) : string;
begin
Case Char(B) of
'A'..'Z' : Result := Char(B);
else
Result := '{}';
end;
end;
// ========================================================================
function TReverseCALM.ID_Label(Addrs : longint) : string;
begin
Result := 'Label'+IntToHex(Addrs, Round(LogN(16, MemorySize)+0.5));
end;
function TReverseCALM.ID_Symbol(Reg : word) : string;
begin
Result := 'Reg'+IntToHex(Reg, 2);
end;
procedure TReverseCALM.AddLabel(Addrs : longint; Name : string);
begin
FLabelList.Add(ID_Label(Addrs)+'='+Name);
end;
function TReverseCALM.GetLabel(Addrs : longint; MustCreate : boolean) : string;
begin
Result := FLabelList.Values[ID_Label(Addrs)];
if Result <> '' then exit;
if MustCreate then begin
Result := ID_Label(Addrs);
AddLabel(Addrs, Result);
end;
end;
procedure TReverseCALM.AddRegister(Reg : word; Name : string);
begin
FRegisterList.Add(ID_Symbol(Reg)+'='+Name);
end;
procedure TReverseCALM.AddSymbol(Reg : word; Name : string);
begin
FSymbolList.Add(ID_Symbol(Reg)+'='+Name);
end;
function TReverseCALM.GetSymbol(Reg : word; MustCreate : boolean) : string;
Var
ID : string;
begin
ID := ID_Symbol(Reg);
Result := FRegisterList.Values[ID];
If Result<>'' then exit;
Result := FSymbolList.Values[ID];
if Result <> '' then exit;
If MustCreate then begin
Result := ID;
AddSymbol(Reg, Result);
end;
end;
function TReverseCALM.GetCALM(var Buffer; Addrs : longint) : string;
begin
if GetLabel(Addrs, False)='' then
Result := Tab+GetMnemonic(GetWord(Buffer, Addrs)^)
else
Result := GetLabel(Addrs, False)+':'+Tab+GetMnemonic(GetWord(Buffer, Addrs)^);
end;
constructor TReverseCALM.Create;
begin
inherited Create;
FMnemonicList := TStringList.Create;
FRegisterList := TStringList.Create;
FLabelList := TStringList.Create;
FSymbolList := TStringList.Create;
FProcessor := '';
FWordBits := 0;
FWordLen := 0;
end;
procedure TReverseCALM.BuildHeader(Dest : TStrings);
begin
With Dest do begin
Add(';'+Tab+'PIC2CALM (c) 2001 O. Baumgartner');
Add(';'+Tab+'http://www.boumpower.ch');
Add('');
Add('.proc '+Processor);
Add('');
end;
end;
procedure TReverseCALM.BuildSymbolTable(Dest : TStrings);
var
Loc : word;
Reg : word;
i : word;
begin
If FSymbolList.Count=0 then exit;
Loc := $00;
With FSymbolList do begin
Sort;
for i := 0 to Pred(Count) do begin
Reg := StrToInt('$'+copy(Names[i], 4, 255));
if Loc<>Reg then begin
Loc := Reg;
Dest.Add('.loc 16'''+IntToHex(Loc, 2));
end;
Dest.Add(Values[Names[i]]+':'+Tab+'.blk.16 1');
Inc(Loc);
end;
Sorted := false;
end;
Dest.Add('');
end;
procedure TReverseCALM.BuildSourceCALM(var Buffer; BufferSize : longint; Dest : TStrings);
var
Loc : longint;
i : longint;
begin
BuildHeader(Dest);
BuildSymbolTable(Dest);
Loc := $000;
Dest.Add('.loc 16'''+IntToHex(Loc, Round(LogN(16, MemorySize)+0.5)));
for i := 0 to pred(BufferSize div 2) do
Dest.Add(GetCALM(Buffer, i))
end;
// ===============================================================================
constructor TPicFamilyMnemonic.Create(AOwner : TReversePicFamily; Name, Operands, Code : String);
var
bit : integer;
begin
inherited Create;
FMnemonic := '';
FOpCode := 0;
FOperationType := opError;
FAccumulatorPos := 0;
FOpcodeMask := 0;
FRegisterMask := 0;
FBitMask := 0;
FPosBitAddress := 0;
FLiteralMask := 0;
ReverseOwner := AOwner;
if Length(Code)=0 then exit; { Erreur }
For Bit := Length(Code) downto 1 do
if Code[Bit]=' ' then Delete(Code, Bit, 1); { remove blancs }
if Length(Code)<>AOwner.WordBits then Exit; { Erreur !!! }
FMnemonic := Name;
FOperationType := GetOperationType(Operands);
FAccumulatorPos := GetAccumulatorPos(Operands);
if FOperationType=opError then exit; { Erreur !!! }
For Bit := 0 to pred(AOwner.WordBits) do
Case Code[AOwner.WordBits-Bit] of
'f' : SetBitW(FRegisterMask, Bit);
'b' : begin
If FBitMask=0 then FPosBitAddress := bit;
SetBitW(FBitMask, Bit);
end;
'k' : SetBitW(FLiteralMask, Bit);
'x' : {Don't care};
'0' : SetBitW(FOpCodeMask, Bit);
'1' : begin
SetBitW(FOpCodeMask, Bit);
SetBitW(FOpCode, Bit);
end;
else FOperationType := opError;
end
end;
function TPicFamilyMnemonic.GetBitAddress(Reg : word; BitAddress : byte) : string;
begin
Result := IntToStr(BitAddress);
end;
function TPicFamilyMnemonic.GetAccumulator(Acc : word) : string;
begin
Result := 'W';
end;
function TPicFamilyMnemonic.GetOperationType(S : string) : integer;
begin
Result := opError;
If S='' then Result := opNoOperand;
If CompareText(S, 'Addr')=0 then Result:=opLabel;
If CompareText(S, 'W')=0 then Result:=opLiteral;
If CompareText(S, '#Val,W')=0 then Result:=opLiteral;
If CompareText(S, 'Reg')=0 then Result:=opByteOriented;
If CompareText(S, 'Reg,W')=0 then Result:=opByteOriented;
If CompareText(S, 'W,Reg')=0 then Result:=opByteOriented;
If CompareText(S, 'Reg:#b')=0 then Result:=opBitOriented;
end;
function TPicFamilyMnemonic.GetAccumulatorPos(S : string) : integer;
var
i, A, C : word;
begin
Result := accNo;
if Length(S)= 0 then exit;
A := 0; C :=0;
for i := 1 to Length(S) do begin
if S[i] in ['W'] then A := i;
if S[i] in [',', ':'] then C := i;
end;
if A=0 then exit;
if C=0 then begin
Result := accOnly;
exit;
end;
if A<C then
Result := accSource
else
Result := accDest;
end;
function TPicFamilyMnemonic.GetMnemonic(W : word; var Mnemonic : string) : boolean;
var
Literal : word;
begin
Result := (W and FOpcodeMask) = FOpCode;
If Result = false then exit;
Case FOperationType of
opNoOperand : Mnemonic := FMnemonic;
opLabel : Mnemonic := FMnemonic+Tab+ReverseOwner.GetLabel(W and FLiteralMask, True);
opLiteral : begin
Literal := W and FLiteralMask;
Mnemonic := FMnemonic+Tab+
'#16'''+IntToHex(Literal, 2)+ { Hexa}
','+GetAccumulator(0)+Tab+
'; #10'''+IntToStr(Literal)+ { Décimal }
' #2'''+IntToBin(Literal, 8)+ { Binaire }
' #"'+IntToAscii(Literal)+'"'; { Ascii }
end;
opByteOriented : Case FAccumulatorPos of
accNo : Mnemonic := FMnemonic+Tab+ReverseOwner.GetSymbol(W and FRegisterMask, True);
accOnly : Mnemonic := FMnemonic+Tab+GetAccumulator(0);
accSource : Mnemonic := FMnemonic+Tab+GetAccumulator(0)+
','+ReverseOwner.GetSymbol(W and FRegisterMask, True);
accDest : Mnemonic := FMnemonic+Tab+ReverseOwner.GetSymbol(W and FRegisterMask, True)+
','+GetAccumulator(0);
end;
opBitOriented : Mnemonic := FMnemonic + Tab+
ReverseOwner.GetSymbol(W and FRegisterMask, True)+
':#'+GetBitAddress(W and FRegisterMask, (W and FBitMask) shr FPosBitAddress);
opError : Mnemonic := '^Error : '+FMnemonic+
' 16'''+IntToHex(W, 4)+
' 2'''+IntToBin(W, 14);
end;
end;
// ===============================================================================
function TReversePicFamily.GetWord(var Buffer; Addrs : longint) : pointer;
Var
X : array[0..32768] of word absolute Buffer;
begin
Result := @X[Addrs];
end;
function TReversePicFamily.GetMnemonic(var X) : string;
var
W : word absolute X;
i : integer;
Found : boolean;
begin
Found := False;
i := Pred(FMnemonicList.Count);
while (not Found) and (i>=0) do begin
Found := TPicFamilyMnemonic(FMnemonicList.Objects[i]).GetMnemonic(W, Result);
Dec(i);
end;
If Found then exit;
Result := '16'''+IntToHex(W, 2*FWordLen)+Tab+
';2'''+IntToBin(W, FWordBits);
end;
procedure TReversePicFamily.AddMnemonic(Name, Operands, Code : String);
var
Mnemonic : TPicFamilyMnemonic;
begin
Mnemonic := TPicFamilyMnemonic.Create(Self, Name, Operands, Code);
FMnemonicList.AddObject(Name+' '+Operands, Mnemonic);
If Mnemonic.FOperationType=opError then
MessageBox(0,
PChar('"'+Name+'" "'+Operands+'" "'+Code+'"'),
'Erreur dans AddMnemonic()', MB_OK);
end;
procedure TReversePicFamily.SetProcessor(ProcName : String);
var
i : integer;
S : TStringList;
StrAddrs : String;
begin
S := TStringList.Create;
FProcessor := ProcName;
With IniFile do begin
FProcessor := ReadString(ProcName, 'Proc', 'Not defined');
FWordBits := ReadInteger(ProcName, 'WordBits', 0);
FWordLen := (FWordBits+7) div 8; { longueur des mots }
FRegisterCount := ReadInteger(ProcName, 'RegisterCount', 0);
FMemorySize := ReadInteger(ProcName, 'MemorySize', 0);
end;
// lecture des labels prédéfinis
IniFile.ReadSectionValues(ProcName+'.Labels', S);
i := 0;
While i< S.Count do begin
StrAddrs := Trim(S.Names[i]);
if (Length(StrAddrs)>0) and (StrAddrs[1] in ['$', '0'..'9']) then
AddLabel(StrToInt(StrAddrs),
S.Values[StrAddrs]);
Inc(i);
end;
S.Clear;
// lecture des Registres prédéfinis
IniFile.ReadSectionValues(ProcName+'.Registers', S);
i := 0;
While i< S.Count do begin
StrAddrs := Trim(S.Names[i]);
if (Length(StrAddrs)>0) and (StrAddrs[1] in ['$', '0'..'9']) then
AddRegister(StrToInt(StrAddrs),
S.Values[StrAddrs]);
Inc(i);
end;
S.Clear;
// lecture des Mnemonics
IniFile.ReadSectionValues(ProcName+'.Mnemonics', S);
If S.Count>0 then
for I := Pred(S.Count) downto 0 do
if CompareText(S.Names[i], 'Mnemonic')=0 then S.Delete(i);
i := 0;
S.Free;
{
; Syntaxe AddInstruction(Mnemonic, Operands, Opcode);
;
; Operands
; Addr : Label pour Jump, Goto, Call, etc
; #Val,W : Literal field, constant data
; Reg,W : Register file address 0x00 to 0x7F, d=0 store in W
; W,Reg : idem, mais attention si on utilise d car d=1 store in W
; Reg : Register only
; W : accumulator only
; Reg:#b : bit-oriented operation
; OpCode
; f : file register
; b : bit address
; k : literal
; d : destination select NE PAS UTILISER !!!,
; coder 2x l'instruction avec les bons Operands
; Les instructions non triviale comme ClrC, ClrZ, etc sont
; à mettre en fin de table pour être décodée.
}
AddMnemonic('Move', '#Val,W', '11 00xx kkkk kkkk');
AddMnemonic('Move', 'W,Reg', '00 0000 1fff ffff');
AddMnemonic('Move', 'Reg,W', '00 1000 0fff ffff');
AddMnemonic('Test', 'Reg', '00 1000 1fff ffff');
AddMnemonic('Move', 'W,Reg', '00 0000 0fff ffff'); { Option, Tris PortA, tris PortB }
// AddMnemonic('Move', 'W,Reg', '00 0000 0fff ffff');
// AddMnemonic('Move', 'W,Reg', '00 0000 0fff ffff');
AddMnemonic('Add', '#Val,W', '11 1110 kkkk kkkk');
AddMnemonic('Add', 'Reg,W', '00 0111 0fff ffff');
AddMnemonic('Add', 'W,Reg', '00 0111 1fff ffff');
AddMnemonic('Sub', '#Val,W', '11 1100 kkkk kkkk');
AddMnemonic('Sub', 'Reg,W', '00 0010 0fff ffff');
AddMnemonic('Sub', 'W,Reg', '00 0010 1fff ffff');
AddMnemonic('And', '#Val,W', '11 1001 kkkk kkkk');
AddMnemonic('And', 'Reg,W', '00 0101 0fff ffff');
AddMnemonic('And', 'W,Reg', '00 0101 1fff ffff');
AddMnemonic('Or', '#Val,W', '11 1000 kkkk kkkk');
AddMnemonic('Or', 'Reg,W', '00 0100 0fff ffff');
AddMnemonic('Or', 'W,Reg', '00 0100 1fff ffff');
AddMnemonic('Xor', '#Val,W', '11 1010 kkkk kkkk');
AddMnemonic('Xor', 'Reg,W', '00 0110 0fff ffff');
AddMnemonic('Xor', 'W,Reg', '00 0110 1fff ffff');
AddMnemonic('Swap', 'Reg,W', '00 1110 0fff ffff');
AddMnemonic('Swap', 'Reg', '00 1110 1fff ffff');
AddMnemonic('Clr', 'Reg', '00 0001 1fff ffff');
AddMnemonic('Clr', 'W', '00 0001 0xxx xxxx');
AddMnemonic('ClrWDT', '', '00 0000 0110 0100');
AddMnemonic('Sleep', '', '00 0000 0110 0011');
AddMnemonic('Not', 'Reg', '00 1001 1fff ffff');
AddMnemonic('Not', 'Reg,W', '00 1001 0fff ffff');
AddMnemonic('Inc', 'Reg', '00 1010 1fff ffff');
AddMnemonic('Inc', 'Reg,W', '00 1010 0fff ffff');
AddMnemonic('Dec', 'Reg', '00 0011 1fff ffff');
AddMnemonic('Dec', 'Reg,W', '00 0011 0fff ffff');
AddMnemonic('RLC', 'Reg', '00 1101 1fff ffff');
AddMnemonic('RLC', 'Reg,W', '00 1101 0fff ffff');
AddMnemonic('RRC', 'Reg', '00 1100 1fff ffff');
AddMnemonic('RRC', 'Reg,W', '00 1100 0fff ffff');
AddMnemonic('Clr', 'Reg:#b', '01 00bb bfff ffff');
AddMnemonic('Set', 'Reg:#b', '01 01bb bfff ffff');
AddMnemonic('IncSkip,EQ', 'Reg', '00 1111 1fff ffff');
AddMnemonic('IncSkip,EQ', 'Reg,W', '00 1111 0fff ffff');
AddMnemonic('DecSkip,EQ', 'Reg', '00 1011 1fff ffff');
AddMnemonic('DecSkip,EQ', 'Reg,W', '00 1011 0fff ffff');
AddMnemonic('TestSkip,BC','Reg:#b', '01 10bb bfff ffff');
AddMnemonic('TestSkip,BS','Reg:#b', '01 11bb bfff ffff');
AddMnemonic('Jump', 'Addr', '10 1kkk kkkk kkkk');
AddMnemonic('Call', 'Addr', '10 0kkk kkkk kkkk');
AddMnemonic('RetMove', '#Val,W', '11 01xx kkkk kkkk');
AddMnemonic('Ret', '', '00 0000 0000 1000');
AddMnemonic('RetI', '', '00 0000 0000 1001');
AddMnemonic('Nop', '', '00 0000 0xx0 0000');
{ Non Trivial }
AddMnemonic('ClrC', '', '01 0000 0000 0011');
AddMnemonic('SetC', '', '01 0100 0000 0011');
AddMnemonic('ClrD', '', '01 0000 1000 0011');
AddMnemonic('SetD', '', '01 0100 1000 0011');
AddMnemonic('ClrZ', '', '01 0001 0000 0011');
AddMnemonic('SetZ', '', '01 0101 0000 0011');
AddMnemonic('Skip,CS', '', '01 1100 0000 0011');
AddMnemonic('Skip,CC', '', '01 1000 0000 0011');
AddMnemonic('Skip,DS', '', '01 1100 1000 0011');
AddMnemonic('Skip,DC', '', '01 1000 1000 0011');
AddMnemonic('Skip,ZS', '', '01 1101 0000 0011');
AddMnemonic('Skip,ZC', '', '01 1001 0000 0011');
end;
// =========================================================================
procedure OpenIniFile;
Const
IniName = 'Pic2CALM.INI';
var
FName : string;
begin
FName := FileSearch(IniName,
ExtractFileDir(ParamStr(0))+';'+
GetCurrentDir);
if FName='' then begin
MessageBox(0, PChar('Le fichier '+IniName+' n''a pas été trouvé'),
'Erreur d''ouverture',
MB_OK+MB_ICONERROR+MB_APPLMODAL);
Abort;
end;
IniFile := TIniFile.Create(ExpandFileName(Fname));
end;
Initialization
Begin
OpenIniFile;
ReverseCALM := TReversePicFamily.Create;
With ReverseCALM do begin
SetProcessor('Pic16f84');
end;
end;
Finalization
begin
IniFile.Free;
end;
end.
|
unit Variant_18_1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids;
type
TForm22 = class(TForm)
Tab: TStringGrid;
Label1: TLabel;
Edit1: TEdit;
Label2: TLabel;
Label3: TLabel;
Edit2: TEdit;
Label4: TLabel;
Edit3: TEdit;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form22: TForm22;
implementation
{$R *.dfm}
const
Eps = 1E-3;
var
A, B, H, R, Rup: Real;
function F(X: Real): Real;
begin
F := Sin(X);
end;
function DF(X: Real): Real;
begin
DF := Cos(X);
end;
procedure Kat(A, B: Real; var R: Real);
begin
if F(A)*F(B) = 0 then
begin
if F(A) = 0 then
R := A
else
R := B
end
else
if F(A)*F(B) < 0 then
begin
if F(A) < 0 then
while Abs(F(A)) > Eps do
begin
A := A - F(A) / DF(A);
R := A;
end
else
while Abs(F(B)) > Eps do
begin
B := B - F(B) / DF(B);
R := B;
end;
end;
end;
procedure TForm22.Button1Click(Sender: TObject);
var
I: Integer;
begin
A := StrToFloat(Edit1.Text);
B := StrToFloat(Edit2.Text);
H := StrToFloat(Edit3.Text);
with Tab do
begin
Cells[0,0] := 'N';
Cells[1,0] := 'Section';
Cells[2,0] := 'Root';
end;
I := 1;
Rup := 5;
with Tab do
repeat
Kat(A,A + H, R);
if (Round(R-Rup) <> 0) and ((A-R)*(H+A-R) <= 0) then
begin
Cells[0,I] := IntToStr(I);
Cells[1,I] := FloatToStrF(A, ffNumber, 4, 2) + ' .. '
+ FloatToStrF(A+H, ffNumber, 4, 2);
Cells[2,I] := FloatToStrF(R, ffNumber, 12, 9);
Inc(I);
end;
Rup := R;
A := A + H;
until A >= B;
end;
procedure TForm22.Button2Click(Sender: TObject);
var
J: Integer;
begin
Edit1.Clear;
Edit2.Clear;
Edit3.Clear;
for J := 1 to Tab.RowCount do
begin
Tab.Cells[0,J] := '';
Tab.Cells[1,J] := '';
Tab.Cells[2,J] := '';
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.