text
stringlengths
14
6.51M
unit IWDBExtCtrls; {PUBDIST} interface uses {$IFDEF Linux} QGraphics, {$ELSE}Graphics,{$ENDIF} {$IFDEF Linux} IWJpeg, {$ELSE}Jpeg,{$ENDIF} Classes, DB, IWExtCtrls, IWHTMLTag; type TIWDBImage = class(TIWDynamicImage) protected FDataField: string; FDataSource: TDataSource; // procedure Notification(AComponent: TComponent; AOperation: TOperation); override; public function RenderHTML: TIWHTMLTag; override; published property DataField: string read FDataField write FDataField; property DataSource: TDataSource read FDataSource write FDataSource; end; implementation uses IWDBStdCtrls, IWControl, SysUtils; { TIWDBImage } procedure TIWDBImage.Notification(AComponent: TComponent; AOperation: TOperation); begin inherited; if AOperation = opRemove then begin if FDatasource = AComponent then begin FDatasource := nil; end; end; end; function TIWDBImage.RenderHTML: TIWHTMLTag; var LField: TField; S: TMemoryStream; Ljpg: TJPEGImage; LHeader: array [0..1] of byte; begin // Clear first in case the datafield is empty so we dont display the last image FPicture.Graphic := nil; if CheckDataSource(DataSource, DataField, LField) then begin if LField.IsBlob then begin S := TMemoryStream.Create; try TBlobField(LField).SaveToStream(S); // Find file type S.Position := 0; S.Read(LHeader, 2); S.Position := 0; if (LHeader[0] = $FF) and (LHeader[1] = $D8) then begin LJPg := TJPEGImage.Create; try LJpg.LoadFromStream(S); FPicture.Assign(LJPG); finally FreeAndNil(LJpg); end; end else begin FPicture.Assign(LField); end; finally FreeAndNil(S); end; end; end; Result := inherited RenderHTML; end; end.
unit DropSource3; // ----------------------------------------------------------------------------- // // *** NOT FOR RELEASE *** // // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite // Module: DropSource3 // Description: Deprecated TDropSource class. // Provided for compatibility with previous versions of the // Drag and Drop Component Suite. // Version: 4.0 // Date: 25-JUN-2000 // Target: Win32, Delphi 3-6 and C++ Builder 3-5 // Authors: Angus Johnson, ajohnson@rpi.net.au // Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright © 1997-2000 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- interface uses DragDrop, DropSource, ActiveX, Classes; {$include DragDrop.inc} const MAXFORMATS = 20; type // TODO -oanme -cStopShip : Verify that TDropSource can be used for pre v4 components. TDropSource = class(TCustomDropSource) private FDataFormats: array[0..MAXFORMATS-1] of TFormatEtc; FDataFormatsCount: integer; protected // IDataObject implementation function QueryGetData(const FormatEtc: TFormatEtc): HRESULT; stdcall; // TCustomDropSource implementation function HasFormat(const FormatEtc: TFormatEtc): boolean; override; function GetEnumFormatEtc(dwDirection: LongInt): IEnumFormatEtc; override; // New functions... procedure AddFormatEtc(cfFmt: TClipFormat; pt: PDVTargetDevice; dwAsp, lInd, tym: longint); virtual; public constructor Create(AOwner: TComponent); override; end; implementation uses ShlObj, SysUtils, Windows; // ----------------------------------------------------------------------------- // TEnumFormatEtc // ----------------------------------------------------------------------------- type pFormatList = ^TFormatList; TFormatList = array[0..255] of TFormatEtc; TEnumFormatEtc = class(TInterfacedObject, IEnumFormatEtc) private FFormatList: pFormatList; FFormatCount: Integer; FIndex: Integer; public constructor Create(FormatList: pFormatList; FormatCount, Index: Integer); { IEnumFormatEtc } function Next(Celt: LongInt; out Elt; pCeltFetched: pLongInt): HRESULT; stdcall; function Skip(Celt: LongInt): HRESULT; stdcall; function Reset: HRESULT; stdcall; function Clone(out Enum: IEnumFormatEtc): HRESULT; stdcall; end; // ----------------------------------------------------------------------------- constructor TEnumFormatEtc.Create(FormatList: pFormatList; FormatCount, Index: Integer); begin inherited Create; FFormatList := FormatList; FFormatCount := FormatCount; FIndex := Index; end; // ----------------------------------------------------------------------------- function TEnumFormatEtc.Next(Celt: LongInt; out Elt; pCeltFetched: pLongInt): HRESULT; var i: Integer; begin i := 0; WHILE (i < Celt) and (FIndex < FFormatCount) do begin TFormatList(Elt)[i] := FFormatList[fIndex]; Inc(FIndex); Inc(i); end; if pCeltFetched <> NIL then pCeltFetched^ := i; if i = Celt then result := S_OK else result := S_FALSE; end; // ----------------------------------------------------------------------------- function TEnumFormatEtc.Skip(Celt: LongInt): HRESULT; begin if Celt <= FFormatCount - FIndex then begin FIndex := FIndex + Celt; result := S_OK; end else begin FIndex := FFormatCount; result := S_FALSE; end; end; // ----------------------------------------------------------------------------- function TEnumFormatEtc.ReSet: HRESULT; begin fIndex := 0; result := S_OK; end; // ----------------------------------------------------------------------------- function TEnumFormatEtc.Clone(out Enum: IEnumFormatEtc): HRESULT; begin enum := TEnumFormatEtc.Create(FFormatList, FFormatCount, FIndex); result := S_OK; end; // ----------------------------------------------------------------------------- // TDropSource // ----------------------------------------------------------------------------- constructor TDropSource.Create(AOwner: TComponent); begin inherited Create(aOwner); FDataFormatsCount := 0; end; // ----------------------------------------------------------------------------- function TDropSource.QueryGetData(const FormatEtc: TFormatEtc): HRESULT; stdcall; var i: integer; begin result:= S_OK; for i := 0 to FDataFormatsCount-1 do with FDataFormats[i] do begin if (FormatEtc.cfFormat = cfFormat) and (FormatEtc.dwAspect = dwAspect) and (FormatEtc.tymed and tymed <> 0) then exit; //result:= S_OK; end; result:= E_FAIL; end; // ----------------------------------------------------------------------------- function TDropSource.GetEnumFormatEtc(dwDirection: Integer): IEnumFormatEtc; begin if (dwDirection = DATADIR_GET) then Result := TEnumFormatEtc.Create(pFormatList(@FDataFormats), FDataFormatsCount, 0) else result := nil; end; // ----------------------------------------------------------------------------- procedure TDropSource.AddFormatEtc(cfFmt: TClipFormat; pt: PDVTargetDevice; dwAsp, lInd, tym: longint); begin if fDataFormatsCount = MAXFORMATS then exit; FDataFormats[fDataFormatsCount].cfFormat := cfFmt; FDataFormats[fDataFormatsCount].ptd := pt; FDataFormats[fDataFormatsCount].dwAspect := dwAsp; FDataFormats[fDataFormatsCount].lIndex := lInd; FDataFormats[fDataFormatsCount].tymed := tym; inc(FDataFormatsCount); end; // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- function TDropSource.HasFormat(const FormatEtc: TFormatEtc): boolean; begin Result := True; { TODO -oanme -cStopShip : TDropSource.HasFormat needs implementation } end; initialization OleInitialize(NIL); ShGetMalloc(ShellMalloc); finalization ShellMalloc := nil; OleUninitialize; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit REST.Authenticator.OAuth.WebForm.FMX; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.WebBrowser, FMX.StdCtrls; type TOAuth2WebFormRedirectEvent = procedure(const AURL: string; var DoCloseWebView : boolean) of object; TOAuth2WebFormTitleChangedEvent = procedure(const ATitle: string; var DoCloseWebView : boolean) of object; Tfrm_OAuthWebForm = class(TForm) {$NODEFINE Tfrm_OAuthWebForm} Layout1: TLayout; Layout2: TLayout; Layout3: TLayout; WebBrowser: TWebBrowser; btn_Close: TButton; procedure FormCreate(Sender: TObject); procedure WebBrowserShouldStartLoadWithRequest(ASender: TObject; const URL: string); procedure WebBrowserDidFinishLoad(ASender: TObject); procedure btn_CloseClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FOnBeforeRedirect: TOAuth2WebFormRedirectEvent; FOnAfterRedirect: TOAuth2WebFormRedirectEvent; FOnBrowserTitleChanged : TOAuth2WebFormTitleChangedEvent; FLastURL: string; public { Public declarations } procedure ShowWithURL(const AURL: string); property LastURL: string read FLastURL; property OnAfterRedirect: TOAuth2WebFormRedirectEvent read FOnAfterRedirect write FOnAfterRedirect; property OnBeforeRedirect: TOAuth2WebFormRedirectEvent read FOnBeforeRedirect write FOnBeforeRedirect; property OnTitleChanged : TOAuth2WebFormTitleChangedEvent read FOnBrowserTitleChanged write FOnBrowserTitleChanged; end; var frm_OAuthWebForm: Tfrm_OAuthWebForm; {$NODEFINE frm_OAuthWebForm} implementation {$R *.fmx} type TWebBrowserAccess = class(TWebBrowser); procedure Tfrm_OAuthWebForm.btn_CloseClick(Sender: TObject); begin Close; end; procedure Tfrm_OAuthWebForm.FormClose(Sender: TObject; var Action: TCloseAction); begin TWebBrowserAccess(WebBrowser).Hide; end; procedure Tfrm_OAuthWebForm.FormCreate(Sender: TObject); begin FOnAfterRedirect := NIL; FOnBeforeRedirect:= NIL; FOnBrowserTitleChanged:= NIL; FLastURL := ''; end; procedure Tfrm_OAuthWebForm.ShowWithURL(const AURL: string); begin Show; WebBrowser.CanFocus := TRUE; WebBrowser.Navigate( AURL ); WebBrowser.SetFocus; end; procedure Tfrm_OAuthWebForm.WebBrowserDidFinishLoad(ASender: TObject); var LDoCloseForm : boolean; begin FLastURL := WebBrowser.URL; if Assigned(FOnAfterRedirect) then begin LDoCloseForm:= FALSE; FOnAfterRedirect(FLastURL, LDoCloseForm); if LDoCloseForm then self.Close; end; end; procedure Tfrm_OAuthWebForm.WebBrowserShouldStartLoadWithRequest( ASender: TObject; const URL: string); var LDoCloseForm : boolean; begin if Assigned(FOnBeforeRedirect) then begin LDoCloseForm:= FALSE; FOnBeforeRedirect(URL, LDoCloseForm); if LDoCloseForm then begin self.Close; end; end; end; end.
{ ****************************************************************************** } { Fast KDTree Int64 type support } { ****************************************************************************** } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit FastKDTreeI64; {$INCLUDE zDefine.inc} interface uses CoreClasses, PascalStrings, UnicodeMixedLib, KM; const // Int64 KDTree KDT1DI64_Axis = 1; KDT2DI64_Axis = 2; KDT3DI64_Axis = 3; KDT4DI64_Axis = 4; KDT5DI64_Axis = 5; KDT6DI64_Axis = 6; KDT7DI64_Axis = 7; KDT8DI64_Axis = 8; KDT9DI64_Axis = 9; KDT10DI64_Axis = 10; KDT11DI64_Axis = 11; KDT12DI64_Axis = 12; KDT13DI64_Axis = 13; KDT14DI64_Axis = 14; KDT15DI64_Axis = 15; KDT16DI64_Axis = 16; KDT17DI64_Axis = 17; KDT18DI64_Axis = 18; KDT19DI64_Axis = 19; KDT20DI64_Axis = 20; KDT21DI64_Axis = 21; KDT22DI64_Axis = 22; KDT23DI64_Axis = 23; KDT24DI64_Axis = 24; KDT48DI64_Axis = 48; KDT52DI64_Axis = 52; KDT64DI64_Axis = 64; KDT96DI64_Axis = 96; KDT128DI64_Axis = 128; KDT156DI64_Axis = 156; KDT192DI64_Axis = 192; KDT256DI64_Axis = 256; KDT384DI64_Axis = 384; KDT512DI64_Axis = 512; KDT800DI64_Axis = 800; KDT1024DI64_Axis = 1024; type // Int64: KDTree TKDT1DI64 = class; TKDT1DI64_VecType = KM.TKMFloat; // 1D TKDT2DI64 = class; TKDT2DI64_VecType = KM.TKMFloat; // 2D TKDT3DI64 = class; TKDT3DI64_VecType = KM.TKMFloat; // 3D TKDT4DI64 = class; TKDT4DI64_VecType = KM.TKMFloat; // 4D TKDT5DI64 = class; TKDT5DI64_VecType = KM.TKMFloat; // 5D TKDT6DI64 = class; TKDT6DI64_VecType = KM.TKMFloat; // 6D TKDT7DI64 = class; TKDT7DI64_VecType = KM.TKMFloat; // 7D TKDT8DI64 = class; TKDT8DI64_VecType = KM.TKMFloat; // 8D TKDT9DI64 = class; TKDT9DI64_VecType = KM.TKMFloat; // 9D TKDT10DI64 = class; TKDT10DI64_VecType = KM.TKMFloat; // 10D TKDT11DI64 = class; TKDT11DI64_VecType = KM.TKMFloat; // 11D TKDT12DI64 = class; TKDT12DI64_VecType = KM.TKMFloat; // 12D TKDT13DI64 = class; TKDT13DI64_VecType = KM.TKMFloat; // 13D TKDT14DI64 = class; TKDT14DI64_VecType = KM.TKMFloat; // 14D TKDT15DI64 = class; TKDT15DI64_VecType = KM.TKMFloat; // 15D TKDT16DI64 = class; TKDT16DI64_VecType = KM.TKMFloat; // 16D TKDT17DI64 = class; TKDT17DI64_VecType = KM.TKMFloat; // 17D TKDT18DI64 = class; TKDT18DI64_VecType = KM.TKMFloat; // 18D TKDT19DI64 = class; TKDT19DI64_VecType = KM.TKMFloat; // 19D TKDT20DI64 = class; TKDT20DI64_VecType = KM.TKMFloat; // 20D TKDT21DI64 = class; TKDT21DI64_VecType = KM.TKMFloat; // 21D TKDT22DI64 = class; TKDT22DI64_VecType = KM.TKMFloat; // 22D TKDT23DI64 = class; TKDT23DI64_VecType = KM.TKMFloat; // 23D TKDT24DI64 = class; TKDT24DI64_VecType = KM.TKMFloat; // 24D TKDT48DI64 = class; TKDT48DI64_VecType = KM.TKMFloat; // 48D TKDT52DI64 = class; TKDT52DI64_VecType = KM.TKMFloat; // 52D TKDT64DI64 = class; TKDT64DI64_VecType = KM.TKMFloat; // 64D TKDT96DI64 = class; TKDT96DI64_VecType = KM.TKMFloat; // 96D TKDT128DI64 = class; TKDT128DI64_VecType = KM.TKMFloat; // 128D TKDT156DI64 = class; TKDT156DI64_VecType = KM.TKMFloat; // 156D TKDT192DI64 = class; TKDT192DI64_VecType = KM.TKMFloat; // 192D TKDT256DI64 = class; TKDT256DI64_VecType = KM.TKMFloat; // 256D TKDT384DI64 = class; TKDT384DI64_VecType = KM.TKMFloat; // 384D TKDT512DI64 = class; TKDT512DI64_VecType = KM.TKMFloat; // 512D TKDT800DI64 = class; TKDT800DI64_VecType = KM.TKMFloat; // 800D TKDT1024DI64 = class; TKDT1024DI64_VecType = KM.TKMFloat; // 1024D // Int64 KDTree TKDT1DI64 = class(TCoreClassObject) public type // code split TKDT1DI64_Vec = array [0 .. KDT1DI64_Axis - 1] of TKDT1DI64_VecType; PKDT1DI64_Vec = ^TKDT1DI64_Vec; TKDT1DI64_DynamicVecBuffer = array of TKDT1DI64_Vec; PKDT1DI64_DynamicVecBuffer = ^TKDT1DI64_DynamicVecBuffer; TKDT1DI64_Source = record buff: TKDT1DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT1DI64_Source = ^TKDT1DI64_Source; TKDT1DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1DI64_Source) - 1] of PKDT1DI64_Source; PKDT1DI64_SourceBuffer = ^TKDT1DI64_SourceBuffer; TKDT1DI64_DyanmicSourceBuffer = array of PKDT1DI64_Source; PKDT1DI64_DyanmicSourceBuffer = ^TKDT1DI64_DyanmicSourceBuffer; TKDT1DI64_DyanmicStoreBuffer = array of TKDT1DI64_Source; PKDT1DI64_DyanmicStoreBuffer = ^TKDT1DI64_DyanmicStoreBuffer; PKDT1DI64_Node = ^TKDT1DI64_Node; TKDT1DI64_Node = record Parent, Right, Left: PKDT1DI64_Node; Vec: PKDT1DI64_Source; end; TKDT1DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer); TKDT1DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT1DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT1DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT1DI64_DyanmicStoreBuffer; KDBuff: TKDT1DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT1DI64_Node; TestBuff: TKDT1DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DI64_Node; function GetData(const Index: NativeInt): PKDT1DI64_Source; public RootNode: PKDT1DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT1DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT1DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT1DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT1DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildProc); overload; { search } function Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DI64_Node; overload; function Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DI64_Node; overload; function Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double): PKDT1DI64_Node; overload; function Search(const buff: TKDT1DI64_Vec): PKDT1DI64_Node; overload; function SearchToken(const buff: TKDT1DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT1DI64_DynamicVecBuffer; var OutBuff: TKDT1DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT1DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT1DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT1DI64_Vec; overload; class function Vec(const v: TKDT1DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT1DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer); class procedure Test; end; TKDT2DI64 = class(TCoreClassObject) public type // code split TKDT2DI64_Vec = array [0 .. KDT2DI64_Axis - 1] of TKDT2DI64_VecType; PKDT2DI64_Vec = ^TKDT2DI64_Vec; TKDT2DI64_DynamicVecBuffer = array of TKDT2DI64_Vec; PKDT2DI64_DynamicVecBuffer = ^TKDT2DI64_DynamicVecBuffer; TKDT2DI64_Source = record buff: TKDT2DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT2DI64_Source = ^TKDT2DI64_Source; TKDT2DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT2DI64_Source) - 1] of PKDT2DI64_Source; PKDT2DI64_SourceBuffer = ^TKDT2DI64_SourceBuffer; TKDT2DI64_DyanmicSourceBuffer = array of PKDT2DI64_Source; PKDT2DI64_DyanmicSourceBuffer = ^TKDT2DI64_DyanmicSourceBuffer; TKDT2DI64_DyanmicStoreBuffer = array of TKDT2DI64_Source; PKDT2DI64_DyanmicStoreBuffer = ^TKDT2DI64_DyanmicStoreBuffer; PKDT2DI64_Node = ^TKDT2DI64_Node; TKDT2DI64_Node = record Parent, Right, Left: PKDT2DI64_Node; Vec: PKDT2DI64_Source; end; TKDT2DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer); TKDT2DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT2DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT2DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT2DI64_DyanmicStoreBuffer; KDBuff: TKDT2DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT2DI64_Node; TestBuff: TKDT2DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DI64_Node; function GetData(const Index: NativeInt): PKDT2DI64_Source; public RootNode: PKDT2DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT2DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT2DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT2DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT2DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildProc); overload; { search } function Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DI64_Node; overload; function Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DI64_Node; overload; function Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double): PKDT2DI64_Node; overload; function Search(const buff: TKDT2DI64_Vec): PKDT2DI64_Node; overload; function SearchToken(const buff: TKDT2DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT2DI64_DynamicVecBuffer; var OutBuff: TKDT2DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT2DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT2DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT2DI64_Vec; overload; class function Vec(const v: TKDT2DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT2DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer); class procedure Test; end; TKDT3DI64 = class(TCoreClassObject) public type // code split TKDT3DI64_Vec = array [0 .. KDT3DI64_Axis - 1] of TKDT3DI64_VecType; PKDT3DI64_Vec = ^TKDT3DI64_Vec; TKDT3DI64_DynamicVecBuffer = array of TKDT3DI64_Vec; PKDT3DI64_DynamicVecBuffer = ^TKDT3DI64_DynamicVecBuffer; TKDT3DI64_Source = record buff: TKDT3DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT3DI64_Source = ^TKDT3DI64_Source; TKDT3DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT3DI64_Source) - 1] of PKDT3DI64_Source; PKDT3DI64_SourceBuffer = ^TKDT3DI64_SourceBuffer; TKDT3DI64_DyanmicSourceBuffer = array of PKDT3DI64_Source; PKDT3DI64_DyanmicSourceBuffer = ^TKDT3DI64_DyanmicSourceBuffer; TKDT3DI64_DyanmicStoreBuffer = array of TKDT3DI64_Source; PKDT3DI64_DyanmicStoreBuffer = ^TKDT3DI64_DyanmicStoreBuffer; PKDT3DI64_Node = ^TKDT3DI64_Node; TKDT3DI64_Node = record Parent, Right, Left: PKDT3DI64_Node; Vec: PKDT3DI64_Source; end; TKDT3DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer); TKDT3DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT3DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT3DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT3DI64_DyanmicStoreBuffer; KDBuff: TKDT3DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT3DI64_Node; TestBuff: TKDT3DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DI64_Node; function GetData(const Index: NativeInt): PKDT3DI64_Source; public RootNode: PKDT3DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT3DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT3DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT3DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT3DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildProc); overload; { search } function Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DI64_Node; overload; function Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DI64_Node; overload; function Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double): PKDT3DI64_Node; overload; function Search(const buff: TKDT3DI64_Vec): PKDT3DI64_Node; overload; function SearchToken(const buff: TKDT3DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT3DI64_DynamicVecBuffer; var OutBuff: TKDT3DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT3DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT3DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT3DI64_Vec; overload; class function Vec(const v: TKDT3DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT3DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer); class procedure Test; end; TKDT4DI64 = class(TCoreClassObject) public type // code split TKDT4DI64_Vec = array [0 .. KDT4DI64_Axis - 1] of TKDT4DI64_VecType; PKDT4DI64_Vec = ^TKDT4DI64_Vec; TKDT4DI64_DynamicVecBuffer = array of TKDT4DI64_Vec; PKDT4DI64_DynamicVecBuffer = ^TKDT4DI64_DynamicVecBuffer; TKDT4DI64_Source = record buff: TKDT4DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT4DI64_Source = ^TKDT4DI64_Source; TKDT4DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT4DI64_Source) - 1] of PKDT4DI64_Source; PKDT4DI64_SourceBuffer = ^TKDT4DI64_SourceBuffer; TKDT4DI64_DyanmicSourceBuffer = array of PKDT4DI64_Source; PKDT4DI64_DyanmicSourceBuffer = ^TKDT4DI64_DyanmicSourceBuffer; TKDT4DI64_DyanmicStoreBuffer = array of TKDT4DI64_Source; PKDT4DI64_DyanmicStoreBuffer = ^TKDT4DI64_DyanmicStoreBuffer; PKDT4DI64_Node = ^TKDT4DI64_Node; TKDT4DI64_Node = record Parent, Right, Left: PKDT4DI64_Node; Vec: PKDT4DI64_Source; end; TKDT4DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer); TKDT4DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT4DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT4DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT4DI64_DyanmicStoreBuffer; KDBuff: TKDT4DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT4DI64_Node; TestBuff: TKDT4DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DI64_Node; function GetData(const Index: NativeInt): PKDT4DI64_Source; public RootNode: PKDT4DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT4DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT4DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT4DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT4DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildProc); overload; { search } function Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DI64_Node; overload; function Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DI64_Node; overload; function Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double): PKDT4DI64_Node; overload; function Search(const buff: TKDT4DI64_Vec): PKDT4DI64_Node; overload; function SearchToken(const buff: TKDT4DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT4DI64_DynamicVecBuffer; var OutBuff: TKDT4DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT4DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT4DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT4DI64_Vec; overload; class function Vec(const v: TKDT4DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT4DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer); class procedure Test; end; TKDT5DI64 = class(TCoreClassObject) public type // code split TKDT5DI64_Vec = array [0 .. KDT5DI64_Axis - 1] of TKDT5DI64_VecType; PKDT5DI64_Vec = ^TKDT5DI64_Vec; TKDT5DI64_DynamicVecBuffer = array of TKDT5DI64_Vec; PKDT5DI64_DynamicVecBuffer = ^TKDT5DI64_DynamicVecBuffer; TKDT5DI64_Source = record buff: TKDT5DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT5DI64_Source = ^TKDT5DI64_Source; TKDT5DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT5DI64_Source) - 1] of PKDT5DI64_Source; PKDT5DI64_SourceBuffer = ^TKDT5DI64_SourceBuffer; TKDT5DI64_DyanmicSourceBuffer = array of PKDT5DI64_Source; PKDT5DI64_DyanmicSourceBuffer = ^TKDT5DI64_DyanmicSourceBuffer; TKDT5DI64_DyanmicStoreBuffer = array of TKDT5DI64_Source; PKDT5DI64_DyanmicStoreBuffer = ^TKDT5DI64_DyanmicStoreBuffer; PKDT5DI64_Node = ^TKDT5DI64_Node; TKDT5DI64_Node = record Parent, Right, Left: PKDT5DI64_Node; Vec: PKDT5DI64_Source; end; TKDT5DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer); TKDT5DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT5DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT5DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT5DI64_DyanmicStoreBuffer; KDBuff: TKDT5DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT5DI64_Node; TestBuff: TKDT5DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DI64_Node; function GetData(const Index: NativeInt): PKDT5DI64_Source; public RootNode: PKDT5DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT5DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT5DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT5DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT5DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildProc); overload; { search } function Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DI64_Node; overload; function Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DI64_Node; overload; function Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double): PKDT5DI64_Node; overload; function Search(const buff: TKDT5DI64_Vec): PKDT5DI64_Node; overload; function SearchToken(const buff: TKDT5DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT5DI64_DynamicVecBuffer; var OutBuff: TKDT5DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT5DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT5DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT5DI64_Vec; overload; class function Vec(const v: TKDT5DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT5DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer); class procedure Test; end; TKDT6DI64 = class(TCoreClassObject) public type // code split TKDT6DI64_Vec = array [0 .. KDT6DI64_Axis - 1] of TKDT6DI64_VecType; PKDT6DI64_Vec = ^TKDT6DI64_Vec; TKDT6DI64_DynamicVecBuffer = array of TKDT6DI64_Vec; PKDT6DI64_DynamicVecBuffer = ^TKDT6DI64_DynamicVecBuffer; TKDT6DI64_Source = record buff: TKDT6DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT6DI64_Source = ^TKDT6DI64_Source; TKDT6DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT6DI64_Source) - 1] of PKDT6DI64_Source; PKDT6DI64_SourceBuffer = ^TKDT6DI64_SourceBuffer; TKDT6DI64_DyanmicSourceBuffer = array of PKDT6DI64_Source; PKDT6DI64_DyanmicSourceBuffer = ^TKDT6DI64_DyanmicSourceBuffer; TKDT6DI64_DyanmicStoreBuffer = array of TKDT6DI64_Source; PKDT6DI64_DyanmicStoreBuffer = ^TKDT6DI64_DyanmicStoreBuffer; PKDT6DI64_Node = ^TKDT6DI64_Node; TKDT6DI64_Node = record Parent, Right, Left: PKDT6DI64_Node; Vec: PKDT6DI64_Source; end; TKDT6DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer); TKDT6DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT6DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT6DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT6DI64_DyanmicStoreBuffer; KDBuff: TKDT6DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT6DI64_Node; TestBuff: TKDT6DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DI64_Node; function GetData(const Index: NativeInt): PKDT6DI64_Source; public RootNode: PKDT6DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT6DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT6DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT6DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT6DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildProc); overload; { search } function Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DI64_Node; overload; function Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DI64_Node; overload; function Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double): PKDT6DI64_Node; overload; function Search(const buff: TKDT6DI64_Vec): PKDT6DI64_Node; overload; function SearchToken(const buff: TKDT6DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT6DI64_DynamicVecBuffer; var OutBuff: TKDT6DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT6DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT6DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT6DI64_Vec; overload; class function Vec(const v: TKDT6DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT6DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer); class procedure Test; end; TKDT7DI64 = class(TCoreClassObject) public type // code split TKDT7DI64_Vec = array [0 .. KDT7DI64_Axis - 1] of TKDT7DI64_VecType; PKDT7DI64_Vec = ^TKDT7DI64_Vec; TKDT7DI64_DynamicVecBuffer = array of TKDT7DI64_Vec; PKDT7DI64_DynamicVecBuffer = ^TKDT7DI64_DynamicVecBuffer; TKDT7DI64_Source = record buff: TKDT7DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT7DI64_Source = ^TKDT7DI64_Source; TKDT7DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT7DI64_Source) - 1] of PKDT7DI64_Source; PKDT7DI64_SourceBuffer = ^TKDT7DI64_SourceBuffer; TKDT7DI64_DyanmicSourceBuffer = array of PKDT7DI64_Source; PKDT7DI64_DyanmicSourceBuffer = ^TKDT7DI64_DyanmicSourceBuffer; TKDT7DI64_DyanmicStoreBuffer = array of TKDT7DI64_Source; PKDT7DI64_DyanmicStoreBuffer = ^TKDT7DI64_DyanmicStoreBuffer; PKDT7DI64_Node = ^TKDT7DI64_Node; TKDT7DI64_Node = record Parent, Right, Left: PKDT7DI64_Node; Vec: PKDT7DI64_Source; end; TKDT7DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer); TKDT7DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT7DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT7DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT7DI64_DyanmicStoreBuffer; KDBuff: TKDT7DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT7DI64_Node; TestBuff: TKDT7DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DI64_Node; function GetData(const Index: NativeInt): PKDT7DI64_Source; public RootNode: PKDT7DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT7DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT7DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT7DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT7DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildProc); overload; { search } function Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DI64_Node; overload; function Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DI64_Node; overload; function Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double): PKDT7DI64_Node; overload; function Search(const buff: TKDT7DI64_Vec): PKDT7DI64_Node; overload; function SearchToken(const buff: TKDT7DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT7DI64_DynamicVecBuffer; var OutBuff: TKDT7DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT7DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT7DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT7DI64_Vec; overload; class function Vec(const v: TKDT7DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT7DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer); class procedure Test; end; TKDT8DI64 = class(TCoreClassObject) public type // code split TKDT8DI64_Vec = array [0 .. KDT8DI64_Axis - 1] of TKDT8DI64_VecType; PKDT8DI64_Vec = ^TKDT8DI64_Vec; TKDT8DI64_DynamicVecBuffer = array of TKDT8DI64_Vec; PKDT8DI64_DynamicVecBuffer = ^TKDT8DI64_DynamicVecBuffer; TKDT8DI64_Source = record buff: TKDT8DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT8DI64_Source = ^TKDT8DI64_Source; TKDT8DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT8DI64_Source) - 1] of PKDT8DI64_Source; PKDT8DI64_SourceBuffer = ^TKDT8DI64_SourceBuffer; TKDT8DI64_DyanmicSourceBuffer = array of PKDT8DI64_Source; PKDT8DI64_DyanmicSourceBuffer = ^TKDT8DI64_DyanmicSourceBuffer; TKDT8DI64_DyanmicStoreBuffer = array of TKDT8DI64_Source; PKDT8DI64_DyanmicStoreBuffer = ^TKDT8DI64_DyanmicStoreBuffer; PKDT8DI64_Node = ^TKDT8DI64_Node; TKDT8DI64_Node = record Parent, Right, Left: PKDT8DI64_Node; Vec: PKDT8DI64_Source; end; TKDT8DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer); TKDT8DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT8DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT8DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT8DI64_DyanmicStoreBuffer; KDBuff: TKDT8DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT8DI64_Node; TestBuff: TKDT8DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DI64_Node; function GetData(const Index: NativeInt): PKDT8DI64_Source; public RootNode: PKDT8DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT8DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT8DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT8DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT8DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildProc); overload; { search } function Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DI64_Node; overload; function Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DI64_Node; overload; function Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double): PKDT8DI64_Node; overload; function Search(const buff: TKDT8DI64_Vec): PKDT8DI64_Node; overload; function SearchToken(const buff: TKDT8DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT8DI64_DynamicVecBuffer; var OutBuff: TKDT8DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT8DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT8DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT8DI64_Vec; overload; class function Vec(const v: TKDT8DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT8DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer); class procedure Test; end; TKDT9DI64 = class(TCoreClassObject) public type // code split TKDT9DI64_Vec = array [0 .. KDT9DI64_Axis - 1] of TKDT9DI64_VecType; PKDT9DI64_Vec = ^TKDT9DI64_Vec; TKDT9DI64_DynamicVecBuffer = array of TKDT9DI64_Vec; PKDT9DI64_DynamicVecBuffer = ^TKDT9DI64_DynamicVecBuffer; TKDT9DI64_Source = record buff: TKDT9DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT9DI64_Source = ^TKDT9DI64_Source; TKDT9DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT9DI64_Source) - 1] of PKDT9DI64_Source; PKDT9DI64_SourceBuffer = ^TKDT9DI64_SourceBuffer; TKDT9DI64_DyanmicSourceBuffer = array of PKDT9DI64_Source; PKDT9DI64_DyanmicSourceBuffer = ^TKDT9DI64_DyanmicSourceBuffer; TKDT9DI64_DyanmicStoreBuffer = array of TKDT9DI64_Source; PKDT9DI64_DyanmicStoreBuffer = ^TKDT9DI64_DyanmicStoreBuffer; PKDT9DI64_Node = ^TKDT9DI64_Node; TKDT9DI64_Node = record Parent, Right, Left: PKDT9DI64_Node; Vec: PKDT9DI64_Source; end; TKDT9DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer); TKDT9DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT9DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT9DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT9DI64_DyanmicStoreBuffer; KDBuff: TKDT9DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT9DI64_Node; TestBuff: TKDT9DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DI64_Node; function GetData(const Index: NativeInt): PKDT9DI64_Source; public RootNode: PKDT9DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT9DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT9DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT9DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT9DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildProc); overload; { search } function Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DI64_Node; overload; function Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DI64_Node; overload; function Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double): PKDT9DI64_Node; overload; function Search(const buff: TKDT9DI64_Vec): PKDT9DI64_Node; overload; function SearchToken(const buff: TKDT9DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT9DI64_DynamicVecBuffer; var OutBuff: TKDT9DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT9DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT9DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT9DI64_Vec; overload; class function Vec(const v: TKDT9DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT9DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer); class procedure Test; end; TKDT10DI64 = class(TCoreClassObject) public type // code split TKDT10DI64_Vec = array [0 .. KDT10DI64_Axis - 1] of TKDT10DI64_VecType; PKDT10DI64_Vec = ^TKDT10DI64_Vec; TKDT10DI64_DynamicVecBuffer = array of TKDT10DI64_Vec; PKDT10DI64_DynamicVecBuffer = ^TKDT10DI64_DynamicVecBuffer; TKDT10DI64_Source = record buff: TKDT10DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT10DI64_Source = ^TKDT10DI64_Source; TKDT10DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT10DI64_Source) - 1] of PKDT10DI64_Source; PKDT10DI64_SourceBuffer = ^TKDT10DI64_SourceBuffer; TKDT10DI64_DyanmicSourceBuffer = array of PKDT10DI64_Source; PKDT10DI64_DyanmicSourceBuffer = ^TKDT10DI64_DyanmicSourceBuffer; TKDT10DI64_DyanmicStoreBuffer = array of TKDT10DI64_Source; PKDT10DI64_DyanmicStoreBuffer = ^TKDT10DI64_DyanmicStoreBuffer; PKDT10DI64_Node = ^TKDT10DI64_Node; TKDT10DI64_Node = record Parent, Right, Left: PKDT10DI64_Node; Vec: PKDT10DI64_Source; end; TKDT10DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer); TKDT10DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT10DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT10DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT10DI64_DyanmicStoreBuffer; KDBuff: TKDT10DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT10DI64_Node; TestBuff: TKDT10DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DI64_Node; function GetData(const Index: NativeInt): PKDT10DI64_Source; public RootNode: PKDT10DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT10DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT10DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT10DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT10DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildProc); overload; { search } function Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DI64_Node; overload; function Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DI64_Node; overload; function Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double): PKDT10DI64_Node; overload; function Search(const buff: TKDT10DI64_Vec): PKDT10DI64_Node; overload; function SearchToken(const buff: TKDT10DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT10DI64_DynamicVecBuffer; var OutBuff: TKDT10DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT10DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT10DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT10DI64_Vec; overload; class function Vec(const v: TKDT10DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT10DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer); class procedure Test; end; TKDT11DI64 = class(TCoreClassObject) public type // code split TKDT11DI64_Vec = array [0 .. KDT11DI64_Axis - 1] of TKDT11DI64_VecType; PKDT11DI64_Vec = ^TKDT11DI64_Vec; TKDT11DI64_DynamicVecBuffer = array of TKDT11DI64_Vec; PKDT11DI64_DynamicVecBuffer = ^TKDT11DI64_DynamicVecBuffer; TKDT11DI64_Source = record buff: TKDT11DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT11DI64_Source = ^TKDT11DI64_Source; TKDT11DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT11DI64_Source) - 1] of PKDT11DI64_Source; PKDT11DI64_SourceBuffer = ^TKDT11DI64_SourceBuffer; TKDT11DI64_DyanmicSourceBuffer = array of PKDT11DI64_Source; PKDT11DI64_DyanmicSourceBuffer = ^TKDT11DI64_DyanmicSourceBuffer; TKDT11DI64_DyanmicStoreBuffer = array of TKDT11DI64_Source; PKDT11DI64_DyanmicStoreBuffer = ^TKDT11DI64_DyanmicStoreBuffer; PKDT11DI64_Node = ^TKDT11DI64_Node; TKDT11DI64_Node = record Parent, Right, Left: PKDT11DI64_Node; Vec: PKDT11DI64_Source; end; TKDT11DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer); TKDT11DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT11DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT11DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT11DI64_DyanmicStoreBuffer; KDBuff: TKDT11DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT11DI64_Node; TestBuff: TKDT11DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DI64_Node; function GetData(const Index: NativeInt): PKDT11DI64_Source; public RootNode: PKDT11DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT11DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT11DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT11DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT11DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildProc); overload; { search } function Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DI64_Node; overload; function Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DI64_Node; overload; function Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double): PKDT11DI64_Node; overload; function Search(const buff: TKDT11DI64_Vec): PKDT11DI64_Node; overload; function SearchToken(const buff: TKDT11DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT11DI64_DynamicVecBuffer; var OutBuff: TKDT11DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT11DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT11DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT11DI64_Vec; overload; class function Vec(const v: TKDT11DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT11DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer); class procedure Test; end; TKDT12DI64 = class(TCoreClassObject) public type // code split TKDT12DI64_Vec = array [0 .. KDT12DI64_Axis - 1] of TKDT12DI64_VecType; PKDT12DI64_Vec = ^TKDT12DI64_Vec; TKDT12DI64_DynamicVecBuffer = array of TKDT12DI64_Vec; PKDT12DI64_DynamicVecBuffer = ^TKDT12DI64_DynamicVecBuffer; TKDT12DI64_Source = record buff: TKDT12DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT12DI64_Source = ^TKDT12DI64_Source; TKDT12DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT12DI64_Source) - 1] of PKDT12DI64_Source; PKDT12DI64_SourceBuffer = ^TKDT12DI64_SourceBuffer; TKDT12DI64_DyanmicSourceBuffer = array of PKDT12DI64_Source; PKDT12DI64_DyanmicSourceBuffer = ^TKDT12DI64_DyanmicSourceBuffer; TKDT12DI64_DyanmicStoreBuffer = array of TKDT12DI64_Source; PKDT12DI64_DyanmicStoreBuffer = ^TKDT12DI64_DyanmicStoreBuffer; PKDT12DI64_Node = ^TKDT12DI64_Node; TKDT12DI64_Node = record Parent, Right, Left: PKDT12DI64_Node; Vec: PKDT12DI64_Source; end; TKDT12DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer); TKDT12DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT12DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT12DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT12DI64_DyanmicStoreBuffer; KDBuff: TKDT12DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT12DI64_Node; TestBuff: TKDT12DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DI64_Node; function GetData(const Index: NativeInt): PKDT12DI64_Source; public RootNode: PKDT12DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT12DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT12DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT12DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT12DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildProc); overload; { search } function Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DI64_Node; overload; function Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DI64_Node; overload; function Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double): PKDT12DI64_Node; overload; function Search(const buff: TKDT12DI64_Vec): PKDT12DI64_Node; overload; function SearchToken(const buff: TKDT12DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT12DI64_DynamicVecBuffer; var OutBuff: TKDT12DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT12DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT12DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT12DI64_Vec; overload; class function Vec(const v: TKDT12DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT12DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer); class procedure Test; end; TKDT13DI64 = class(TCoreClassObject) public type // code split TKDT13DI64_Vec = array [0 .. KDT13DI64_Axis - 1] of TKDT13DI64_VecType; PKDT13DI64_Vec = ^TKDT13DI64_Vec; TKDT13DI64_DynamicVecBuffer = array of TKDT13DI64_Vec; PKDT13DI64_DynamicVecBuffer = ^TKDT13DI64_DynamicVecBuffer; TKDT13DI64_Source = record buff: TKDT13DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT13DI64_Source = ^TKDT13DI64_Source; TKDT13DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT13DI64_Source) - 1] of PKDT13DI64_Source; PKDT13DI64_SourceBuffer = ^TKDT13DI64_SourceBuffer; TKDT13DI64_DyanmicSourceBuffer = array of PKDT13DI64_Source; PKDT13DI64_DyanmicSourceBuffer = ^TKDT13DI64_DyanmicSourceBuffer; TKDT13DI64_DyanmicStoreBuffer = array of TKDT13DI64_Source; PKDT13DI64_DyanmicStoreBuffer = ^TKDT13DI64_DyanmicStoreBuffer; PKDT13DI64_Node = ^TKDT13DI64_Node; TKDT13DI64_Node = record Parent, Right, Left: PKDT13DI64_Node; Vec: PKDT13DI64_Source; end; TKDT13DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer); TKDT13DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT13DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT13DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT13DI64_DyanmicStoreBuffer; KDBuff: TKDT13DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT13DI64_Node; TestBuff: TKDT13DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DI64_Node; function GetData(const Index: NativeInt): PKDT13DI64_Source; public RootNode: PKDT13DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT13DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT13DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT13DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT13DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildProc); overload; { search } function Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DI64_Node; overload; function Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DI64_Node; overload; function Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double): PKDT13DI64_Node; overload; function Search(const buff: TKDT13DI64_Vec): PKDT13DI64_Node; overload; function SearchToken(const buff: TKDT13DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT13DI64_DynamicVecBuffer; var OutBuff: TKDT13DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT13DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT13DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT13DI64_Vec; overload; class function Vec(const v: TKDT13DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT13DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer); class procedure Test; end; TKDT14DI64 = class(TCoreClassObject) public type // code split TKDT14DI64_Vec = array [0 .. KDT14DI64_Axis - 1] of TKDT14DI64_VecType; PKDT14DI64_Vec = ^TKDT14DI64_Vec; TKDT14DI64_DynamicVecBuffer = array of TKDT14DI64_Vec; PKDT14DI64_DynamicVecBuffer = ^TKDT14DI64_DynamicVecBuffer; TKDT14DI64_Source = record buff: TKDT14DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT14DI64_Source = ^TKDT14DI64_Source; TKDT14DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT14DI64_Source) - 1] of PKDT14DI64_Source; PKDT14DI64_SourceBuffer = ^TKDT14DI64_SourceBuffer; TKDT14DI64_DyanmicSourceBuffer = array of PKDT14DI64_Source; PKDT14DI64_DyanmicSourceBuffer = ^TKDT14DI64_DyanmicSourceBuffer; TKDT14DI64_DyanmicStoreBuffer = array of TKDT14DI64_Source; PKDT14DI64_DyanmicStoreBuffer = ^TKDT14DI64_DyanmicStoreBuffer; PKDT14DI64_Node = ^TKDT14DI64_Node; TKDT14DI64_Node = record Parent, Right, Left: PKDT14DI64_Node; Vec: PKDT14DI64_Source; end; TKDT14DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer); TKDT14DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT14DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT14DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT14DI64_DyanmicStoreBuffer; KDBuff: TKDT14DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT14DI64_Node; TestBuff: TKDT14DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DI64_Node; function GetData(const Index: NativeInt): PKDT14DI64_Source; public RootNode: PKDT14DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT14DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT14DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT14DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT14DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildProc); overload; { search } function Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DI64_Node; overload; function Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DI64_Node; overload; function Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double): PKDT14DI64_Node; overload; function Search(const buff: TKDT14DI64_Vec): PKDT14DI64_Node; overload; function SearchToken(const buff: TKDT14DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT14DI64_DynamicVecBuffer; var OutBuff: TKDT14DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT14DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT14DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT14DI64_Vec; overload; class function Vec(const v: TKDT14DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT14DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer); class procedure Test; end; TKDT15DI64 = class(TCoreClassObject) public type // code split TKDT15DI64_Vec = array [0 .. KDT15DI64_Axis - 1] of TKDT15DI64_VecType; PKDT15DI64_Vec = ^TKDT15DI64_Vec; TKDT15DI64_DynamicVecBuffer = array of TKDT15DI64_Vec; PKDT15DI64_DynamicVecBuffer = ^TKDT15DI64_DynamicVecBuffer; TKDT15DI64_Source = record buff: TKDT15DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT15DI64_Source = ^TKDT15DI64_Source; TKDT15DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT15DI64_Source) - 1] of PKDT15DI64_Source; PKDT15DI64_SourceBuffer = ^TKDT15DI64_SourceBuffer; TKDT15DI64_DyanmicSourceBuffer = array of PKDT15DI64_Source; PKDT15DI64_DyanmicSourceBuffer = ^TKDT15DI64_DyanmicSourceBuffer; TKDT15DI64_DyanmicStoreBuffer = array of TKDT15DI64_Source; PKDT15DI64_DyanmicStoreBuffer = ^TKDT15DI64_DyanmicStoreBuffer; PKDT15DI64_Node = ^TKDT15DI64_Node; TKDT15DI64_Node = record Parent, Right, Left: PKDT15DI64_Node; Vec: PKDT15DI64_Source; end; TKDT15DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer); TKDT15DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT15DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT15DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT15DI64_DyanmicStoreBuffer; KDBuff: TKDT15DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT15DI64_Node; TestBuff: TKDT15DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DI64_Node; function GetData(const Index: NativeInt): PKDT15DI64_Source; public RootNode: PKDT15DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT15DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT15DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT15DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT15DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildProc); overload; { search } function Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DI64_Node; overload; function Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DI64_Node; overload; function Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double): PKDT15DI64_Node; overload; function Search(const buff: TKDT15DI64_Vec): PKDT15DI64_Node; overload; function SearchToken(const buff: TKDT15DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT15DI64_DynamicVecBuffer; var OutBuff: TKDT15DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT15DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT15DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT15DI64_Vec; overload; class function Vec(const v: TKDT15DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT15DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer); class procedure Test; end; TKDT16DI64 = class(TCoreClassObject) public type // code split TKDT16DI64_Vec = array [0 .. KDT16DI64_Axis - 1] of TKDT16DI64_VecType; PKDT16DI64_Vec = ^TKDT16DI64_Vec; TKDT16DI64_DynamicVecBuffer = array of TKDT16DI64_Vec; PKDT16DI64_DynamicVecBuffer = ^TKDT16DI64_DynamicVecBuffer; TKDT16DI64_Source = record buff: TKDT16DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT16DI64_Source = ^TKDT16DI64_Source; TKDT16DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT16DI64_Source) - 1] of PKDT16DI64_Source; PKDT16DI64_SourceBuffer = ^TKDT16DI64_SourceBuffer; TKDT16DI64_DyanmicSourceBuffer = array of PKDT16DI64_Source; PKDT16DI64_DyanmicSourceBuffer = ^TKDT16DI64_DyanmicSourceBuffer; TKDT16DI64_DyanmicStoreBuffer = array of TKDT16DI64_Source; PKDT16DI64_DyanmicStoreBuffer = ^TKDT16DI64_DyanmicStoreBuffer; PKDT16DI64_Node = ^TKDT16DI64_Node; TKDT16DI64_Node = record Parent, Right, Left: PKDT16DI64_Node; Vec: PKDT16DI64_Source; end; TKDT16DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer); TKDT16DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT16DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT16DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT16DI64_DyanmicStoreBuffer; KDBuff: TKDT16DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT16DI64_Node; TestBuff: TKDT16DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DI64_Node; function GetData(const Index: NativeInt): PKDT16DI64_Source; public RootNode: PKDT16DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT16DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT16DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT16DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT16DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildProc); overload; { search } function Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DI64_Node; overload; function Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DI64_Node; overload; function Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double): PKDT16DI64_Node; overload; function Search(const buff: TKDT16DI64_Vec): PKDT16DI64_Node; overload; function SearchToken(const buff: TKDT16DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT16DI64_DynamicVecBuffer; var OutBuff: TKDT16DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT16DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT16DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT16DI64_Vec; overload; class function Vec(const v: TKDT16DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT16DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer); class procedure Test; end; TKDT17DI64 = class(TCoreClassObject) public type // code split TKDT17DI64_Vec = array [0 .. KDT17DI64_Axis - 1] of TKDT17DI64_VecType; PKDT17DI64_Vec = ^TKDT17DI64_Vec; TKDT17DI64_DynamicVecBuffer = array of TKDT17DI64_Vec; PKDT17DI64_DynamicVecBuffer = ^TKDT17DI64_DynamicVecBuffer; TKDT17DI64_Source = record buff: TKDT17DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT17DI64_Source = ^TKDT17DI64_Source; TKDT17DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT17DI64_Source) - 1] of PKDT17DI64_Source; PKDT17DI64_SourceBuffer = ^TKDT17DI64_SourceBuffer; TKDT17DI64_DyanmicSourceBuffer = array of PKDT17DI64_Source; PKDT17DI64_DyanmicSourceBuffer = ^TKDT17DI64_DyanmicSourceBuffer; TKDT17DI64_DyanmicStoreBuffer = array of TKDT17DI64_Source; PKDT17DI64_DyanmicStoreBuffer = ^TKDT17DI64_DyanmicStoreBuffer; PKDT17DI64_Node = ^TKDT17DI64_Node; TKDT17DI64_Node = record Parent, Right, Left: PKDT17DI64_Node; Vec: PKDT17DI64_Source; end; TKDT17DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer); TKDT17DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT17DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT17DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT17DI64_DyanmicStoreBuffer; KDBuff: TKDT17DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT17DI64_Node; TestBuff: TKDT17DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DI64_Node; function GetData(const Index: NativeInt): PKDT17DI64_Source; public RootNode: PKDT17DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT17DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT17DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT17DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT17DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildProc); overload; { search } function Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DI64_Node; overload; function Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DI64_Node; overload; function Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double): PKDT17DI64_Node; overload; function Search(const buff: TKDT17DI64_Vec): PKDT17DI64_Node; overload; function SearchToken(const buff: TKDT17DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT17DI64_DynamicVecBuffer; var OutBuff: TKDT17DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT17DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT17DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT17DI64_Vec; overload; class function Vec(const v: TKDT17DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT17DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer); class procedure Test; end; TKDT18DI64 = class(TCoreClassObject) public type // code split TKDT18DI64_Vec = array [0 .. KDT18DI64_Axis - 1] of TKDT18DI64_VecType; PKDT18DI64_Vec = ^TKDT18DI64_Vec; TKDT18DI64_DynamicVecBuffer = array of TKDT18DI64_Vec; PKDT18DI64_DynamicVecBuffer = ^TKDT18DI64_DynamicVecBuffer; TKDT18DI64_Source = record buff: TKDT18DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT18DI64_Source = ^TKDT18DI64_Source; TKDT18DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT18DI64_Source) - 1] of PKDT18DI64_Source; PKDT18DI64_SourceBuffer = ^TKDT18DI64_SourceBuffer; TKDT18DI64_DyanmicSourceBuffer = array of PKDT18DI64_Source; PKDT18DI64_DyanmicSourceBuffer = ^TKDT18DI64_DyanmicSourceBuffer; TKDT18DI64_DyanmicStoreBuffer = array of TKDT18DI64_Source; PKDT18DI64_DyanmicStoreBuffer = ^TKDT18DI64_DyanmicStoreBuffer; PKDT18DI64_Node = ^TKDT18DI64_Node; TKDT18DI64_Node = record Parent, Right, Left: PKDT18DI64_Node; Vec: PKDT18DI64_Source; end; TKDT18DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer); TKDT18DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT18DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT18DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT18DI64_DyanmicStoreBuffer; KDBuff: TKDT18DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT18DI64_Node; TestBuff: TKDT18DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DI64_Node; function GetData(const Index: NativeInt): PKDT18DI64_Source; public RootNode: PKDT18DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT18DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT18DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT18DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT18DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildProc); overload; { search } function Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DI64_Node; overload; function Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DI64_Node; overload; function Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double): PKDT18DI64_Node; overload; function Search(const buff: TKDT18DI64_Vec): PKDT18DI64_Node; overload; function SearchToken(const buff: TKDT18DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT18DI64_DynamicVecBuffer; var OutBuff: TKDT18DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT18DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT18DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT18DI64_Vec; overload; class function Vec(const v: TKDT18DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT18DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer); class procedure Test; end; TKDT19DI64 = class(TCoreClassObject) public type // code split TKDT19DI64_Vec = array [0 .. KDT19DI64_Axis - 1] of TKDT19DI64_VecType; PKDT19DI64_Vec = ^TKDT19DI64_Vec; TKDT19DI64_DynamicVecBuffer = array of TKDT19DI64_Vec; PKDT19DI64_DynamicVecBuffer = ^TKDT19DI64_DynamicVecBuffer; TKDT19DI64_Source = record buff: TKDT19DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT19DI64_Source = ^TKDT19DI64_Source; TKDT19DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT19DI64_Source) - 1] of PKDT19DI64_Source; PKDT19DI64_SourceBuffer = ^TKDT19DI64_SourceBuffer; TKDT19DI64_DyanmicSourceBuffer = array of PKDT19DI64_Source; PKDT19DI64_DyanmicSourceBuffer = ^TKDT19DI64_DyanmicSourceBuffer; TKDT19DI64_DyanmicStoreBuffer = array of TKDT19DI64_Source; PKDT19DI64_DyanmicStoreBuffer = ^TKDT19DI64_DyanmicStoreBuffer; PKDT19DI64_Node = ^TKDT19DI64_Node; TKDT19DI64_Node = record Parent, Right, Left: PKDT19DI64_Node; Vec: PKDT19DI64_Source; end; TKDT19DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer); TKDT19DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT19DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT19DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT19DI64_DyanmicStoreBuffer; KDBuff: TKDT19DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT19DI64_Node; TestBuff: TKDT19DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DI64_Node; function GetData(const Index: NativeInt): PKDT19DI64_Source; public RootNode: PKDT19DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT19DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT19DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT19DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT19DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildProc); overload; { search } function Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DI64_Node; overload; function Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DI64_Node; overload; function Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double): PKDT19DI64_Node; overload; function Search(const buff: TKDT19DI64_Vec): PKDT19DI64_Node; overload; function SearchToken(const buff: TKDT19DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT19DI64_DynamicVecBuffer; var OutBuff: TKDT19DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT19DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT19DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT19DI64_Vec; overload; class function Vec(const v: TKDT19DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT19DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer); class procedure Test; end; TKDT20DI64 = class(TCoreClassObject) public type // code split TKDT20DI64_Vec = array [0 .. KDT20DI64_Axis - 1] of TKDT20DI64_VecType; PKDT20DI64_Vec = ^TKDT20DI64_Vec; TKDT20DI64_DynamicVecBuffer = array of TKDT20DI64_Vec; PKDT20DI64_DynamicVecBuffer = ^TKDT20DI64_DynamicVecBuffer; TKDT20DI64_Source = record buff: TKDT20DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT20DI64_Source = ^TKDT20DI64_Source; TKDT20DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT20DI64_Source) - 1] of PKDT20DI64_Source; PKDT20DI64_SourceBuffer = ^TKDT20DI64_SourceBuffer; TKDT20DI64_DyanmicSourceBuffer = array of PKDT20DI64_Source; PKDT20DI64_DyanmicSourceBuffer = ^TKDT20DI64_DyanmicSourceBuffer; TKDT20DI64_DyanmicStoreBuffer = array of TKDT20DI64_Source; PKDT20DI64_DyanmicStoreBuffer = ^TKDT20DI64_DyanmicStoreBuffer; PKDT20DI64_Node = ^TKDT20DI64_Node; TKDT20DI64_Node = record Parent, Right, Left: PKDT20DI64_Node; Vec: PKDT20DI64_Source; end; TKDT20DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer); TKDT20DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT20DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT20DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT20DI64_DyanmicStoreBuffer; KDBuff: TKDT20DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT20DI64_Node; TestBuff: TKDT20DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DI64_Node; function GetData(const Index: NativeInt): PKDT20DI64_Source; public RootNode: PKDT20DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT20DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT20DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT20DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT20DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildProc); overload; { search } function Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DI64_Node; overload; function Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DI64_Node; overload; function Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double): PKDT20DI64_Node; overload; function Search(const buff: TKDT20DI64_Vec): PKDT20DI64_Node; overload; function SearchToken(const buff: TKDT20DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT20DI64_DynamicVecBuffer; var OutBuff: TKDT20DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT20DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT20DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT20DI64_Vec; overload; class function Vec(const v: TKDT20DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT20DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer); class procedure Test; end; TKDT21DI64 = class(TCoreClassObject) public type // code split TKDT21DI64_Vec = array [0 .. KDT21DI64_Axis - 1] of TKDT21DI64_VecType; PKDT21DI64_Vec = ^TKDT21DI64_Vec; TKDT21DI64_DynamicVecBuffer = array of TKDT21DI64_Vec; PKDT21DI64_DynamicVecBuffer = ^TKDT21DI64_DynamicVecBuffer; TKDT21DI64_Source = record buff: TKDT21DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT21DI64_Source = ^TKDT21DI64_Source; TKDT21DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT21DI64_Source) - 1] of PKDT21DI64_Source; PKDT21DI64_SourceBuffer = ^TKDT21DI64_SourceBuffer; TKDT21DI64_DyanmicSourceBuffer = array of PKDT21DI64_Source; PKDT21DI64_DyanmicSourceBuffer = ^TKDT21DI64_DyanmicSourceBuffer; TKDT21DI64_DyanmicStoreBuffer = array of TKDT21DI64_Source; PKDT21DI64_DyanmicStoreBuffer = ^TKDT21DI64_DyanmicStoreBuffer; PKDT21DI64_Node = ^TKDT21DI64_Node; TKDT21DI64_Node = record Parent, Right, Left: PKDT21DI64_Node; Vec: PKDT21DI64_Source; end; TKDT21DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer); TKDT21DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT21DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT21DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT21DI64_DyanmicStoreBuffer; KDBuff: TKDT21DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT21DI64_Node; TestBuff: TKDT21DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DI64_Node; function GetData(const Index: NativeInt): PKDT21DI64_Source; public RootNode: PKDT21DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT21DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT21DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT21DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT21DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildProc); overload; { search } function Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DI64_Node; overload; function Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DI64_Node; overload; function Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double): PKDT21DI64_Node; overload; function Search(const buff: TKDT21DI64_Vec): PKDT21DI64_Node; overload; function SearchToken(const buff: TKDT21DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT21DI64_DynamicVecBuffer; var OutBuff: TKDT21DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT21DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT21DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT21DI64_Vec; overload; class function Vec(const v: TKDT21DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT21DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer); class procedure Test; end; TKDT22DI64 = class(TCoreClassObject) public type // code split TKDT22DI64_Vec = array [0 .. KDT22DI64_Axis - 1] of TKDT22DI64_VecType; PKDT22DI64_Vec = ^TKDT22DI64_Vec; TKDT22DI64_DynamicVecBuffer = array of TKDT22DI64_Vec; PKDT22DI64_DynamicVecBuffer = ^TKDT22DI64_DynamicVecBuffer; TKDT22DI64_Source = record buff: TKDT22DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT22DI64_Source = ^TKDT22DI64_Source; TKDT22DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT22DI64_Source) - 1] of PKDT22DI64_Source; PKDT22DI64_SourceBuffer = ^TKDT22DI64_SourceBuffer; TKDT22DI64_DyanmicSourceBuffer = array of PKDT22DI64_Source; PKDT22DI64_DyanmicSourceBuffer = ^TKDT22DI64_DyanmicSourceBuffer; TKDT22DI64_DyanmicStoreBuffer = array of TKDT22DI64_Source; PKDT22DI64_DyanmicStoreBuffer = ^TKDT22DI64_DyanmicStoreBuffer; PKDT22DI64_Node = ^TKDT22DI64_Node; TKDT22DI64_Node = record Parent, Right, Left: PKDT22DI64_Node; Vec: PKDT22DI64_Source; end; TKDT22DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer); TKDT22DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT22DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT22DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT22DI64_DyanmicStoreBuffer; KDBuff: TKDT22DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT22DI64_Node; TestBuff: TKDT22DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DI64_Node; function GetData(const Index: NativeInt): PKDT22DI64_Source; public RootNode: PKDT22DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT22DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT22DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT22DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT22DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildProc); overload; { search } function Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DI64_Node; overload; function Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DI64_Node; overload; function Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double): PKDT22DI64_Node; overload; function Search(const buff: TKDT22DI64_Vec): PKDT22DI64_Node; overload; function SearchToken(const buff: TKDT22DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT22DI64_DynamicVecBuffer; var OutBuff: TKDT22DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT22DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT22DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT22DI64_Vec; overload; class function Vec(const v: TKDT22DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT22DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer); class procedure Test; end; TKDT23DI64 = class(TCoreClassObject) public type // code split TKDT23DI64_Vec = array [0 .. KDT23DI64_Axis - 1] of TKDT23DI64_VecType; PKDT23DI64_Vec = ^TKDT23DI64_Vec; TKDT23DI64_DynamicVecBuffer = array of TKDT23DI64_Vec; PKDT23DI64_DynamicVecBuffer = ^TKDT23DI64_DynamicVecBuffer; TKDT23DI64_Source = record buff: TKDT23DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT23DI64_Source = ^TKDT23DI64_Source; TKDT23DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT23DI64_Source) - 1] of PKDT23DI64_Source; PKDT23DI64_SourceBuffer = ^TKDT23DI64_SourceBuffer; TKDT23DI64_DyanmicSourceBuffer = array of PKDT23DI64_Source; PKDT23DI64_DyanmicSourceBuffer = ^TKDT23DI64_DyanmicSourceBuffer; TKDT23DI64_DyanmicStoreBuffer = array of TKDT23DI64_Source; PKDT23DI64_DyanmicStoreBuffer = ^TKDT23DI64_DyanmicStoreBuffer; PKDT23DI64_Node = ^TKDT23DI64_Node; TKDT23DI64_Node = record Parent, Right, Left: PKDT23DI64_Node; Vec: PKDT23DI64_Source; end; TKDT23DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer); TKDT23DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT23DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT23DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT23DI64_DyanmicStoreBuffer; KDBuff: TKDT23DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT23DI64_Node; TestBuff: TKDT23DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DI64_Node; function GetData(const Index: NativeInt): PKDT23DI64_Source; public RootNode: PKDT23DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT23DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT23DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT23DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT23DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildProc); overload; { search } function Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DI64_Node; overload; function Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DI64_Node; overload; function Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double): PKDT23DI64_Node; overload; function Search(const buff: TKDT23DI64_Vec): PKDT23DI64_Node; overload; function SearchToken(const buff: TKDT23DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT23DI64_DynamicVecBuffer; var OutBuff: TKDT23DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT23DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT23DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT23DI64_Vec; overload; class function Vec(const v: TKDT23DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT23DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer); class procedure Test; end; TKDT24DI64 = class(TCoreClassObject) public type // code split TKDT24DI64_Vec = array [0 .. KDT24DI64_Axis - 1] of TKDT24DI64_VecType; PKDT24DI64_Vec = ^TKDT24DI64_Vec; TKDT24DI64_DynamicVecBuffer = array of TKDT24DI64_Vec; PKDT24DI64_DynamicVecBuffer = ^TKDT24DI64_DynamicVecBuffer; TKDT24DI64_Source = record buff: TKDT24DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT24DI64_Source = ^TKDT24DI64_Source; TKDT24DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT24DI64_Source) - 1] of PKDT24DI64_Source; PKDT24DI64_SourceBuffer = ^TKDT24DI64_SourceBuffer; TKDT24DI64_DyanmicSourceBuffer = array of PKDT24DI64_Source; PKDT24DI64_DyanmicSourceBuffer = ^TKDT24DI64_DyanmicSourceBuffer; TKDT24DI64_DyanmicStoreBuffer = array of TKDT24DI64_Source; PKDT24DI64_DyanmicStoreBuffer = ^TKDT24DI64_DyanmicStoreBuffer; PKDT24DI64_Node = ^TKDT24DI64_Node; TKDT24DI64_Node = record Parent, Right, Left: PKDT24DI64_Node; Vec: PKDT24DI64_Source; end; TKDT24DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer); TKDT24DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT24DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT24DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT24DI64_DyanmicStoreBuffer; KDBuff: TKDT24DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT24DI64_Node; TestBuff: TKDT24DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DI64_Node; function GetData(const Index: NativeInt): PKDT24DI64_Source; public RootNode: PKDT24DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT24DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT24DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT24DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT24DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildProc); overload; { search } function Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DI64_Node; overload; function Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DI64_Node; overload; function Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double): PKDT24DI64_Node; overload; function Search(const buff: TKDT24DI64_Vec): PKDT24DI64_Node; overload; function SearchToken(const buff: TKDT24DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT24DI64_DynamicVecBuffer; var OutBuff: TKDT24DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT24DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT24DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT24DI64_Vec; overload; class function Vec(const v: TKDT24DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT24DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer); class procedure Test; end; TKDT48DI64 = class(TCoreClassObject) public type // code split TKDT48DI64_Vec = array [0 .. KDT48DI64_Axis - 1] of TKDT48DI64_VecType; PKDT48DI64_Vec = ^TKDT48DI64_Vec; TKDT48DI64_DynamicVecBuffer = array of TKDT48DI64_Vec; PKDT48DI64_DynamicVecBuffer = ^TKDT48DI64_DynamicVecBuffer; TKDT48DI64_Source = record buff: TKDT48DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT48DI64_Source = ^TKDT48DI64_Source; TKDT48DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT48DI64_Source) - 1] of PKDT48DI64_Source; PKDT48DI64_SourceBuffer = ^TKDT48DI64_SourceBuffer; TKDT48DI64_DyanmicSourceBuffer = array of PKDT48DI64_Source; PKDT48DI64_DyanmicSourceBuffer = ^TKDT48DI64_DyanmicSourceBuffer; TKDT48DI64_DyanmicStoreBuffer = array of TKDT48DI64_Source; PKDT48DI64_DyanmicStoreBuffer = ^TKDT48DI64_DyanmicStoreBuffer; PKDT48DI64_Node = ^TKDT48DI64_Node; TKDT48DI64_Node = record Parent, Right, Left: PKDT48DI64_Node; Vec: PKDT48DI64_Source; end; TKDT48DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer); TKDT48DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT48DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT48DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT48DI64_DyanmicStoreBuffer; KDBuff: TKDT48DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT48DI64_Node; TestBuff: TKDT48DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DI64_Node; function GetData(const Index: NativeInt): PKDT48DI64_Source; public RootNode: PKDT48DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT48DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT48DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT48DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT48DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildProc); overload; { search } function Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DI64_Node; overload; function Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DI64_Node; overload; function Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double): PKDT48DI64_Node; overload; function Search(const buff: TKDT48DI64_Vec): PKDT48DI64_Node; overload; function SearchToken(const buff: TKDT48DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT48DI64_DynamicVecBuffer; var OutBuff: TKDT48DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT48DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT48DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT48DI64_Vec; overload; class function Vec(const v: TKDT48DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT48DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer); class procedure Test; end; TKDT52DI64 = class(TCoreClassObject) public type // code split TKDT52DI64_Vec = array [0 .. KDT52DI64_Axis - 1] of TKDT52DI64_VecType; PKDT52DI64_Vec = ^TKDT52DI64_Vec; TKDT52DI64_DynamicVecBuffer = array of TKDT52DI64_Vec; PKDT52DI64_DynamicVecBuffer = ^TKDT52DI64_DynamicVecBuffer; TKDT52DI64_Source = record buff: TKDT52DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT52DI64_Source = ^TKDT52DI64_Source; TKDT52DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT52DI64_Source) - 1] of PKDT52DI64_Source; PKDT52DI64_SourceBuffer = ^TKDT52DI64_SourceBuffer; TKDT52DI64_DyanmicSourceBuffer = array of PKDT52DI64_Source; PKDT52DI64_DyanmicSourceBuffer = ^TKDT52DI64_DyanmicSourceBuffer; TKDT52DI64_DyanmicStoreBuffer = array of TKDT52DI64_Source; PKDT52DI64_DyanmicStoreBuffer = ^TKDT52DI64_DyanmicStoreBuffer; PKDT52DI64_Node = ^TKDT52DI64_Node; TKDT52DI64_Node = record Parent, Right, Left: PKDT52DI64_Node; Vec: PKDT52DI64_Source; end; TKDT52DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer); TKDT52DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT52DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT52DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT52DI64_DyanmicStoreBuffer; KDBuff: TKDT52DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT52DI64_Node; TestBuff: TKDT52DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DI64_Node; function GetData(const Index: NativeInt): PKDT52DI64_Source; public RootNode: PKDT52DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT52DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT52DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT52DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT52DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildProc); overload; { search } function Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DI64_Node; overload; function Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DI64_Node; overload; function Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double): PKDT52DI64_Node; overload; function Search(const buff: TKDT52DI64_Vec): PKDT52DI64_Node; overload; function SearchToken(const buff: TKDT52DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT52DI64_DynamicVecBuffer; var OutBuff: TKDT52DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT52DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT52DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT52DI64_Vec; overload; class function Vec(const v: TKDT52DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT52DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer); class procedure Test; end; TKDT64DI64 = class(TCoreClassObject) public type // code split TKDT64DI64_Vec = array [0 .. KDT64DI64_Axis - 1] of TKDT64DI64_VecType; PKDT64DI64_Vec = ^TKDT64DI64_Vec; TKDT64DI64_DynamicVecBuffer = array of TKDT64DI64_Vec; PKDT64DI64_DynamicVecBuffer = ^TKDT64DI64_DynamicVecBuffer; TKDT64DI64_Source = record buff: TKDT64DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT64DI64_Source = ^TKDT64DI64_Source; TKDT64DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT64DI64_Source) - 1] of PKDT64DI64_Source; PKDT64DI64_SourceBuffer = ^TKDT64DI64_SourceBuffer; TKDT64DI64_DyanmicSourceBuffer = array of PKDT64DI64_Source; PKDT64DI64_DyanmicSourceBuffer = ^TKDT64DI64_DyanmicSourceBuffer; TKDT64DI64_DyanmicStoreBuffer = array of TKDT64DI64_Source; PKDT64DI64_DyanmicStoreBuffer = ^TKDT64DI64_DyanmicStoreBuffer; PKDT64DI64_Node = ^TKDT64DI64_Node; TKDT64DI64_Node = record Parent, Right, Left: PKDT64DI64_Node; Vec: PKDT64DI64_Source; end; TKDT64DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer); TKDT64DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT64DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT64DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT64DI64_DyanmicStoreBuffer; KDBuff: TKDT64DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT64DI64_Node; TestBuff: TKDT64DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DI64_Node; function GetData(const Index: NativeInt): PKDT64DI64_Source; public RootNode: PKDT64DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT64DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT64DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT64DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT64DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildProc); overload; { search } function Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DI64_Node; overload; function Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DI64_Node; overload; function Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double): PKDT64DI64_Node; overload; function Search(const buff: TKDT64DI64_Vec): PKDT64DI64_Node; overload; function SearchToken(const buff: TKDT64DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT64DI64_DynamicVecBuffer; var OutBuff: TKDT64DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT64DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT64DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT64DI64_Vec; overload; class function Vec(const v: TKDT64DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT64DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer); class procedure Test; end; TKDT96DI64 = class(TCoreClassObject) public type // code split TKDT96DI64_Vec = array [0 .. KDT96DI64_Axis - 1] of TKDT96DI64_VecType; PKDT96DI64_Vec = ^TKDT96DI64_Vec; TKDT96DI64_DynamicVecBuffer = array of TKDT96DI64_Vec; PKDT96DI64_DynamicVecBuffer = ^TKDT96DI64_DynamicVecBuffer; TKDT96DI64_Source = record buff: TKDT96DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT96DI64_Source = ^TKDT96DI64_Source; TKDT96DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT96DI64_Source) - 1] of PKDT96DI64_Source; PKDT96DI64_SourceBuffer = ^TKDT96DI64_SourceBuffer; TKDT96DI64_DyanmicSourceBuffer = array of PKDT96DI64_Source; PKDT96DI64_DyanmicSourceBuffer = ^TKDT96DI64_DyanmicSourceBuffer; TKDT96DI64_DyanmicStoreBuffer = array of TKDT96DI64_Source; PKDT96DI64_DyanmicStoreBuffer = ^TKDT96DI64_DyanmicStoreBuffer; PKDT96DI64_Node = ^TKDT96DI64_Node; TKDT96DI64_Node = record Parent, Right, Left: PKDT96DI64_Node; Vec: PKDT96DI64_Source; end; TKDT96DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer); TKDT96DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT96DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT96DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT96DI64_DyanmicStoreBuffer; KDBuff: TKDT96DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT96DI64_Node; TestBuff: TKDT96DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DI64_Node; function GetData(const Index: NativeInt): PKDT96DI64_Source; public RootNode: PKDT96DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT96DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT96DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT96DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT96DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildProc); overload; { search } function Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DI64_Node; overload; function Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DI64_Node; overload; function Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double): PKDT96DI64_Node; overload; function Search(const buff: TKDT96DI64_Vec): PKDT96DI64_Node; overload; function SearchToken(const buff: TKDT96DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT96DI64_DynamicVecBuffer; var OutBuff: TKDT96DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT96DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT96DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT96DI64_Vec; overload; class function Vec(const v: TKDT96DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT96DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer); class procedure Test; end; TKDT128DI64 = class(TCoreClassObject) public type // code split TKDT128DI64_Vec = array [0 .. KDT128DI64_Axis - 1] of TKDT128DI64_VecType; PKDT128DI64_Vec = ^TKDT128DI64_Vec; TKDT128DI64_DynamicVecBuffer = array of TKDT128DI64_Vec; PKDT128DI64_DynamicVecBuffer = ^TKDT128DI64_DynamicVecBuffer; TKDT128DI64_Source = record buff: TKDT128DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT128DI64_Source = ^TKDT128DI64_Source; TKDT128DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT128DI64_Source) - 1] of PKDT128DI64_Source; PKDT128DI64_SourceBuffer = ^TKDT128DI64_SourceBuffer; TKDT128DI64_DyanmicSourceBuffer = array of PKDT128DI64_Source; PKDT128DI64_DyanmicSourceBuffer = ^TKDT128DI64_DyanmicSourceBuffer; TKDT128DI64_DyanmicStoreBuffer = array of TKDT128DI64_Source; PKDT128DI64_DyanmicStoreBuffer = ^TKDT128DI64_DyanmicStoreBuffer; PKDT128DI64_Node = ^TKDT128DI64_Node; TKDT128DI64_Node = record Parent, Right, Left: PKDT128DI64_Node; Vec: PKDT128DI64_Source; end; TKDT128DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer); TKDT128DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT128DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT128DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT128DI64_DyanmicStoreBuffer; KDBuff: TKDT128DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT128DI64_Node; TestBuff: TKDT128DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DI64_Node; function GetData(const Index: NativeInt): PKDT128DI64_Source; public RootNode: PKDT128DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT128DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT128DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT128DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT128DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildProc); overload; { search } function Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DI64_Node; overload; function Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DI64_Node; overload; function Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double): PKDT128DI64_Node; overload; function Search(const buff: TKDT128DI64_Vec): PKDT128DI64_Node; overload; function SearchToken(const buff: TKDT128DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT128DI64_DynamicVecBuffer; var OutBuff: TKDT128DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT128DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT128DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT128DI64_Vec; overload; class function Vec(const v: TKDT128DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT128DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer); class procedure Test; end; TKDT156DI64 = class(TCoreClassObject) public type // code split TKDT156DI64_Vec = array [0 .. KDT156DI64_Axis - 1] of TKDT156DI64_VecType; PKDT156DI64_Vec = ^TKDT156DI64_Vec; TKDT156DI64_DynamicVecBuffer = array of TKDT156DI64_Vec; PKDT156DI64_DynamicVecBuffer = ^TKDT156DI64_DynamicVecBuffer; TKDT156DI64_Source = record buff: TKDT156DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT156DI64_Source = ^TKDT156DI64_Source; TKDT156DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT156DI64_Source) - 1] of PKDT156DI64_Source; PKDT156DI64_SourceBuffer = ^TKDT156DI64_SourceBuffer; TKDT156DI64_DyanmicSourceBuffer = array of PKDT156DI64_Source; PKDT156DI64_DyanmicSourceBuffer = ^TKDT156DI64_DyanmicSourceBuffer; TKDT156DI64_DyanmicStoreBuffer = array of TKDT156DI64_Source; PKDT156DI64_DyanmicStoreBuffer = ^TKDT156DI64_DyanmicStoreBuffer; PKDT156DI64_Node = ^TKDT156DI64_Node; TKDT156DI64_Node = record Parent, Right, Left: PKDT156DI64_Node; Vec: PKDT156DI64_Source; end; TKDT156DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer); TKDT156DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT156DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT156DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT156DI64_DyanmicStoreBuffer; KDBuff: TKDT156DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT156DI64_Node; TestBuff: TKDT156DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DI64_Node; function GetData(const Index: NativeInt): PKDT156DI64_Source; public RootNode: PKDT156DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT156DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT156DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT156DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT156DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildProc); overload; { search } function Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DI64_Node; overload; function Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DI64_Node; overload; function Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double): PKDT156DI64_Node; overload; function Search(const buff: TKDT156DI64_Vec): PKDT156DI64_Node; overload; function SearchToken(const buff: TKDT156DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT156DI64_DynamicVecBuffer; var OutBuff: TKDT156DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT156DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT156DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT156DI64_Vec; overload; class function Vec(const v: TKDT156DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT156DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer); class procedure Test; end; TKDT192DI64 = class(TCoreClassObject) public type // code split TKDT192DI64_Vec = array [0 .. KDT192DI64_Axis - 1] of TKDT192DI64_VecType; PKDT192DI64_Vec = ^TKDT192DI64_Vec; TKDT192DI64_DynamicVecBuffer = array of TKDT192DI64_Vec; PKDT192DI64_DynamicVecBuffer = ^TKDT192DI64_DynamicVecBuffer; TKDT192DI64_Source = record buff: TKDT192DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT192DI64_Source = ^TKDT192DI64_Source; TKDT192DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT192DI64_Source) - 1] of PKDT192DI64_Source; PKDT192DI64_SourceBuffer = ^TKDT192DI64_SourceBuffer; TKDT192DI64_DyanmicSourceBuffer = array of PKDT192DI64_Source; PKDT192DI64_DyanmicSourceBuffer = ^TKDT192DI64_DyanmicSourceBuffer; TKDT192DI64_DyanmicStoreBuffer = array of TKDT192DI64_Source; PKDT192DI64_DyanmicStoreBuffer = ^TKDT192DI64_DyanmicStoreBuffer; PKDT192DI64_Node = ^TKDT192DI64_Node; TKDT192DI64_Node = record Parent, Right, Left: PKDT192DI64_Node; Vec: PKDT192DI64_Source; end; TKDT192DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer); TKDT192DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT192DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT192DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT192DI64_DyanmicStoreBuffer; KDBuff: TKDT192DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT192DI64_Node; TestBuff: TKDT192DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DI64_Node; function GetData(const Index: NativeInt): PKDT192DI64_Source; public RootNode: PKDT192DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT192DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT192DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT192DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT192DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildProc); overload; { search } function Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DI64_Node; overload; function Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DI64_Node; overload; function Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double): PKDT192DI64_Node; overload; function Search(const buff: TKDT192DI64_Vec): PKDT192DI64_Node; overload; function SearchToken(const buff: TKDT192DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT192DI64_DynamicVecBuffer; var OutBuff: TKDT192DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT192DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT192DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT192DI64_Vec; overload; class function Vec(const v: TKDT192DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT192DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer); class procedure Test; end; TKDT256DI64 = class(TCoreClassObject) public type // code split TKDT256DI64_Vec = array [0 .. KDT256DI64_Axis - 1] of TKDT256DI64_VecType; PKDT256DI64_Vec = ^TKDT256DI64_Vec; TKDT256DI64_DynamicVecBuffer = array of TKDT256DI64_Vec; PKDT256DI64_DynamicVecBuffer = ^TKDT256DI64_DynamicVecBuffer; TKDT256DI64_Source = record buff: TKDT256DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT256DI64_Source = ^TKDT256DI64_Source; TKDT256DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT256DI64_Source) - 1] of PKDT256DI64_Source; PKDT256DI64_SourceBuffer = ^TKDT256DI64_SourceBuffer; TKDT256DI64_DyanmicSourceBuffer = array of PKDT256DI64_Source; PKDT256DI64_DyanmicSourceBuffer = ^TKDT256DI64_DyanmicSourceBuffer; TKDT256DI64_DyanmicStoreBuffer = array of TKDT256DI64_Source; PKDT256DI64_DyanmicStoreBuffer = ^TKDT256DI64_DyanmicStoreBuffer; PKDT256DI64_Node = ^TKDT256DI64_Node; TKDT256DI64_Node = record Parent, Right, Left: PKDT256DI64_Node; Vec: PKDT256DI64_Source; end; TKDT256DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer); TKDT256DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT256DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT256DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT256DI64_DyanmicStoreBuffer; KDBuff: TKDT256DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT256DI64_Node; TestBuff: TKDT256DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DI64_Node; function GetData(const Index: NativeInt): PKDT256DI64_Source; public RootNode: PKDT256DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT256DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT256DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT256DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT256DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildProc); overload; { search } function Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DI64_Node; overload; function Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DI64_Node; overload; function Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double): PKDT256DI64_Node; overload; function Search(const buff: TKDT256DI64_Vec): PKDT256DI64_Node; overload; function SearchToken(const buff: TKDT256DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT256DI64_DynamicVecBuffer; var OutBuff: TKDT256DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT256DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT256DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT256DI64_Vec; overload; class function Vec(const v: TKDT256DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT256DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer); class procedure Test; end; TKDT384DI64 = class(TCoreClassObject) public type // code split TKDT384DI64_Vec = array [0 .. KDT384DI64_Axis - 1] of TKDT384DI64_VecType; PKDT384DI64_Vec = ^TKDT384DI64_Vec; TKDT384DI64_DynamicVecBuffer = array of TKDT384DI64_Vec; PKDT384DI64_DynamicVecBuffer = ^TKDT384DI64_DynamicVecBuffer; TKDT384DI64_Source = record buff: TKDT384DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT384DI64_Source = ^TKDT384DI64_Source; TKDT384DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT384DI64_Source) - 1] of PKDT384DI64_Source; PKDT384DI64_SourceBuffer = ^TKDT384DI64_SourceBuffer; TKDT384DI64_DyanmicSourceBuffer = array of PKDT384DI64_Source; PKDT384DI64_DyanmicSourceBuffer = ^TKDT384DI64_DyanmicSourceBuffer; TKDT384DI64_DyanmicStoreBuffer = array of TKDT384DI64_Source; PKDT384DI64_DyanmicStoreBuffer = ^TKDT384DI64_DyanmicStoreBuffer; PKDT384DI64_Node = ^TKDT384DI64_Node; TKDT384DI64_Node = record Parent, Right, Left: PKDT384DI64_Node; Vec: PKDT384DI64_Source; end; TKDT384DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer); TKDT384DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT384DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT384DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT384DI64_DyanmicStoreBuffer; KDBuff: TKDT384DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT384DI64_Node; TestBuff: TKDT384DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DI64_Node; function GetData(const Index: NativeInt): PKDT384DI64_Source; public RootNode: PKDT384DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT384DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT384DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT384DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT384DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildProc); overload; { search } function Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DI64_Node; overload; function Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DI64_Node; overload; function Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double): PKDT384DI64_Node; overload; function Search(const buff: TKDT384DI64_Vec): PKDT384DI64_Node; overload; function SearchToken(const buff: TKDT384DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT384DI64_DynamicVecBuffer; var OutBuff: TKDT384DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT384DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT384DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT384DI64_Vec; overload; class function Vec(const v: TKDT384DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT384DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer); class procedure Test; end; TKDT512DI64 = class(TCoreClassObject) public type // code split TKDT512DI64_Vec = array [0 .. KDT512DI64_Axis - 1] of TKDT512DI64_VecType; PKDT512DI64_Vec = ^TKDT512DI64_Vec; TKDT512DI64_DynamicVecBuffer = array of TKDT512DI64_Vec; PKDT512DI64_DynamicVecBuffer = ^TKDT512DI64_DynamicVecBuffer; TKDT512DI64_Source = record buff: TKDT512DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT512DI64_Source = ^TKDT512DI64_Source; TKDT512DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT512DI64_Source) - 1] of PKDT512DI64_Source; PKDT512DI64_SourceBuffer = ^TKDT512DI64_SourceBuffer; TKDT512DI64_DyanmicSourceBuffer = array of PKDT512DI64_Source; PKDT512DI64_DyanmicSourceBuffer = ^TKDT512DI64_DyanmicSourceBuffer; TKDT512DI64_DyanmicStoreBuffer = array of TKDT512DI64_Source; PKDT512DI64_DyanmicStoreBuffer = ^TKDT512DI64_DyanmicStoreBuffer; PKDT512DI64_Node = ^TKDT512DI64_Node; TKDT512DI64_Node = record Parent, Right, Left: PKDT512DI64_Node; Vec: PKDT512DI64_Source; end; TKDT512DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer); TKDT512DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT512DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT512DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT512DI64_DyanmicStoreBuffer; KDBuff: TKDT512DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT512DI64_Node; TestBuff: TKDT512DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DI64_Node; function GetData(const Index: NativeInt): PKDT512DI64_Source; public RootNode: PKDT512DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT512DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT512DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT512DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT512DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildProc); overload; { search } function Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DI64_Node; overload; function Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DI64_Node; overload; function Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double): PKDT512DI64_Node; overload; function Search(const buff: TKDT512DI64_Vec): PKDT512DI64_Node; overload; function SearchToken(const buff: TKDT512DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT512DI64_DynamicVecBuffer; var OutBuff: TKDT512DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT512DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT512DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT512DI64_Vec; overload; class function Vec(const v: TKDT512DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT512DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer); class procedure Test; end; TKDT800DI64 = class(TCoreClassObject) public type // code split TKDT800DI64_Vec = array [0 .. KDT800DI64_Axis - 1] of TKDT800DI64_VecType; PKDT800DI64_Vec = ^TKDT800DI64_Vec; TKDT800DI64_DynamicVecBuffer = array of TKDT800DI64_Vec; PKDT800DI64_DynamicVecBuffer = ^TKDT800DI64_DynamicVecBuffer; TKDT800DI64_Source = record buff: TKDT800DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT800DI64_Source = ^TKDT800DI64_Source; TKDT800DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT800DI64_Source) - 1] of PKDT800DI64_Source; PKDT800DI64_SourceBuffer = ^TKDT800DI64_SourceBuffer; TKDT800DI64_DyanmicSourceBuffer = array of PKDT800DI64_Source; PKDT800DI64_DyanmicSourceBuffer = ^TKDT800DI64_DyanmicSourceBuffer; TKDT800DI64_DyanmicStoreBuffer = array of TKDT800DI64_Source; PKDT800DI64_DyanmicStoreBuffer = ^TKDT800DI64_DyanmicStoreBuffer; PKDT800DI64_Node = ^TKDT800DI64_Node; TKDT800DI64_Node = record Parent, Right, Left: PKDT800DI64_Node; Vec: PKDT800DI64_Source; end; TKDT800DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer); TKDT800DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT800DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT800DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT800DI64_DyanmicStoreBuffer; KDBuff: TKDT800DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT800DI64_Node; TestBuff: TKDT800DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DI64_Node; function GetData(const Index: NativeInt): PKDT800DI64_Source; public RootNode: PKDT800DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT800DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT800DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT800DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT800DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildProc); overload; { search } function Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DI64_Node; overload; function Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DI64_Node; overload; function Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double): PKDT800DI64_Node; overload; function Search(const buff: TKDT800DI64_Vec): PKDT800DI64_Node; overload; function SearchToken(const buff: TKDT800DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT800DI64_DynamicVecBuffer; var OutBuff: TKDT800DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT800DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT800DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT800DI64_Vec; overload; class function Vec(const v: TKDT800DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT800DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer); class procedure Test; end; TKDT1024DI64 = class(TCoreClassObject) public type // code split TKDT1024DI64_Vec = array [0 .. KDT1024DI64_Axis - 1] of TKDT1024DI64_VecType; PKDT1024DI64_Vec = ^TKDT1024DI64_Vec; TKDT1024DI64_DynamicVecBuffer = array of TKDT1024DI64_Vec; PKDT1024DI64_DynamicVecBuffer = ^TKDT1024DI64_DynamicVecBuffer; TKDT1024DI64_Source = record buff: TKDT1024DI64_Vec; Index: Int64; Token: TPascalString; end; PKDT1024DI64_Source = ^TKDT1024DI64_Source; TKDT1024DI64_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1024DI64_Source) - 1] of PKDT1024DI64_Source; PKDT1024DI64_SourceBuffer = ^TKDT1024DI64_SourceBuffer; TKDT1024DI64_DyanmicSourceBuffer = array of PKDT1024DI64_Source; PKDT1024DI64_DyanmicSourceBuffer = ^TKDT1024DI64_DyanmicSourceBuffer; TKDT1024DI64_DyanmicStoreBuffer = array of TKDT1024DI64_Source; PKDT1024DI64_DyanmicStoreBuffer = ^TKDT1024DI64_DyanmicStoreBuffer; PKDT1024DI64_Node = ^TKDT1024DI64_Node; TKDT1024DI64_Node = record Parent, Right, Left: PKDT1024DI64_Node; Vec: PKDT1024DI64_Source; end; TKDT1024DI64_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer); TKDT1024DI64_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT1024DI64_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT1024DI64_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT1024DI64_DyanmicStoreBuffer; KDBuff: TKDT1024DI64_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT1024DI64_Node; TestBuff: TKDT1024DI64_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DI64_Node; function GetData(const Index: NativeInt): PKDT1024DI64_Source; public RootNode: PKDT1024DI64_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT1024DI64_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT1024DI64_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DI64_DynamicVecBuffer; const k, Restarts: NativeInt); overload; { backcall k-means++ clusterization } procedure BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildProc); overload; { search } function Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DI64_Node; overload; function Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DI64_Node; overload; function Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double): PKDT1024DI64_Node; overload; function Search(const buff: TKDT1024DI64_Vec): PKDT1024DI64_Node; overload; function SearchToken(const buff: TKDT1024DI64_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT1024DI64_DynamicVecBuffer; var OutBuff: TKDT1024DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT1024DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure SaveToStream(stream: TCoreClassStream); procedure LoadFromStream(stream: TCoreClassStream); procedure SaveToFile(FileName: SystemString); procedure LoadFromFile(FileName: SystemString); procedure PrintNodeTree(const NodePtr: PKDT1024DI64_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT1024DI64_Vec; overload; class function Vec(const v: TKDT1024DI64_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT1024DI64_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer); class procedure Test; end; procedure Test_All; implementation uses TextParsing, MemoryStream64, DoStatusIO; const SaveToken = $66; function TKDT1DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DI64_Node; function SortCompare(const p1, p2: PKDT1DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT1DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT1DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT1DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT1DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT1DI64.GetData(const Index: NativeInt): PKDT1DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT1DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT1DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT1DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT1DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT1DI64.StoreBuffPtr: PKDT1DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT1DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT1DI64.BuildKDTreeWithCluster(const inBuff: TKDT1DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT1DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT1DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT1DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT1DI64.BuildKDTreeWithCluster(const inBuff: TKDT1DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT1DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildCall); var TempStoreBuff: TKDT1DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT1DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildMethod); var TempStoreBuff: TKDT1DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT1DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI64_BuildProc); var TempStoreBuff: TKDT1DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT1DI64.Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DI64_Node; var NearestNeighbour: PKDT1DI64_Node; function FindParentNode(const buffPtr: PKDT1DI64_Vec; NodePtr: PKDT1DI64_Node): PKDT1DI64_Node; var Next: PKDT1DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT1DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT1DI64_Node; const buffPtr: PKDT1DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT1DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT1DI64_Vec; const p1, p2: PKDT1DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1DI64_Vec); var i, j: NativeInt; p, t: PKDT1DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT1DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT1DI64_Node(NearestNodes[0]); end; end; function TKDT1DI64.Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT1DI64.Search(const buff: TKDT1DI64_Vec; var SearchedDistanceMin: Double): PKDT1DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1DI64.Search(const buff: TKDT1DI64_Vec): PKDT1DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1DI64.SearchToken(const buff: TKDT1DI64_Vec): TPascalString; var p: PKDT1DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT1DI64.Search(const inBuff: TKDT1DI64_DynamicVecBuffer; var OutBuff: TKDT1DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1DI64_DynamicVecBuffer; outBuffPtr: PKDT1DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT1DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT1DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT1DI64.Search(const inBuff: TKDT1DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT1DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT1DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT1DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT1DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT1DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT1DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1DI64_Vec)) <> SizeOf(TKDT1DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT1DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1DI64.PrintNodeTree(const NodePtr: PKDT1DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT1DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT1DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT1DI64.Vec(const s: SystemString): TKDT1DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT1DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT1DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT1DI64.Vec(const v: TKDT1DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT1DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT1DI64.Distance(const v1, v2: TKDT1DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT1DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT1DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT1DI64.Test; var TKDT1DI64_Test: TKDT1DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT1DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT1DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT1DI64_Test := TKDT1DI64.Create; n.Append('...'); SetLength(TKDT1DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT1DI64_Test.TestBuff) - 1 do for j := 0 to KDT1DI64_Axis - 1 do TKDT1DI64_Test.TestBuff[i][j] := i * KDT1DI64_Axis + j; {$IFDEF FPC} TKDT1DI64_Test.BuildKDTreeM(length(TKDT1DI64_Test.TestBuff), nil, @TKDT1DI64_Test.Test_BuildM); {$ELSE FPC} TKDT1DI64_Test.BuildKDTreeM(length(TKDT1DI64_Test.TestBuff), nil, TKDT1DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT1DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT1DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT1DI64_Test.TestBuff) - 1 do begin p := TKDT1DI64_Test.Search(TKDT1DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT1DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT1DI64_Test.TestBuff)); TKDT1DI64_Test.Search(TKDT1DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT1DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT1DI64_Test.Clear; { kMean test } TKDT1DI64_Test.BuildKDTreeWithCluster(TKDT1DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT1DI64_Test.Search(TKDT1DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT1DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT1DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT1DI64_Test); DoStatus(n); n := ''; end; function TKDT2DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DI64_Node; function SortCompare(const p1, p2: PKDT2DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT2DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT2DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT2DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT2DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT2DI64.GetData(const Index: NativeInt): PKDT2DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT2DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT2DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT2DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT2DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT2DI64.StoreBuffPtr: PKDT2DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT2DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT2DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT2DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT2DI64.BuildKDTreeWithCluster(const inBuff: TKDT2DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT2DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT2DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT2DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT2DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT2DI64.BuildKDTreeWithCluster(const inBuff: TKDT2DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT2DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildCall); var TempStoreBuff: TKDT2DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT2DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT2DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildMethod); var TempStoreBuff: TKDT2DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT2DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT2DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI64_BuildProc); var TempStoreBuff: TKDT2DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT2DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT2DI64.Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DI64_Node; var NearestNeighbour: PKDT2DI64_Node; function FindParentNode(const buffPtr: PKDT2DI64_Vec; NodePtr: PKDT2DI64_Node): PKDT2DI64_Node; var Next: PKDT2DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT2DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT2DI64_Node; const buffPtr: PKDT2DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT2DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT2DI64_Vec; const p1, p2: PKDT2DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT2DI64_Vec); var i, j: NativeInt; p, t: PKDT2DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT2DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT2DI64_Node(NearestNodes[0]); end; end; function TKDT2DI64.Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT2DI64.Search(const buff: TKDT2DI64_Vec; var SearchedDistanceMin: Double): PKDT2DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT2DI64.Search(const buff: TKDT2DI64_Vec): PKDT2DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT2DI64.SearchToken(const buff: TKDT2DI64_Vec): TPascalString; var p: PKDT2DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT2DI64.Search(const inBuff: TKDT2DI64_DynamicVecBuffer; var OutBuff: TKDT2DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT2DI64_DynamicVecBuffer; outBuffPtr: PKDT2DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT2DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT2DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT2DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT2DI64.Search(const inBuff: TKDT2DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT2DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT2DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT2DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT2DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT2DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT2DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT2DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT2DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT2DI64_Vec)) <> SizeOf(TKDT2DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT2DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT2DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT2DI64.PrintNodeTree(const NodePtr: PKDT2DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT2DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT2DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT2DI64.Vec(const s: SystemString): TKDT2DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT2DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT2DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT2DI64.Vec(const v: TKDT2DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT2DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT2DI64.Distance(const v1, v2: TKDT2DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT2DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT2DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT2DI64.Test; var TKDT2DI64_Test: TKDT2DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT2DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT2DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT2DI64_Test := TKDT2DI64.Create; n.Append('...'); SetLength(TKDT2DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT2DI64_Test.TestBuff) - 1 do for j := 0 to KDT2DI64_Axis - 1 do TKDT2DI64_Test.TestBuff[i][j] := i * KDT2DI64_Axis + j; {$IFDEF FPC} TKDT2DI64_Test.BuildKDTreeM(length(TKDT2DI64_Test.TestBuff), nil, @TKDT2DI64_Test.Test_BuildM); {$ELSE FPC} TKDT2DI64_Test.BuildKDTreeM(length(TKDT2DI64_Test.TestBuff), nil, TKDT2DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT2DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT2DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT2DI64_Test.TestBuff) - 1 do begin p := TKDT2DI64_Test.Search(TKDT2DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT2DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT2DI64_Test.TestBuff)); TKDT2DI64_Test.Search(TKDT2DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT2DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT2DI64_Test.Clear; { kMean test } TKDT2DI64_Test.BuildKDTreeWithCluster(TKDT2DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT2DI64_Test.Search(TKDT2DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT2DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT2DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT2DI64_Test); DoStatus(n); n := ''; end; function TKDT3DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DI64_Node; function SortCompare(const p1, p2: PKDT3DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT3DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT3DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT3DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT3DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT3DI64.GetData(const Index: NativeInt): PKDT3DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT3DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT3DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT3DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT3DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT3DI64.StoreBuffPtr: PKDT3DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT3DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT3DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT3DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT3DI64.BuildKDTreeWithCluster(const inBuff: TKDT3DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT3DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT3DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT3DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT3DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT3DI64.BuildKDTreeWithCluster(const inBuff: TKDT3DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT3DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildCall); var TempStoreBuff: TKDT3DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT3DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT3DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildMethod); var TempStoreBuff: TKDT3DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT3DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT3DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI64_BuildProc); var TempStoreBuff: TKDT3DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT3DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT3DI64.Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DI64_Node; var NearestNeighbour: PKDT3DI64_Node; function FindParentNode(const buffPtr: PKDT3DI64_Vec; NodePtr: PKDT3DI64_Node): PKDT3DI64_Node; var Next: PKDT3DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT3DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT3DI64_Node; const buffPtr: PKDT3DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT3DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT3DI64_Vec; const p1, p2: PKDT3DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT3DI64_Vec); var i, j: NativeInt; p, t: PKDT3DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT3DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT3DI64_Node(NearestNodes[0]); end; end; function TKDT3DI64.Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT3DI64.Search(const buff: TKDT3DI64_Vec; var SearchedDistanceMin: Double): PKDT3DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT3DI64.Search(const buff: TKDT3DI64_Vec): PKDT3DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT3DI64.SearchToken(const buff: TKDT3DI64_Vec): TPascalString; var p: PKDT3DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT3DI64.Search(const inBuff: TKDT3DI64_DynamicVecBuffer; var OutBuff: TKDT3DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT3DI64_DynamicVecBuffer; outBuffPtr: PKDT3DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT3DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT3DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT3DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT3DI64.Search(const inBuff: TKDT3DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT3DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT3DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT3DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT3DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT3DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT3DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT3DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT3DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT3DI64_Vec)) <> SizeOf(TKDT3DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT3DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT3DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT3DI64.PrintNodeTree(const NodePtr: PKDT3DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT3DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT3DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT3DI64.Vec(const s: SystemString): TKDT3DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT3DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT3DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT3DI64.Vec(const v: TKDT3DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT3DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT3DI64.Distance(const v1, v2: TKDT3DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT3DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT3DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT3DI64.Test; var TKDT3DI64_Test: TKDT3DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT3DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT3DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT3DI64_Test := TKDT3DI64.Create; n.Append('...'); SetLength(TKDT3DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT3DI64_Test.TestBuff) - 1 do for j := 0 to KDT3DI64_Axis - 1 do TKDT3DI64_Test.TestBuff[i][j] := i * KDT3DI64_Axis + j; {$IFDEF FPC} TKDT3DI64_Test.BuildKDTreeM(length(TKDT3DI64_Test.TestBuff), nil, @TKDT3DI64_Test.Test_BuildM); {$ELSE FPC} TKDT3DI64_Test.BuildKDTreeM(length(TKDT3DI64_Test.TestBuff), nil, TKDT3DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT3DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT3DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT3DI64_Test.TestBuff) - 1 do begin p := TKDT3DI64_Test.Search(TKDT3DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT3DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT3DI64_Test.TestBuff)); TKDT3DI64_Test.Search(TKDT3DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT3DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT3DI64_Test.Clear; { kMean test } TKDT3DI64_Test.BuildKDTreeWithCluster(TKDT3DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT3DI64_Test.Search(TKDT3DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT3DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT3DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT3DI64_Test); DoStatus(n); n := ''; end; function TKDT4DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DI64_Node; function SortCompare(const p1, p2: PKDT4DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT4DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT4DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT4DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT4DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT4DI64.GetData(const Index: NativeInt): PKDT4DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT4DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT4DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT4DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT4DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT4DI64.StoreBuffPtr: PKDT4DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT4DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT4DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT4DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT4DI64.BuildKDTreeWithCluster(const inBuff: TKDT4DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT4DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT4DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT4DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT4DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT4DI64.BuildKDTreeWithCluster(const inBuff: TKDT4DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT4DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildCall); var TempStoreBuff: TKDT4DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT4DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT4DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildMethod); var TempStoreBuff: TKDT4DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT4DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT4DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI64_BuildProc); var TempStoreBuff: TKDT4DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT4DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT4DI64.Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DI64_Node; var NearestNeighbour: PKDT4DI64_Node; function FindParentNode(const buffPtr: PKDT4DI64_Vec; NodePtr: PKDT4DI64_Node): PKDT4DI64_Node; var Next: PKDT4DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT4DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT4DI64_Node; const buffPtr: PKDT4DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT4DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT4DI64_Vec; const p1, p2: PKDT4DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT4DI64_Vec); var i, j: NativeInt; p, t: PKDT4DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT4DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT4DI64_Node(NearestNodes[0]); end; end; function TKDT4DI64.Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT4DI64.Search(const buff: TKDT4DI64_Vec; var SearchedDistanceMin: Double): PKDT4DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT4DI64.Search(const buff: TKDT4DI64_Vec): PKDT4DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT4DI64.SearchToken(const buff: TKDT4DI64_Vec): TPascalString; var p: PKDT4DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT4DI64.Search(const inBuff: TKDT4DI64_DynamicVecBuffer; var OutBuff: TKDT4DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT4DI64_DynamicVecBuffer; outBuffPtr: PKDT4DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT4DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT4DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT4DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT4DI64.Search(const inBuff: TKDT4DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT4DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT4DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT4DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT4DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT4DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT4DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT4DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT4DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT4DI64_Vec)) <> SizeOf(TKDT4DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT4DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT4DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT4DI64.PrintNodeTree(const NodePtr: PKDT4DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT4DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT4DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT4DI64.Vec(const s: SystemString): TKDT4DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT4DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT4DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT4DI64.Vec(const v: TKDT4DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT4DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT4DI64.Distance(const v1, v2: TKDT4DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT4DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT4DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT4DI64.Test; var TKDT4DI64_Test: TKDT4DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT4DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT4DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT4DI64_Test := TKDT4DI64.Create; n.Append('...'); SetLength(TKDT4DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT4DI64_Test.TestBuff) - 1 do for j := 0 to KDT4DI64_Axis - 1 do TKDT4DI64_Test.TestBuff[i][j] := i * KDT4DI64_Axis + j; {$IFDEF FPC} TKDT4DI64_Test.BuildKDTreeM(length(TKDT4DI64_Test.TestBuff), nil, @TKDT4DI64_Test.Test_BuildM); {$ELSE FPC} TKDT4DI64_Test.BuildKDTreeM(length(TKDT4DI64_Test.TestBuff), nil, TKDT4DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT4DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT4DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT4DI64_Test.TestBuff) - 1 do begin p := TKDT4DI64_Test.Search(TKDT4DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT4DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT4DI64_Test.TestBuff)); TKDT4DI64_Test.Search(TKDT4DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT4DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT4DI64_Test.Clear; { kMean test } TKDT4DI64_Test.BuildKDTreeWithCluster(TKDT4DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT4DI64_Test.Search(TKDT4DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT4DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT4DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT4DI64_Test); DoStatus(n); n := ''; end; function TKDT5DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DI64_Node; function SortCompare(const p1, p2: PKDT5DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT5DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT5DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT5DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT5DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT5DI64.GetData(const Index: NativeInt): PKDT5DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT5DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT5DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT5DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT5DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT5DI64.StoreBuffPtr: PKDT5DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT5DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT5DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT5DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT5DI64.BuildKDTreeWithCluster(const inBuff: TKDT5DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT5DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT5DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT5DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT5DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT5DI64.BuildKDTreeWithCluster(const inBuff: TKDT5DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT5DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildCall); var TempStoreBuff: TKDT5DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT5DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT5DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildMethod); var TempStoreBuff: TKDT5DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT5DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT5DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI64_BuildProc); var TempStoreBuff: TKDT5DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT5DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT5DI64.Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DI64_Node; var NearestNeighbour: PKDT5DI64_Node; function FindParentNode(const buffPtr: PKDT5DI64_Vec; NodePtr: PKDT5DI64_Node): PKDT5DI64_Node; var Next: PKDT5DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT5DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT5DI64_Node; const buffPtr: PKDT5DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT5DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT5DI64_Vec; const p1, p2: PKDT5DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT5DI64_Vec); var i, j: NativeInt; p, t: PKDT5DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT5DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT5DI64_Node(NearestNodes[0]); end; end; function TKDT5DI64.Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT5DI64.Search(const buff: TKDT5DI64_Vec; var SearchedDistanceMin: Double): PKDT5DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT5DI64.Search(const buff: TKDT5DI64_Vec): PKDT5DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT5DI64.SearchToken(const buff: TKDT5DI64_Vec): TPascalString; var p: PKDT5DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT5DI64.Search(const inBuff: TKDT5DI64_DynamicVecBuffer; var OutBuff: TKDT5DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT5DI64_DynamicVecBuffer; outBuffPtr: PKDT5DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT5DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT5DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT5DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT5DI64.Search(const inBuff: TKDT5DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT5DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT5DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT5DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT5DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT5DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT5DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT5DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT5DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT5DI64_Vec)) <> SizeOf(TKDT5DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT5DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT5DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT5DI64.PrintNodeTree(const NodePtr: PKDT5DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT5DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT5DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT5DI64.Vec(const s: SystemString): TKDT5DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT5DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT5DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT5DI64.Vec(const v: TKDT5DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT5DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT5DI64.Distance(const v1, v2: TKDT5DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT5DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT5DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT5DI64.Test; var TKDT5DI64_Test: TKDT5DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT5DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT5DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT5DI64_Test := TKDT5DI64.Create; n.Append('...'); SetLength(TKDT5DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT5DI64_Test.TestBuff) - 1 do for j := 0 to KDT5DI64_Axis - 1 do TKDT5DI64_Test.TestBuff[i][j] := i * KDT5DI64_Axis + j; {$IFDEF FPC} TKDT5DI64_Test.BuildKDTreeM(length(TKDT5DI64_Test.TestBuff), nil, @TKDT5DI64_Test.Test_BuildM); {$ELSE FPC} TKDT5DI64_Test.BuildKDTreeM(length(TKDT5DI64_Test.TestBuff), nil, TKDT5DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT5DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT5DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT5DI64_Test.TestBuff) - 1 do begin p := TKDT5DI64_Test.Search(TKDT5DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT5DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT5DI64_Test.TestBuff)); TKDT5DI64_Test.Search(TKDT5DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT5DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT5DI64_Test.Clear; { kMean test } TKDT5DI64_Test.BuildKDTreeWithCluster(TKDT5DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT5DI64_Test.Search(TKDT5DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT5DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT5DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT5DI64_Test); DoStatus(n); n := ''; end; function TKDT6DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DI64_Node; function SortCompare(const p1, p2: PKDT6DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT6DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT6DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT6DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT6DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT6DI64.GetData(const Index: NativeInt): PKDT6DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT6DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT6DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT6DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT6DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT6DI64.StoreBuffPtr: PKDT6DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT6DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT6DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT6DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT6DI64.BuildKDTreeWithCluster(const inBuff: TKDT6DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT6DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT6DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT6DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT6DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT6DI64.BuildKDTreeWithCluster(const inBuff: TKDT6DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT6DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildCall); var TempStoreBuff: TKDT6DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT6DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT6DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildMethod); var TempStoreBuff: TKDT6DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT6DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT6DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI64_BuildProc); var TempStoreBuff: TKDT6DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT6DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT6DI64.Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DI64_Node; var NearestNeighbour: PKDT6DI64_Node; function FindParentNode(const buffPtr: PKDT6DI64_Vec; NodePtr: PKDT6DI64_Node): PKDT6DI64_Node; var Next: PKDT6DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT6DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT6DI64_Node; const buffPtr: PKDT6DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT6DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT6DI64_Vec; const p1, p2: PKDT6DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT6DI64_Vec); var i, j: NativeInt; p, t: PKDT6DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT6DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT6DI64_Node(NearestNodes[0]); end; end; function TKDT6DI64.Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT6DI64.Search(const buff: TKDT6DI64_Vec; var SearchedDistanceMin: Double): PKDT6DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT6DI64.Search(const buff: TKDT6DI64_Vec): PKDT6DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT6DI64.SearchToken(const buff: TKDT6DI64_Vec): TPascalString; var p: PKDT6DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT6DI64.Search(const inBuff: TKDT6DI64_DynamicVecBuffer; var OutBuff: TKDT6DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT6DI64_DynamicVecBuffer; outBuffPtr: PKDT6DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT6DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT6DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT6DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT6DI64.Search(const inBuff: TKDT6DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT6DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT6DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT6DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT6DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT6DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT6DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT6DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT6DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT6DI64_Vec)) <> SizeOf(TKDT6DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT6DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT6DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT6DI64.PrintNodeTree(const NodePtr: PKDT6DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT6DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT6DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT6DI64.Vec(const s: SystemString): TKDT6DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT6DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT6DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT6DI64.Vec(const v: TKDT6DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT6DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT6DI64.Distance(const v1, v2: TKDT6DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT6DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT6DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT6DI64.Test; var TKDT6DI64_Test: TKDT6DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT6DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT6DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT6DI64_Test := TKDT6DI64.Create; n.Append('...'); SetLength(TKDT6DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT6DI64_Test.TestBuff) - 1 do for j := 0 to KDT6DI64_Axis - 1 do TKDT6DI64_Test.TestBuff[i][j] := i * KDT6DI64_Axis + j; {$IFDEF FPC} TKDT6DI64_Test.BuildKDTreeM(length(TKDT6DI64_Test.TestBuff), nil, @TKDT6DI64_Test.Test_BuildM); {$ELSE FPC} TKDT6DI64_Test.BuildKDTreeM(length(TKDT6DI64_Test.TestBuff), nil, TKDT6DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT6DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT6DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT6DI64_Test.TestBuff) - 1 do begin p := TKDT6DI64_Test.Search(TKDT6DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT6DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT6DI64_Test.TestBuff)); TKDT6DI64_Test.Search(TKDT6DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT6DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT6DI64_Test.Clear; { kMean test } TKDT6DI64_Test.BuildKDTreeWithCluster(TKDT6DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT6DI64_Test.Search(TKDT6DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT6DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT6DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT6DI64_Test); DoStatus(n); n := ''; end; function TKDT7DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DI64_Node; function SortCompare(const p1, p2: PKDT7DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT7DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT7DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT7DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT7DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT7DI64.GetData(const Index: NativeInt): PKDT7DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT7DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT7DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT7DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT7DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT7DI64.StoreBuffPtr: PKDT7DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT7DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT7DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT7DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT7DI64.BuildKDTreeWithCluster(const inBuff: TKDT7DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT7DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT7DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT7DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT7DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT7DI64.BuildKDTreeWithCluster(const inBuff: TKDT7DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT7DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildCall); var TempStoreBuff: TKDT7DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT7DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT7DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildMethod); var TempStoreBuff: TKDT7DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT7DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT7DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI64_BuildProc); var TempStoreBuff: TKDT7DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT7DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT7DI64.Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DI64_Node; var NearestNeighbour: PKDT7DI64_Node; function FindParentNode(const buffPtr: PKDT7DI64_Vec; NodePtr: PKDT7DI64_Node): PKDT7DI64_Node; var Next: PKDT7DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT7DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT7DI64_Node; const buffPtr: PKDT7DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT7DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT7DI64_Vec; const p1, p2: PKDT7DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT7DI64_Vec); var i, j: NativeInt; p, t: PKDT7DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT7DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT7DI64_Node(NearestNodes[0]); end; end; function TKDT7DI64.Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT7DI64.Search(const buff: TKDT7DI64_Vec; var SearchedDistanceMin: Double): PKDT7DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT7DI64.Search(const buff: TKDT7DI64_Vec): PKDT7DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT7DI64.SearchToken(const buff: TKDT7DI64_Vec): TPascalString; var p: PKDT7DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT7DI64.Search(const inBuff: TKDT7DI64_DynamicVecBuffer; var OutBuff: TKDT7DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT7DI64_DynamicVecBuffer; outBuffPtr: PKDT7DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT7DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT7DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT7DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT7DI64.Search(const inBuff: TKDT7DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT7DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT7DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT7DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT7DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT7DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT7DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT7DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT7DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT7DI64_Vec)) <> SizeOf(TKDT7DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT7DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT7DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT7DI64.PrintNodeTree(const NodePtr: PKDT7DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT7DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT7DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT7DI64.Vec(const s: SystemString): TKDT7DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT7DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT7DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT7DI64.Vec(const v: TKDT7DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT7DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT7DI64.Distance(const v1, v2: TKDT7DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT7DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT7DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT7DI64.Test; var TKDT7DI64_Test: TKDT7DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT7DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT7DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT7DI64_Test := TKDT7DI64.Create; n.Append('...'); SetLength(TKDT7DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT7DI64_Test.TestBuff) - 1 do for j := 0 to KDT7DI64_Axis - 1 do TKDT7DI64_Test.TestBuff[i][j] := i * KDT7DI64_Axis + j; {$IFDEF FPC} TKDT7DI64_Test.BuildKDTreeM(length(TKDT7DI64_Test.TestBuff), nil, @TKDT7DI64_Test.Test_BuildM); {$ELSE FPC} TKDT7DI64_Test.BuildKDTreeM(length(TKDT7DI64_Test.TestBuff), nil, TKDT7DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT7DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT7DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT7DI64_Test.TestBuff) - 1 do begin p := TKDT7DI64_Test.Search(TKDT7DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT7DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT7DI64_Test.TestBuff)); TKDT7DI64_Test.Search(TKDT7DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT7DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT7DI64_Test.Clear; { kMean test } TKDT7DI64_Test.BuildKDTreeWithCluster(TKDT7DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT7DI64_Test.Search(TKDT7DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT7DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT7DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT7DI64_Test); DoStatus(n); n := ''; end; function TKDT8DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DI64_Node; function SortCompare(const p1, p2: PKDT8DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT8DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT8DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT8DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT8DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT8DI64.GetData(const Index: NativeInt): PKDT8DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT8DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT8DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT8DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT8DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT8DI64.StoreBuffPtr: PKDT8DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT8DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT8DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT8DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT8DI64.BuildKDTreeWithCluster(const inBuff: TKDT8DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT8DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT8DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT8DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT8DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT8DI64.BuildKDTreeWithCluster(const inBuff: TKDT8DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT8DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildCall); var TempStoreBuff: TKDT8DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT8DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT8DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildMethod); var TempStoreBuff: TKDT8DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT8DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT8DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI64_BuildProc); var TempStoreBuff: TKDT8DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT8DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT8DI64.Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DI64_Node; var NearestNeighbour: PKDT8DI64_Node; function FindParentNode(const buffPtr: PKDT8DI64_Vec; NodePtr: PKDT8DI64_Node): PKDT8DI64_Node; var Next: PKDT8DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT8DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT8DI64_Node; const buffPtr: PKDT8DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT8DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT8DI64_Vec; const p1, p2: PKDT8DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT8DI64_Vec); var i, j: NativeInt; p, t: PKDT8DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT8DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT8DI64_Node(NearestNodes[0]); end; end; function TKDT8DI64.Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT8DI64.Search(const buff: TKDT8DI64_Vec; var SearchedDistanceMin: Double): PKDT8DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT8DI64.Search(const buff: TKDT8DI64_Vec): PKDT8DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT8DI64.SearchToken(const buff: TKDT8DI64_Vec): TPascalString; var p: PKDT8DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT8DI64.Search(const inBuff: TKDT8DI64_DynamicVecBuffer; var OutBuff: TKDT8DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT8DI64_DynamicVecBuffer; outBuffPtr: PKDT8DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT8DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT8DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT8DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT8DI64.Search(const inBuff: TKDT8DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT8DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT8DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT8DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT8DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT8DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT8DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT8DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT8DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT8DI64_Vec)) <> SizeOf(TKDT8DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT8DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT8DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT8DI64.PrintNodeTree(const NodePtr: PKDT8DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT8DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT8DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT8DI64.Vec(const s: SystemString): TKDT8DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT8DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT8DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT8DI64.Vec(const v: TKDT8DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT8DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT8DI64.Distance(const v1, v2: TKDT8DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT8DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT8DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT8DI64.Test; var TKDT8DI64_Test: TKDT8DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT8DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT8DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT8DI64_Test := TKDT8DI64.Create; n.Append('...'); SetLength(TKDT8DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT8DI64_Test.TestBuff) - 1 do for j := 0 to KDT8DI64_Axis - 1 do TKDT8DI64_Test.TestBuff[i][j] := i * KDT8DI64_Axis + j; {$IFDEF FPC} TKDT8DI64_Test.BuildKDTreeM(length(TKDT8DI64_Test.TestBuff), nil, @TKDT8DI64_Test.Test_BuildM); {$ELSE FPC} TKDT8DI64_Test.BuildKDTreeM(length(TKDT8DI64_Test.TestBuff), nil, TKDT8DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT8DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT8DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT8DI64_Test.TestBuff) - 1 do begin p := TKDT8DI64_Test.Search(TKDT8DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT8DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT8DI64_Test.TestBuff)); TKDT8DI64_Test.Search(TKDT8DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT8DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT8DI64_Test.Clear; { kMean test } TKDT8DI64_Test.BuildKDTreeWithCluster(TKDT8DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT8DI64_Test.Search(TKDT8DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT8DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT8DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT8DI64_Test); DoStatus(n); n := ''; end; function TKDT9DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DI64_Node; function SortCompare(const p1, p2: PKDT9DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT9DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT9DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT9DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT9DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT9DI64.GetData(const Index: NativeInt): PKDT9DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT9DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT9DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT9DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT9DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT9DI64.StoreBuffPtr: PKDT9DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT9DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT9DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT9DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT9DI64.BuildKDTreeWithCluster(const inBuff: TKDT9DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT9DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT9DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT9DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT9DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT9DI64.BuildKDTreeWithCluster(const inBuff: TKDT9DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT9DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildCall); var TempStoreBuff: TKDT9DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT9DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT9DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildMethod); var TempStoreBuff: TKDT9DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT9DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT9DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI64_BuildProc); var TempStoreBuff: TKDT9DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT9DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT9DI64.Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DI64_Node; var NearestNeighbour: PKDT9DI64_Node; function FindParentNode(const buffPtr: PKDT9DI64_Vec; NodePtr: PKDT9DI64_Node): PKDT9DI64_Node; var Next: PKDT9DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT9DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT9DI64_Node; const buffPtr: PKDT9DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT9DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT9DI64_Vec; const p1, p2: PKDT9DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT9DI64_Vec); var i, j: NativeInt; p, t: PKDT9DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT9DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT9DI64_Node(NearestNodes[0]); end; end; function TKDT9DI64.Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT9DI64.Search(const buff: TKDT9DI64_Vec; var SearchedDistanceMin: Double): PKDT9DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT9DI64.Search(const buff: TKDT9DI64_Vec): PKDT9DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT9DI64.SearchToken(const buff: TKDT9DI64_Vec): TPascalString; var p: PKDT9DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT9DI64.Search(const inBuff: TKDT9DI64_DynamicVecBuffer; var OutBuff: TKDT9DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT9DI64_DynamicVecBuffer; outBuffPtr: PKDT9DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT9DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT9DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT9DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT9DI64.Search(const inBuff: TKDT9DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT9DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT9DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT9DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT9DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT9DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT9DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT9DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT9DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT9DI64_Vec)) <> SizeOf(TKDT9DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT9DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT9DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT9DI64.PrintNodeTree(const NodePtr: PKDT9DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT9DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT9DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT9DI64.Vec(const s: SystemString): TKDT9DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT9DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT9DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT9DI64.Vec(const v: TKDT9DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT9DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT9DI64.Distance(const v1, v2: TKDT9DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT9DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT9DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT9DI64.Test; var TKDT9DI64_Test: TKDT9DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT9DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT9DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT9DI64_Test := TKDT9DI64.Create; n.Append('...'); SetLength(TKDT9DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT9DI64_Test.TestBuff) - 1 do for j := 0 to KDT9DI64_Axis - 1 do TKDT9DI64_Test.TestBuff[i][j] := i * KDT9DI64_Axis + j; {$IFDEF FPC} TKDT9DI64_Test.BuildKDTreeM(length(TKDT9DI64_Test.TestBuff), nil, @TKDT9DI64_Test.Test_BuildM); {$ELSE FPC} TKDT9DI64_Test.BuildKDTreeM(length(TKDT9DI64_Test.TestBuff), nil, TKDT9DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT9DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT9DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT9DI64_Test.TestBuff) - 1 do begin p := TKDT9DI64_Test.Search(TKDT9DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT9DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT9DI64_Test.TestBuff)); TKDT9DI64_Test.Search(TKDT9DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT9DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT9DI64_Test.Clear; { kMean test } TKDT9DI64_Test.BuildKDTreeWithCluster(TKDT9DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT9DI64_Test.Search(TKDT9DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT9DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT9DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT9DI64_Test); DoStatus(n); n := ''; end; function TKDT10DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DI64_Node; function SortCompare(const p1, p2: PKDT10DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT10DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT10DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT10DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT10DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT10DI64.GetData(const Index: NativeInt): PKDT10DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT10DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT10DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT10DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT10DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT10DI64.StoreBuffPtr: PKDT10DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT10DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT10DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT10DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT10DI64.BuildKDTreeWithCluster(const inBuff: TKDT10DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT10DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT10DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT10DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT10DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT10DI64.BuildKDTreeWithCluster(const inBuff: TKDT10DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT10DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildCall); var TempStoreBuff: TKDT10DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT10DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT10DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildMethod); var TempStoreBuff: TKDT10DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT10DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT10DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI64_BuildProc); var TempStoreBuff: TKDT10DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT10DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT10DI64.Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DI64_Node; var NearestNeighbour: PKDT10DI64_Node; function FindParentNode(const buffPtr: PKDT10DI64_Vec; NodePtr: PKDT10DI64_Node): PKDT10DI64_Node; var Next: PKDT10DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT10DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT10DI64_Node; const buffPtr: PKDT10DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT10DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT10DI64_Vec; const p1, p2: PKDT10DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT10DI64_Vec); var i, j: NativeInt; p, t: PKDT10DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT10DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT10DI64_Node(NearestNodes[0]); end; end; function TKDT10DI64.Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT10DI64.Search(const buff: TKDT10DI64_Vec; var SearchedDistanceMin: Double): PKDT10DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT10DI64.Search(const buff: TKDT10DI64_Vec): PKDT10DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT10DI64.SearchToken(const buff: TKDT10DI64_Vec): TPascalString; var p: PKDT10DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT10DI64.Search(const inBuff: TKDT10DI64_DynamicVecBuffer; var OutBuff: TKDT10DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT10DI64_DynamicVecBuffer; outBuffPtr: PKDT10DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT10DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT10DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT10DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT10DI64.Search(const inBuff: TKDT10DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT10DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT10DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT10DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT10DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT10DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT10DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT10DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT10DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT10DI64_Vec)) <> SizeOf(TKDT10DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT10DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT10DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT10DI64.PrintNodeTree(const NodePtr: PKDT10DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT10DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT10DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT10DI64.Vec(const s: SystemString): TKDT10DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT10DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT10DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT10DI64.Vec(const v: TKDT10DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT10DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT10DI64.Distance(const v1, v2: TKDT10DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT10DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT10DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT10DI64.Test; var TKDT10DI64_Test: TKDT10DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT10DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT10DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT10DI64_Test := TKDT10DI64.Create; n.Append('...'); SetLength(TKDT10DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT10DI64_Test.TestBuff) - 1 do for j := 0 to KDT10DI64_Axis - 1 do TKDT10DI64_Test.TestBuff[i][j] := i * KDT10DI64_Axis + j; {$IFDEF FPC} TKDT10DI64_Test.BuildKDTreeM(length(TKDT10DI64_Test.TestBuff), nil, @TKDT10DI64_Test.Test_BuildM); {$ELSE FPC} TKDT10DI64_Test.BuildKDTreeM(length(TKDT10DI64_Test.TestBuff), nil, TKDT10DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT10DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT10DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT10DI64_Test.TestBuff) - 1 do begin p := TKDT10DI64_Test.Search(TKDT10DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT10DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT10DI64_Test.TestBuff)); TKDT10DI64_Test.Search(TKDT10DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT10DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT10DI64_Test.Clear; { kMean test } TKDT10DI64_Test.BuildKDTreeWithCluster(TKDT10DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT10DI64_Test.Search(TKDT10DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT10DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT10DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT10DI64_Test); DoStatus(n); n := ''; end; function TKDT11DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DI64_Node; function SortCompare(const p1, p2: PKDT11DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT11DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT11DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT11DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT11DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT11DI64.GetData(const Index: NativeInt): PKDT11DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT11DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT11DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT11DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT11DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT11DI64.StoreBuffPtr: PKDT11DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT11DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT11DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT11DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT11DI64.BuildKDTreeWithCluster(const inBuff: TKDT11DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT11DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT11DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT11DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT11DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT11DI64.BuildKDTreeWithCluster(const inBuff: TKDT11DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT11DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildCall); var TempStoreBuff: TKDT11DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT11DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT11DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildMethod); var TempStoreBuff: TKDT11DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT11DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT11DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI64_BuildProc); var TempStoreBuff: TKDT11DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT11DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT11DI64.Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DI64_Node; var NearestNeighbour: PKDT11DI64_Node; function FindParentNode(const buffPtr: PKDT11DI64_Vec; NodePtr: PKDT11DI64_Node): PKDT11DI64_Node; var Next: PKDT11DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT11DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT11DI64_Node; const buffPtr: PKDT11DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT11DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT11DI64_Vec; const p1, p2: PKDT11DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT11DI64_Vec); var i, j: NativeInt; p, t: PKDT11DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT11DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT11DI64_Node(NearestNodes[0]); end; end; function TKDT11DI64.Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT11DI64.Search(const buff: TKDT11DI64_Vec; var SearchedDistanceMin: Double): PKDT11DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT11DI64.Search(const buff: TKDT11DI64_Vec): PKDT11DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT11DI64.SearchToken(const buff: TKDT11DI64_Vec): TPascalString; var p: PKDT11DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT11DI64.Search(const inBuff: TKDT11DI64_DynamicVecBuffer; var OutBuff: TKDT11DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT11DI64_DynamicVecBuffer; outBuffPtr: PKDT11DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT11DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT11DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT11DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT11DI64.Search(const inBuff: TKDT11DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT11DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT11DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT11DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT11DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT11DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT11DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT11DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT11DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT11DI64_Vec)) <> SizeOf(TKDT11DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT11DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT11DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT11DI64.PrintNodeTree(const NodePtr: PKDT11DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT11DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT11DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT11DI64.Vec(const s: SystemString): TKDT11DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT11DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT11DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT11DI64.Vec(const v: TKDT11DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT11DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT11DI64.Distance(const v1, v2: TKDT11DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT11DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT11DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT11DI64.Test; var TKDT11DI64_Test: TKDT11DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT11DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT11DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT11DI64_Test := TKDT11DI64.Create; n.Append('...'); SetLength(TKDT11DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT11DI64_Test.TestBuff) - 1 do for j := 0 to KDT11DI64_Axis - 1 do TKDT11DI64_Test.TestBuff[i][j] := i * KDT11DI64_Axis + j; {$IFDEF FPC} TKDT11DI64_Test.BuildKDTreeM(length(TKDT11DI64_Test.TestBuff), nil, @TKDT11DI64_Test.Test_BuildM); {$ELSE FPC} TKDT11DI64_Test.BuildKDTreeM(length(TKDT11DI64_Test.TestBuff), nil, TKDT11DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT11DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT11DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT11DI64_Test.TestBuff) - 1 do begin p := TKDT11DI64_Test.Search(TKDT11DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT11DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT11DI64_Test.TestBuff)); TKDT11DI64_Test.Search(TKDT11DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT11DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT11DI64_Test.Clear; { kMean test } TKDT11DI64_Test.BuildKDTreeWithCluster(TKDT11DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT11DI64_Test.Search(TKDT11DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT11DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT11DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT11DI64_Test); DoStatus(n); n := ''; end; function TKDT12DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DI64_Node; function SortCompare(const p1, p2: PKDT12DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT12DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT12DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT12DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT12DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT12DI64.GetData(const Index: NativeInt): PKDT12DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT12DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT12DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT12DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT12DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT12DI64.StoreBuffPtr: PKDT12DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT12DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT12DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT12DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT12DI64.BuildKDTreeWithCluster(const inBuff: TKDT12DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT12DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT12DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT12DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT12DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT12DI64.BuildKDTreeWithCluster(const inBuff: TKDT12DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT12DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildCall); var TempStoreBuff: TKDT12DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT12DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT12DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildMethod); var TempStoreBuff: TKDT12DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT12DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT12DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI64_BuildProc); var TempStoreBuff: TKDT12DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT12DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT12DI64.Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DI64_Node; var NearestNeighbour: PKDT12DI64_Node; function FindParentNode(const buffPtr: PKDT12DI64_Vec; NodePtr: PKDT12DI64_Node): PKDT12DI64_Node; var Next: PKDT12DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT12DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT12DI64_Node; const buffPtr: PKDT12DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT12DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT12DI64_Vec; const p1, p2: PKDT12DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT12DI64_Vec); var i, j: NativeInt; p, t: PKDT12DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT12DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT12DI64_Node(NearestNodes[0]); end; end; function TKDT12DI64.Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT12DI64.Search(const buff: TKDT12DI64_Vec; var SearchedDistanceMin: Double): PKDT12DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT12DI64.Search(const buff: TKDT12DI64_Vec): PKDT12DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT12DI64.SearchToken(const buff: TKDT12DI64_Vec): TPascalString; var p: PKDT12DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT12DI64.Search(const inBuff: TKDT12DI64_DynamicVecBuffer; var OutBuff: TKDT12DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT12DI64_DynamicVecBuffer; outBuffPtr: PKDT12DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT12DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT12DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT12DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT12DI64.Search(const inBuff: TKDT12DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT12DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT12DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT12DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT12DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT12DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT12DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT12DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT12DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT12DI64_Vec)) <> SizeOf(TKDT12DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT12DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT12DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT12DI64.PrintNodeTree(const NodePtr: PKDT12DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT12DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT12DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT12DI64.Vec(const s: SystemString): TKDT12DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT12DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT12DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT12DI64.Vec(const v: TKDT12DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT12DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT12DI64.Distance(const v1, v2: TKDT12DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT12DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT12DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT12DI64.Test; var TKDT12DI64_Test: TKDT12DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT12DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT12DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT12DI64_Test := TKDT12DI64.Create; n.Append('...'); SetLength(TKDT12DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT12DI64_Test.TestBuff) - 1 do for j := 0 to KDT12DI64_Axis - 1 do TKDT12DI64_Test.TestBuff[i][j] := i * KDT12DI64_Axis + j; {$IFDEF FPC} TKDT12DI64_Test.BuildKDTreeM(length(TKDT12DI64_Test.TestBuff), nil, @TKDT12DI64_Test.Test_BuildM); {$ELSE FPC} TKDT12DI64_Test.BuildKDTreeM(length(TKDT12DI64_Test.TestBuff), nil, TKDT12DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT12DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT12DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT12DI64_Test.TestBuff) - 1 do begin p := TKDT12DI64_Test.Search(TKDT12DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT12DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT12DI64_Test.TestBuff)); TKDT12DI64_Test.Search(TKDT12DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT12DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT12DI64_Test.Clear; { kMean test } TKDT12DI64_Test.BuildKDTreeWithCluster(TKDT12DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT12DI64_Test.Search(TKDT12DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT12DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT12DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT12DI64_Test); DoStatus(n); n := ''; end; function TKDT13DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DI64_Node; function SortCompare(const p1, p2: PKDT13DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT13DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT13DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT13DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT13DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT13DI64.GetData(const Index: NativeInt): PKDT13DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT13DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT13DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT13DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT13DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT13DI64.StoreBuffPtr: PKDT13DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT13DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT13DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT13DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT13DI64.BuildKDTreeWithCluster(const inBuff: TKDT13DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT13DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT13DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT13DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT13DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT13DI64.BuildKDTreeWithCluster(const inBuff: TKDT13DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT13DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildCall); var TempStoreBuff: TKDT13DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT13DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT13DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildMethod); var TempStoreBuff: TKDT13DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT13DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT13DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI64_BuildProc); var TempStoreBuff: TKDT13DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT13DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT13DI64.Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DI64_Node; var NearestNeighbour: PKDT13DI64_Node; function FindParentNode(const buffPtr: PKDT13DI64_Vec; NodePtr: PKDT13DI64_Node): PKDT13DI64_Node; var Next: PKDT13DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT13DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT13DI64_Node; const buffPtr: PKDT13DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT13DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT13DI64_Vec; const p1, p2: PKDT13DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT13DI64_Vec); var i, j: NativeInt; p, t: PKDT13DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT13DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT13DI64_Node(NearestNodes[0]); end; end; function TKDT13DI64.Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT13DI64.Search(const buff: TKDT13DI64_Vec; var SearchedDistanceMin: Double): PKDT13DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT13DI64.Search(const buff: TKDT13DI64_Vec): PKDT13DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT13DI64.SearchToken(const buff: TKDT13DI64_Vec): TPascalString; var p: PKDT13DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT13DI64.Search(const inBuff: TKDT13DI64_DynamicVecBuffer; var OutBuff: TKDT13DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT13DI64_DynamicVecBuffer; outBuffPtr: PKDT13DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT13DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT13DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT13DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT13DI64.Search(const inBuff: TKDT13DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT13DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT13DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT13DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT13DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT13DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT13DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT13DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT13DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT13DI64_Vec)) <> SizeOf(TKDT13DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT13DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT13DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT13DI64.PrintNodeTree(const NodePtr: PKDT13DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT13DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT13DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT13DI64.Vec(const s: SystemString): TKDT13DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT13DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT13DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT13DI64.Vec(const v: TKDT13DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT13DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT13DI64.Distance(const v1, v2: TKDT13DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT13DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT13DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT13DI64.Test; var TKDT13DI64_Test: TKDT13DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT13DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT13DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT13DI64_Test := TKDT13DI64.Create; n.Append('...'); SetLength(TKDT13DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT13DI64_Test.TestBuff) - 1 do for j := 0 to KDT13DI64_Axis - 1 do TKDT13DI64_Test.TestBuff[i][j] := i * KDT13DI64_Axis + j; {$IFDEF FPC} TKDT13DI64_Test.BuildKDTreeM(length(TKDT13DI64_Test.TestBuff), nil, @TKDT13DI64_Test.Test_BuildM); {$ELSE FPC} TKDT13DI64_Test.BuildKDTreeM(length(TKDT13DI64_Test.TestBuff), nil, TKDT13DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT13DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT13DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT13DI64_Test.TestBuff) - 1 do begin p := TKDT13DI64_Test.Search(TKDT13DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT13DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT13DI64_Test.TestBuff)); TKDT13DI64_Test.Search(TKDT13DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT13DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT13DI64_Test.Clear; { kMean test } TKDT13DI64_Test.BuildKDTreeWithCluster(TKDT13DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT13DI64_Test.Search(TKDT13DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT13DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT13DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT13DI64_Test); DoStatus(n); n := ''; end; function TKDT14DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DI64_Node; function SortCompare(const p1, p2: PKDT14DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT14DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT14DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT14DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT14DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT14DI64.GetData(const Index: NativeInt): PKDT14DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT14DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT14DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT14DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT14DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT14DI64.StoreBuffPtr: PKDT14DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT14DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT14DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT14DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT14DI64.BuildKDTreeWithCluster(const inBuff: TKDT14DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT14DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT14DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT14DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT14DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT14DI64.BuildKDTreeWithCluster(const inBuff: TKDT14DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT14DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildCall); var TempStoreBuff: TKDT14DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT14DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT14DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildMethod); var TempStoreBuff: TKDT14DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT14DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT14DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI64_BuildProc); var TempStoreBuff: TKDT14DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT14DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT14DI64.Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DI64_Node; var NearestNeighbour: PKDT14DI64_Node; function FindParentNode(const buffPtr: PKDT14DI64_Vec; NodePtr: PKDT14DI64_Node): PKDT14DI64_Node; var Next: PKDT14DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT14DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT14DI64_Node; const buffPtr: PKDT14DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT14DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT14DI64_Vec; const p1, p2: PKDT14DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT14DI64_Vec); var i, j: NativeInt; p, t: PKDT14DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT14DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT14DI64_Node(NearestNodes[0]); end; end; function TKDT14DI64.Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT14DI64.Search(const buff: TKDT14DI64_Vec; var SearchedDistanceMin: Double): PKDT14DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT14DI64.Search(const buff: TKDT14DI64_Vec): PKDT14DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT14DI64.SearchToken(const buff: TKDT14DI64_Vec): TPascalString; var p: PKDT14DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT14DI64.Search(const inBuff: TKDT14DI64_DynamicVecBuffer; var OutBuff: TKDT14DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT14DI64_DynamicVecBuffer; outBuffPtr: PKDT14DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT14DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT14DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT14DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT14DI64.Search(const inBuff: TKDT14DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT14DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT14DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT14DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT14DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT14DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT14DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT14DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT14DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT14DI64_Vec)) <> SizeOf(TKDT14DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT14DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT14DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT14DI64.PrintNodeTree(const NodePtr: PKDT14DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT14DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT14DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT14DI64.Vec(const s: SystemString): TKDT14DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT14DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT14DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT14DI64.Vec(const v: TKDT14DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT14DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT14DI64.Distance(const v1, v2: TKDT14DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT14DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT14DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT14DI64.Test; var TKDT14DI64_Test: TKDT14DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT14DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT14DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT14DI64_Test := TKDT14DI64.Create; n.Append('...'); SetLength(TKDT14DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT14DI64_Test.TestBuff) - 1 do for j := 0 to KDT14DI64_Axis - 1 do TKDT14DI64_Test.TestBuff[i][j] := i * KDT14DI64_Axis + j; {$IFDEF FPC} TKDT14DI64_Test.BuildKDTreeM(length(TKDT14DI64_Test.TestBuff), nil, @TKDT14DI64_Test.Test_BuildM); {$ELSE FPC} TKDT14DI64_Test.BuildKDTreeM(length(TKDT14DI64_Test.TestBuff), nil, TKDT14DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT14DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT14DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT14DI64_Test.TestBuff) - 1 do begin p := TKDT14DI64_Test.Search(TKDT14DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT14DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT14DI64_Test.TestBuff)); TKDT14DI64_Test.Search(TKDT14DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT14DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT14DI64_Test.Clear; { kMean test } TKDT14DI64_Test.BuildKDTreeWithCluster(TKDT14DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT14DI64_Test.Search(TKDT14DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT14DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT14DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT14DI64_Test); DoStatus(n); n := ''; end; function TKDT15DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DI64_Node; function SortCompare(const p1, p2: PKDT15DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT15DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT15DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT15DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT15DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT15DI64.GetData(const Index: NativeInt): PKDT15DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT15DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT15DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT15DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT15DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT15DI64.StoreBuffPtr: PKDT15DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT15DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT15DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT15DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT15DI64.BuildKDTreeWithCluster(const inBuff: TKDT15DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT15DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT15DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT15DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT15DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT15DI64.BuildKDTreeWithCluster(const inBuff: TKDT15DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT15DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildCall); var TempStoreBuff: TKDT15DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT15DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT15DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildMethod); var TempStoreBuff: TKDT15DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT15DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT15DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI64_BuildProc); var TempStoreBuff: TKDT15DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT15DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT15DI64.Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DI64_Node; var NearestNeighbour: PKDT15DI64_Node; function FindParentNode(const buffPtr: PKDT15DI64_Vec; NodePtr: PKDT15DI64_Node): PKDT15DI64_Node; var Next: PKDT15DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT15DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT15DI64_Node; const buffPtr: PKDT15DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT15DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT15DI64_Vec; const p1, p2: PKDT15DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT15DI64_Vec); var i, j: NativeInt; p, t: PKDT15DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT15DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT15DI64_Node(NearestNodes[0]); end; end; function TKDT15DI64.Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT15DI64.Search(const buff: TKDT15DI64_Vec; var SearchedDistanceMin: Double): PKDT15DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT15DI64.Search(const buff: TKDT15DI64_Vec): PKDT15DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT15DI64.SearchToken(const buff: TKDT15DI64_Vec): TPascalString; var p: PKDT15DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT15DI64.Search(const inBuff: TKDT15DI64_DynamicVecBuffer; var OutBuff: TKDT15DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT15DI64_DynamicVecBuffer; outBuffPtr: PKDT15DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT15DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT15DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT15DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT15DI64.Search(const inBuff: TKDT15DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT15DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT15DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT15DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT15DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT15DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT15DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT15DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT15DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT15DI64_Vec)) <> SizeOf(TKDT15DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT15DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT15DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT15DI64.PrintNodeTree(const NodePtr: PKDT15DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT15DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT15DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT15DI64.Vec(const s: SystemString): TKDT15DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT15DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT15DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT15DI64.Vec(const v: TKDT15DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT15DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT15DI64.Distance(const v1, v2: TKDT15DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT15DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT15DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT15DI64.Test; var TKDT15DI64_Test: TKDT15DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT15DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT15DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT15DI64_Test := TKDT15DI64.Create; n.Append('...'); SetLength(TKDT15DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT15DI64_Test.TestBuff) - 1 do for j := 0 to KDT15DI64_Axis - 1 do TKDT15DI64_Test.TestBuff[i][j] := i * KDT15DI64_Axis + j; {$IFDEF FPC} TKDT15DI64_Test.BuildKDTreeM(length(TKDT15DI64_Test.TestBuff), nil, @TKDT15DI64_Test.Test_BuildM); {$ELSE FPC} TKDT15DI64_Test.BuildKDTreeM(length(TKDT15DI64_Test.TestBuff), nil, TKDT15DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT15DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT15DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT15DI64_Test.TestBuff) - 1 do begin p := TKDT15DI64_Test.Search(TKDT15DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT15DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT15DI64_Test.TestBuff)); TKDT15DI64_Test.Search(TKDT15DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT15DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT15DI64_Test.Clear; { kMean test } TKDT15DI64_Test.BuildKDTreeWithCluster(TKDT15DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT15DI64_Test.Search(TKDT15DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT15DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT15DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT15DI64_Test); DoStatus(n); n := ''; end; function TKDT16DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DI64_Node; function SortCompare(const p1, p2: PKDT16DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT16DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT16DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT16DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT16DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT16DI64.GetData(const Index: NativeInt): PKDT16DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT16DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT16DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT16DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT16DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT16DI64.StoreBuffPtr: PKDT16DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT16DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT16DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT16DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT16DI64.BuildKDTreeWithCluster(const inBuff: TKDT16DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT16DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT16DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT16DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT16DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT16DI64.BuildKDTreeWithCluster(const inBuff: TKDT16DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT16DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildCall); var TempStoreBuff: TKDT16DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT16DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT16DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildMethod); var TempStoreBuff: TKDT16DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT16DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT16DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI64_BuildProc); var TempStoreBuff: TKDT16DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT16DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT16DI64.Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DI64_Node; var NearestNeighbour: PKDT16DI64_Node; function FindParentNode(const buffPtr: PKDT16DI64_Vec; NodePtr: PKDT16DI64_Node): PKDT16DI64_Node; var Next: PKDT16DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT16DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT16DI64_Node; const buffPtr: PKDT16DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT16DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT16DI64_Vec; const p1, p2: PKDT16DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT16DI64_Vec); var i, j: NativeInt; p, t: PKDT16DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT16DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT16DI64_Node(NearestNodes[0]); end; end; function TKDT16DI64.Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT16DI64.Search(const buff: TKDT16DI64_Vec; var SearchedDistanceMin: Double): PKDT16DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT16DI64.Search(const buff: TKDT16DI64_Vec): PKDT16DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT16DI64.SearchToken(const buff: TKDT16DI64_Vec): TPascalString; var p: PKDT16DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT16DI64.Search(const inBuff: TKDT16DI64_DynamicVecBuffer; var OutBuff: TKDT16DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT16DI64_DynamicVecBuffer; outBuffPtr: PKDT16DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT16DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT16DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT16DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT16DI64.Search(const inBuff: TKDT16DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT16DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT16DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT16DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT16DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT16DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT16DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT16DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT16DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT16DI64_Vec)) <> SizeOf(TKDT16DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT16DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT16DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT16DI64.PrintNodeTree(const NodePtr: PKDT16DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT16DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT16DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT16DI64.Vec(const s: SystemString): TKDT16DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT16DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT16DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT16DI64.Vec(const v: TKDT16DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT16DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT16DI64.Distance(const v1, v2: TKDT16DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT16DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT16DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT16DI64.Test; var TKDT16DI64_Test: TKDT16DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT16DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT16DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT16DI64_Test := TKDT16DI64.Create; n.Append('...'); SetLength(TKDT16DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT16DI64_Test.TestBuff) - 1 do for j := 0 to KDT16DI64_Axis - 1 do TKDT16DI64_Test.TestBuff[i][j] := i * KDT16DI64_Axis + j; {$IFDEF FPC} TKDT16DI64_Test.BuildKDTreeM(length(TKDT16DI64_Test.TestBuff), nil, @TKDT16DI64_Test.Test_BuildM); {$ELSE FPC} TKDT16DI64_Test.BuildKDTreeM(length(TKDT16DI64_Test.TestBuff), nil, TKDT16DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT16DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT16DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT16DI64_Test.TestBuff) - 1 do begin p := TKDT16DI64_Test.Search(TKDT16DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT16DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT16DI64_Test.TestBuff)); TKDT16DI64_Test.Search(TKDT16DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT16DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT16DI64_Test.Clear; { kMean test } TKDT16DI64_Test.BuildKDTreeWithCluster(TKDT16DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT16DI64_Test.Search(TKDT16DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT16DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT16DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT16DI64_Test); DoStatus(n); n := ''; end; function TKDT17DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DI64_Node; function SortCompare(const p1, p2: PKDT17DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT17DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT17DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT17DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT17DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT17DI64.GetData(const Index: NativeInt): PKDT17DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT17DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT17DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT17DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT17DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT17DI64.StoreBuffPtr: PKDT17DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT17DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT17DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT17DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT17DI64.BuildKDTreeWithCluster(const inBuff: TKDT17DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT17DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT17DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT17DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT17DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT17DI64.BuildKDTreeWithCluster(const inBuff: TKDT17DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT17DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildCall); var TempStoreBuff: TKDT17DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT17DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT17DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildMethod); var TempStoreBuff: TKDT17DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT17DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT17DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI64_BuildProc); var TempStoreBuff: TKDT17DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT17DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT17DI64.Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DI64_Node; var NearestNeighbour: PKDT17DI64_Node; function FindParentNode(const buffPtr: PKDT17DI64_Vec; NodePtr: PKDT17DI64_Node): PKDT17DI64_Node; var Next: PKDT17DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT17DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT17DI64_Node; const buffPtr: PKDT17DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT17DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT17DI64_Vec; const p1, p2: PKDT17DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT17DI64_Vec); var i, j: NativeInt; p, t: PKDT17DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT17DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT17DI64_Node(NearestNodes[0]); end; end; function TKDT17DI64.Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT17DI64.Search(const buff: TKDT17DI64_Vec; var SearchedDistanceMin: Double): PKDT17DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT17DI64.Search(const buff: TKDT17DI64_Vec): PKDT17DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT17DI64.SearchToken(const buff: TKDT17DI64_Vec): TPascalString; var p: PKDT17DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT17DI64.Search(const inBuff: TKDT17DI64_DynamicVecBuffer; var OutBuff: TKDT17DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT17DI64_DynamicVecBuffer; outBuffPtr: PKDT17DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT17DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT17DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT17DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT17DI64.Search(const inBuff: TKDT17DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT17DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT17DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT17DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT17DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT17DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT17DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT17DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT17DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT17DI64_Vec)) <> SizeOf(TKDT17DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT17DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT17DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT17DI64.PrintNodeTree(const NodePtr: PKDT17DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT17DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT17DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT17DI64.Vec(const s: SystemString): TKDT17DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT17DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT17DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT17DI64.Vec(const v: TKDT17DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT17DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT17DI64.Distance(const v1, v2: TKDT17DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT17DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT17DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT17DI64.Test; var TKDT17DI64_Test: TKDT17DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT17DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT17DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT17DI64_Test := TKDT17DI64.Create; n.Append('...'); SetLength(TKDT17DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT17DI64_Test.TestBuff) - 1 do for j := 0 to KDT17DI64_Axis - 1 do TKDT17DI64_Test.TestBuff[i][j] := i * KDT17DI64_Axis + j; {$IFDEF FPC} TKDT17DI64_Test.BuildKDTreeM(length(TKDT17DI64_Test.TestBuff), nil, @TKDT17DI64_Test.Test_BuildM); {$ELSE FPC} TKDT17DI64_Test.BuildKDTreeM(length(TKDT17DI64_Test.TestBuff), nil, TKDT17DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT17DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT17DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT17DI64_Test.TestBuff) - 1 do begin p := TKDT17DI64_Test.Search(TKDT17DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT17DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT17DI64_Test.TestBuff)); TKDT17DI64_Test.Search(TKDT17DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT17DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT17DI64_Test.Clear; { kMean test } TKDT17DI64_Test.BuildKDTreeWithCluster(TKDT17DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT17DI64_Test.Search(TKDT17DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT17DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT17DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT17DI64_Test); DoStatus(n); n := ''; end; function TKDT18DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DI64_Node; function SortCompare(const p1, p2: PKDT18DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT18DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT18DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT18DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT18DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT18DI64.GetData(const Index: NativeInt): PKDT18DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT18DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT18DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT18DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT18DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT18DI64.StoreBuffPtr: PKDT18DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT18DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT18DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT18DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT18DI64.BuildKDTreeWithCluster(const inBuff: TKDT18DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT18DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT18DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT18DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT18DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT18DI64.BuildKDTreeWithCluster(const inBuff: TKDT18DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT18DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildCall); var TempStoreBuff: TKDT18DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT18DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT18DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildMethod); var TempStoreBuff: TKDT18DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT18DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT18DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI64_BuildProc); var TempStoreBuff: TKDT18DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT18DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT18DI64.Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DI64_Node; var NearestNeighbour: PKDT18DI64_Node; function FindParentNode(const buffPtr: PKDT18DI64_Vec; NodePtr: PKDT18DI64_Node): PKDT18DI64_Node; var Next: PKDT18DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT18DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT18DI64_Node; const buffPtr: PKDT18DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT18DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT18DI64_Vec; const p1, p2: PKDT18DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT18DI64_Vec); var i, j: NativeInt; p, t: PKDT18DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT18DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT18DI64_Node(NearestNodes[0]); end; end; function TKDT18DI64.Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT18DI64.Search(const buff: TKDT18DI64_Vec; var SearchedDistanceMin: Double): PKDT18DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT18DI64.Search(const buff: TKDT18DI64_Vec): PKDT18DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT18DI64.SearchToken(const buff: TKDT18DI64_Vec): TPascalString; var p: PKDT18DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT18DI64.Search(const inBuff: TKDT18DI64_DynamicVecBuffer; var OutBuff: TKDT18DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT18DI64_DynamicVecBuffer; outBuffPtr: PKDT18DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT18DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT18DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT18DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT18DI64.Search(const inBuff: TKDT18DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT18DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT18DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT18DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT18DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT18DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT18DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT18DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT18DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT18DI64_Vec)) <> SizeOf(TKDT18DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT18DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT18DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT18DI64.PrintNodeTree(const NodePtr: PKDT18DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT18DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT18DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT18DI64.Vec(const s: SystemString): TKDT18DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT18DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT18DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT18DI64.Vec(const v: TKDT18DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT18DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT18DI64.Distance(const v1, v2: TKDT18DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT18DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT18DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT18DI64.Test; var TKDT18DI64_Test: TKDT18DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT18DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT18DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT18DI64_Test := TKDT18DI64.Create; n.Append('...'); SetLength(TKDT18DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT18DI64_Test.TestBuff) - 1 do for j := 0 to KDT18DI64_Axis - 1 do TKDT18DI64_Test.TestBuff[i][j] := i * KDT18DI64_Axis + j; {$IFDEF FPC} TKDT18DI64_Test.BuildKDTreeM(length(TKDT18DI64_Test.TestBuff), nil, @TKDT18DI64_Test.Test_BuildM); {$ELSE FPC} TKDT18DI64_Test.BuildKDTreeM(length(TKDT18DI64_Test.TestBuff), nil, TKDT18DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT18DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT18DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT18DI64_Test.TestBuff) - 1 do begin p := TKDT18DI64_Test.Search(TKDT18DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT18DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT18DI64_Test.TestBuff)); TKDT18DI64_Test.Search(TKDT18DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT18DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT18DI64_Test.Clear; { kMean test } TKDT18DI64_Test.BuildKDTreeWithCluster(TKDT18DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT18DI64_Test.Search(TKDT18DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT18DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT18DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT18DI64_Test); DoStatus(n); n := ''; end; function TKDT19DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DI64_Node; function SortCompare(const p1, p2: PKDT19DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT19DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT19DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT19DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT19DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT19DI64.GetData(const Index: NativeInt): PKDT19DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT19DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT19DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT19DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT19DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT19DI64.StoreBuffPtr: PKDT19DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT19DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT19DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT19DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT19DI64.BuildKDTreeWithCluster(const inBuff: TKDT19DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT19DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT19DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT19DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT19DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT19DI64.BuildKDTreeWithCluster(const inBuff: TKDT19DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT19DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildCall); var TempStoreBuff: TKDT19DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT19DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT19DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildMethod); var TempStoreBuff: TKDT19DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT19DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT19DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI64_BuildProc); var TempStoreBuff: TKDT19DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT19DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT19DI64.Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DI64_Node; var NearestNeighbour: PKDT19DI64_Node; function FindParentNode(const buffPtr: PKDT19DI64_Vec; NodePtr: PKDT19DI64_Node): PKDT19DI64_Node; var Next: PKDT19DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT19DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT19DI64_Node; const buffPtr: PKDT19DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT19DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT19DI64_Vec; const p1, p2: PKDT19DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT19DI64_Vec); var i, j: NativeInt; p, t: PKDT19DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT19DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT19DI64_Node(NearestNodes[0]); end; end; function TKDT19DI64.Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT19DI64.Search(const buff: TKDT19DI64_Vec; var SearchedDistanceMin: Double): PKDT19DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT19DI64.Search(const buff: TKDT19DI64_Vec): PKDT19DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT19DI64.SearchToken(const buff: TKDT19DI64_Vec): TPascalString; var p: PKDT19DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT19DI64.Search(const inBuff: TKDT19DI64_DynamicVecBuffer; var OutBuff: TKDT19DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT19DI64_DynamicVecBuffer; outBuffPtr: PKDT19DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT19DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT19DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT19DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT19DI64.Search(const inBuff: TKDT19DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT19DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT19DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT19DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT19DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT19DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT19DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT19DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT19DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT19DI64_Vec)) <> SizeOf(TKDT19DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT19DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT19DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT19DI64.PrintNodeTree(const NodePtr: PKDT19DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT19DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT19DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT19DI64.Vec(const s: SystemString): TKDT19DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT19DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT19DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT19DI64.Vec(const v: TKDT19DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT19DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT19DI64.Distance(const v1, v2: TKDT19DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT19DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT19DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT19DI64.Test; var TKDT19DI64_Test: TKDT19DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT19DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT19DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT19DI64_Test := TKDT19DI64.Create; n.Append('...'); SetLength(TKDT19DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT19DI64_Test.TestBuff) - 1 do for j := 0 to KDT19DI64_Axis - 1 do TKDT19DI64_Test.TestBuff[i][j] := i * KDT19DI64_Axis + j; {$IFDEF FPC} TKDT19DI64_Test.BuildKDTreeM(length(TKDT19DI64_Test.TestBuff), nil, @TKDT19DI64_Test.Test_BuildM); {$ELSE FPC} TKDT19DI64_Test.BuildKDTreeM(length(TKDT19DI64_Test.TestBuff), nil, TKDT19DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT19DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT19DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT19DI64_Test.TestBuff) - 1 do begin p := TKDT19DI64_Test.Search(TKDT19DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT19DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT19DI64_Test.TestBuff)); TKDT19DI64_Test.Search(TKDT19DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT19DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT19DI64_Test.Clear; { kMean test } TKDT19DI64_Test.BuildKDTreeWithCluster(TKDT19DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT19DI64_Test.Search(TKDT19DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT19DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT19DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT19DI64_Test); DoStatus(n); n := ''; end; function TKDT20DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DI64_Node; function SortCompare(const p1, p2: PKDT20DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT20DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT20DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT20DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT20DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT20DI64.GetData(const Index: NativeInt): PKDT20DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT20DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT20DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT20DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT20DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT20DI64.StoreBuffPtr: PKDT20DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT20DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT20DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT20DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT20DI64.BuildKDTreeWithCluster(const inBuff: TKDT20DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT20DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT20DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT20DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT20DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT20DI64.BuildKDTreeWithCluster(const inBuff: TKDT20DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT20DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildCall); var TempStoreBuff: TKDT20DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT20DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT20DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildMethod); var TempStoreBuff: TKDT20DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT20DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT20DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI64_BuildProc); var TempStoreBuff: TKDT20DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT20DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT20DI64.Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DI64_Node; var NearestNeighbour: PKDT20DI64_Node; function FindParentNode(const buffPtr: PKDT20DI64_Vec; NodePtr: PKDT20DI64_Node): PKDT20DI64_Node; var Next: PKDT20DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT20DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT20DI64_Node; const buffPtr: PKDT20DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT20DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT20DI64_Vec; const p1, p2: PKDT20DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT20DI64_Vec); var i, j: NativeInt; p, t: PKDT20DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT20DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT20DI64_Node(NearestNodes[0]); end; end; function TKDT20DI64.Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT20DI64.Search(const buff: TKDT20DI64_Vec; var SearchedDistanceMin: Double): PKDT20DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT20DI64.Search(const buff: TKDT20DI64_Vec): PKDT20DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT20DI64.SearchToken(const buff: TKDT20DI64_Vec): TPascalString; var p: PKDT20DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT20DI64.Search(const inBuff: TKDT20DI64_DynamicVecBuffer; var OutBuff: TKDT20DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT20DI64_DynamicVecBuffer; outBuffPtr: PKDT20DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT20DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT20DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT20DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT20DI64.Search(const inBuff: TKDT20DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT20DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT20DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT20DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT20DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT20DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT20DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT20DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT20DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT20DI64_Vec)) <> SizeOf(TKDT20DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT20DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT20DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT20DI64.PrintNodeTree(const NodePtr: PKDT20DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT20DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT20DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT20DI64.Vec(const s: SystemString): TKDT20DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT20DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT20DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT20DI64.Vec(const v: TKDT20DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT20DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT20DI64.Distance(const v1, v2: TKDT20DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT20DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT20DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT20DI64.Test; var TKDT20DI64_Test: TKDT20DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT20DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT20DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT20DI64_Test := TKDT20DI64.Create; n.Append('...'); SetLength(TKDT20DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT20DI64_Test.TestBuff) - 1 do for j := 0 to KDT20DI64_Axis - 1 do TKDT20DI64_Test.TestBuff[i][j] := i * KDT20DI64_Axis + j; {$IFDEF FPC} TKDT20DI64_Test.BuildKDTreeM(length(TKDT20DI64_Test.TestBuff), nil, @TKDT20DI64_Test.Test_BuildM); {$ELSE FPC} TKDT20DI64_Test.BuildKDTreeM(length(TKDT20DI64_Test.TestBuff), nil, TKDT20DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT20DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT20DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT20DI64_Test.TestBuff) - 1 do begin p := TKDT20DI64_Test.Search(TKDT20DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT20DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT20DI64_Test.TestBuff)); TKDT20DI64_Test.Search(TKDT20DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT20DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT20DI64_Test.Clear; { kMean test } TKDT20DI64_Test.BuildKDTreeWithCluster(TKDT20DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT20DI64_Test.Search(TKDT20DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT20DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT20DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT20DI64_Test); DoStatus(n); n := ''; end; function TKDT21DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DI64_Node; function SortCompare(const p1, p2: PKDT21DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT21DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT21DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT21DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT21DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT21DI64.GetData(const Index: NativeInt): PKDT21DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT21DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT21DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT21DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT21DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT21DI64.StoreBuffPtr: PKDT21DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT21DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT21DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT21DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT21DI64.BuildKDTreeWithCluster(const inBuff: TKDT21DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT21DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT21DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT21DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT21DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT21DI64.BuildKDTreeWithCluster(const inBuff: TKDT21DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT21DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildCall); var TempStoreBuff: TKDT21DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT21DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT21DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildMethod); var TempStoreBuff: TKDT21DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT21DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT21DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI64_BuildProc); var TempStoreBuff: TKDT21DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT21DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT21DI64.Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DI64_Node; var NearestNeighbour: PKDT21DI64_Node; function FindParentNode(const buffPtr: PKDT21DI64_Vec; NodePtr: PKDT21DI64_Node): PKDT21DI64_Node; var Next: PKDT21DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT21DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT21DI64_Node; const buffPtr: PKDT21DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT21DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT21DI64_Vec; const p1, p2: PKDT21DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT21DI64_Vec); var i, j: NativeInt; p, t: PKDT21DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT21DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT21DI64_Node(NearestNodes[0]); end; end; function TKDT21DI64.Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT21DI64.Search(const buff: TKDT21DI64_Vec; var SearchedDistanceMin: Double): PKDT21DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT21DI64.Search(const buff: TKDT21DI64_Vec): PKDT21DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT21DI64.SearchToken(const buff: TKDT21DI64_Vec): TPascalString; var p: PKDT21DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT21DI64.Search(const inBuff: TKDT21DI64_DynamicVecBuffer; var OutBuff: TKDT21DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT21DI64_DynamicVecBuffer; outBuffPtr: PKDT21DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT21DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT21DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT21DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT21DI64.Search(const inBuff: TKDT21DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT21DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT21DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT21DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT21DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT21DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT21DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT21DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT21DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT21DI64_Vec)) <> SizeOf(TKDT21DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT21DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT21DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT21DI64.PrintNodeTree(const NodePtr: PKDT21DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT21DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT21DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT21DI64.Vec(const s: SystemString): TKDT21DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT21DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT21DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT21DI64.Vec(const v: TKDT21DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT21DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT21DI64.Distance(const v1, v2: TKDT21DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT21DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT21DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT21DI64.Test; var TKDT21DI64_Test: TKDT21DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT21DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT21DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT21DI64_Test := TKDT21DI64.Create; n.Append('...'); SetLength(TKDT21DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT21DI64_Test.TestBuff) - 1 do for j := 0 to KDT21DI64_Axis - 1 do TKDT21DI64_Test.TestBuff[i][j] := i * KDT21DI64_Axis + j; {$IFDEF FPC} TKDT21DI64_Test.BuildKDTreeM(length(TKDT21DI64_Test.TestBuff), nil, @TKDT21DI64_Test.Test_BuildM); {$ELSE FPC} TKDT21DI64_Test.BuildKDTreeM(length(TKDT21DI64_Test.TestBuff), nil, TKDT21DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT21DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT21DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT21DI64_Test.TestBuff) - 1 do begin p := TKDT21DI64_Test.Search(TKDT21DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT21DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT21DI64_Test.TestBuff)); TKDT21DI64_Test.Search(TKDT21DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT21DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT21DI64_Test.Clear; { kMean test } TKDT21DI64_Test.BuildKDTreeWithCluster(TKDT21DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT21DI64_Test.Search(TKDT21DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT21DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT21DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT21DI64_Test); DoStatus(n); n := ''; end; function TKDT22DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DI64_Node; function SortCompare(const p1, p2: PKDT22DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT22DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT22DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT22DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT22DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT22DI64.GetData(const Index: NativeInt): PKDT22DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT22DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT22DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT22DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT22DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT22DI64.StoreBuffPtr: PKDT22DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT22DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT22DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT22DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT22DI64.BuildKDTreeWithCluster(const inBuff: TKDT22DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT22DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT22DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT22DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT22DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT22DI64.BuildKDTreeWithCluster(const inBuff: TKDT22DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT22DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildCall); var TempStoreBuff: TKDT22DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT22DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT22DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildMethod); var TempStoreBuff: TKDT22DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT22DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT22DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI64_BuildProc); var TempStoreBuff: TKDT22DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT22DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT22DI64.Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DI64_Node; var NearestNeighbour: PKDT22DI64_Node; function FindParentNode(const buffPtr: PKDT22DI64_Vec; NodePtr: PKDT22DI64_Node): PKDT22DI64_Node; var Next: PKDT22DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT22DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT22DI64_Node; const buffPtr: PKDT22DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT22DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT22DI64_Vec; const p1, p2: PKDT22DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT22DI64_Vec); var i, j: NativeInt; p, t: PKDT22DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT22DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT22DI64_Node(NearestNodes[0]); end; end; function TKDT22DI64.Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT22DI64.Search(const buff: TKDT22DI64_Vec; var SearchedDistanceMin: Double): PKDT22DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT22DI64.Search(const buff: TKDT22DI64_Vec): PKDT22DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT22DI64.SearchToken(const buff: TKDT22DI64_Vec): TPascalString; var p: PKDT22DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT22DI64.Search(const inBuff: TKDT22DI64_DynamicVecBuffer; var OutBuff: TKDT22DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT22DI64_DynamicVecBuffer; outBuffPtr: PKDT22DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT22DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT22DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT22DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT22DI64.Search(const inBuff: TKDT22DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT22DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT22DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT22DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT22DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT22DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT22DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT22DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT22DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT22DI64_Vec)) <> SizeOf(TKDT22DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT22DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT22DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT22DI64.PrintNodeTree(const NodePtr: PKDT22DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT22DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT22DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT22DI64.Vec(const s: SystemString): TKDT22DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT22DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT22DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT22DI64.Vec(const v: TKDT22DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT22DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT22DI64.Distance(const v1, v2: TKDT22DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT22DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT22DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT22DI64.Test; var TKDT22DI64_Test: TKDT22DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT22DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT22DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT22DI64_Test := TKDT22DI64.Create; n.Append('...'); SetLength(TKDT22DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT22DI64_Test.TestBuff) - 1 do for j := 0 to KDT22DI64_Axis - 1 do TKDT22DI64_Test.TestBuff[i][j] := i * KDT22DI64_Axis + j; {$IFDEF FPC} TKDT22DI64_Test.BuildKDTreeM(length(TKDT22DI64_Test.TestBuff), nil, @TKDT22DI64_Test.Test_BuildM); {$ELSE FPC} TKDT22DI64_Test.BuildKDTreeM(length(TKDT22DI64_Test.TestBuff), nil, TKDT22DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT22DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT22DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT22DI64_Test.TestBuff) - 1 do begin p := TKDT22DI64_Test.Search(TKDT22DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT22DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT22DI64_Test.TestBuff)); TKDT22DI64_Test.Search(TKDT22DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT22DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT22DI64_Test.Clear; { kMean test } TKDT22DI64_Test.BuildKDTreeWithCluster(TKDT22DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT22DI64_Test.Search(TKDT22DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT22DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT22DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT22DI64_Test); DoStatus(n); n := ''; end; function TKDT23DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DI64_Node; function SortCompare(const p1, p2: PKDT23DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT23DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT23DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT23DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT23DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT23DI64.GetData(const Index: NativeInt): PKDT23DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT23DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT23DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT23DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT23DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT23DI64.StoreBuffPtr: PKDT23DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT23DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT23DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT23DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT23DI64.BuildKDTreeWithCluster(const inBuff: TKDT23DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT23DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT23DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT23DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT23DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT23DI64.BuildKDTreeWithCluster(const inBuff: TKDT23DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT23DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildCall); var TempStoreBuff: TKDT23DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT23DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT23DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildMethod); var TempStoreBuff: TKDT23DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT23DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT23DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI64_BuildProc); var TempStoreBuff: TKDT23DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT23DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT23DI64.Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DI64_Node; var NearestNeighbour: PKDT23DI64_Node; function FindParentNode(const buffPtr: PKDT23DI64_Vec; NodePtr: PKDT23DI64_Node): PKDT23DI64_Node; var Next: PKDT23DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT23DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT23DI64_Node; const buffPtr: PKDT23DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT23DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT23DI64_Vec; const p1, p2: PKDT23DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT23DI64_Vec); var i, j: NativeInt; p, t: PKDT23DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT23DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT23DI64_Node(NearestNodes[0]); end; end; function TKDT23DI64.Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT23DI64.Search(const buff: TKDT23DI64_Vec; var SearchedDistanceMin: Double): PKDT23DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT23DI64.Search(const buff: TKDT23DI64_Vec): PKDT23DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT23DI64.SearchToken(const buff: TKDT23DI64_Vec): TPascalString; var p: PKDT23DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT23DI64.Search(const inBuff: TKDT23DI64_DynamicVecBuffer; var OutBuff: TKDT23DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT23DI64_DynamicVecBuffer; outBuffPtr: PKDT23DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT23DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT23DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT23DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT23DI64.Search(const inBuff: TKDT23DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT23DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT23DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT23DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT23DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT23DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT23DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT23DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT23DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT23DI64_Vec)) <> SizeOf(TKDT23DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT23DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT23DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT23DI64.PrintNodeTree(const NodePtr: PKDT23DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT23DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT23DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT23DI64.Vec(const s: SystemString): TKDT23DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT23DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT23DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT23DI64.Vec(const v: TKDT23DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT23DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT23DI64.Distance(const v1, v2: TKDT23DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT23DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT23DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT23DI64.Test; var TKDT23DI64_Test: TKDT23DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT23DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT23DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT23DI64_Test := TKDT23DI64.Create; n.Append('...'); SetLength(TKDT23DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT23DI64_Test.TestBuff) - 1 do for j := 0 to KDT23DI64_Axis - 1 do TKDT23DI64_Test.TestBuff[i][j] := i * KDT23DI64_Axis + j; {$IFDEF FPC} TKDT23DI64_Test.BuildKDTreeM(length(TKDT23DI64_Test.TestBuff), nil, @TKDT23DI64_Test.Test_BuildM); {$ELSE FPC} TKDT23DI64_Test.BuildKDTreeM(length(TKDT23DI64_Test.TestBuff), nil, TKDT23DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT23DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT23DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT23DI64_Test.TestBuff) - 1 do begin p := TKDT23DI64_Test.Search(TKDT23DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT23DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT23DI64_Test.TestBuff)); TKDT23DI64_Test.Search(TKDT23DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT23DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT23DI64_Test.Clear; { kMean test } TKDT23DI64_Test.BuildKDTreeWithCluster(TKDT23DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT23DI64_Test.Search(TKDT23DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT23DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT23DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT23DI64_Test); DoStatus(n); n := ''; end; function TKDT24DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DI64_Node; function SortCompare(const p1, p2: PKDT24DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT24DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT24DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT24DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT24DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT24DI64.GetData(const Index: NativeInt): PKDT24DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT24DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT24DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT24DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT24DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT24DI64.StoreBuffPtr: PKDT24DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT24DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT24DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT24DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT24DI64.BuildKDTreeWithCluster(const inBuff: TKDT24DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT24DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT24DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT24DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT24DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT24DI64.BuildKDTreeWithCluster(const inBuff: TKDT24DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT24DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildCall); var TempStoreBuff: TKDT24DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT24DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT24DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildMethod); var TempStoreBuff: TKDT24DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT24DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT24DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI64_BuildProc); var TempStoreBuff: TKDT24DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT24DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT24DI64.Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DI64_Node; var NearestNeighbour: PKDT24DI64_Node; function FindParentNode(const buffPtr: PKDT24DI64_Vec; NodePtr: PKDT24DI64_Node): PKDT24DI64_Node; var Next: PKDT24DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT24DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT24DI64_Node; const buffPtr: PKDT24DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT24DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT24DI64_Vec; const p1, p2: PKDT24DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT24DI64_Vec); var i, j: NativeInt; p, t: PKDT24DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT24DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT24DI64_Node(NearestNodes[0]); end; end; function TKDT24DI64.Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT24DI64.Search(const buff: TKDT24DI64_Vec; var SearchedDistanceMin: Double): PKDT24DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT24DI64.Search(const buff: TKDT24DI64_Vec): PKDT24DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT24DI64.SearchToken(const buff: TKDT24DI64_Vec): TPascalString; var p: PKDT24DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT24DI64.Search(const inBuff: TKDT24DI64_DynamicVecBuffer; var OutBuff: TKDT24DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT24DI64_DynamicVecBuffer; outBuffPtr: PKDT24DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT24DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT24DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT24DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT24DI64.Search(const inBuff: TKDT24DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT24DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT24DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT24DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT24DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT24DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT24DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT24DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT24DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT24DI64_Vec)) <> SizeOf(TKDT24DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT24DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT24DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT24DI64.PrintNodeTree(const NodePtr: PKDT24DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT24DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT24DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT24DI64.Vec(const s: SystemString): TKDT24DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT24DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT24DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT24DI64.Vec(const v: TKDT24DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT24DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT24DI64.Distance(const v1, v2: TKDT24DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT24DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT24DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT24DI64.Test; var TKDT24DI64_Test: TKDT24DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT24DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT24DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT24DI64_Test := TKDT24DI64.Create; n.Append('...'); SetLength(TKDT24DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT24DI64_Test.TestBuff) - 1 do for j := 0 to KDT24DI64_Axis - 1 do TKDT24DI64_Test.TestBuff[i][j] := i * KDT24DI64_Axis + j; {$IFDEF FPC} TKDT24DI64_Test.BuildKDTreeM(length(TKDT24DI64_Test.TestBuff), nil, @TKDT24DI64_Test.Test_BuildM); {$ELSE FPC} TKDT24DI64_Test.BuildKDTreeM(length(TKDT24DI64_Test.TestBuff), nil, TKDT24DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT24DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT24DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT24DI64_Test.TestBuff) - 1 do begin p := TKDT24DI64_Test.Search(TKDT24DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT24DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT24DI64_Test.TestBuff)); TKDT24DI64_Test.Search(TKDT24DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT24DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT24DI64_Test.Clear; { kMean test } TKDT24DI64_Test.BuildKDTreeWithCluster(TKDT24DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT24DI64_Test.Search(TKDT24DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT24DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT24DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT24DI64_Test); DoStatus(n); n := ''; end; function TKDT48DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DI64_Node; function SortCompare(const p1, p2: PKDT48DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT48DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT48DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT48DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT48DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT48DI64.GetData(const Index: NativeInt): PKDT48DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT48DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT48DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT48DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT48DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT48DI64.StoreBuffPtr: PKDT48DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT48DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT48DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT48DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT48DI64.BuildKDTreeWithCluster(const inBuff: TKDT48DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT48DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT48DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT48DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT48DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT48DI64.BuildKDTreeWithCluster(const inBuff: TKDT48DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT48DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildCall); var TempStoreBuff: TKDT48DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT48DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT48DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildMethod); var TempStoreBuff: TKDT48DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT48DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT48DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI64_BuildProc); var TempStoreBuff: TKDT48DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT48DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT48DI64.Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DI64_Node; var NearestNeighbour: PKDT48DI64_Node; function FindParentNode(const buffPtr: PKDT48DI64_Vec; NodePtr: PKDT48DI64_Node): PKDT48DI64_Node; var Next: PKDT48DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT48DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT48DI64_Node; const buffPtr: PKDT48DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT48DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT48DI64_Vec; const p1, p2: PKDT48DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT48DI64_Vec); var i, j: NativeInt; p, t: PKDT48DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT48DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT48DI64_Node(NearestNodes[0]); end; end; function TKDT48DI64.Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT48DI64.Search(const buff: TKDT48DI64_Vec; var SearchedDistanceMin: Double): PKDT48DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT48DI64.Search(const buff: TKDT48DI64_Vec): PKDT48DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT48DI64.SearchToken(const buff: TKDT48DI64_Vec): TPascalString; var p: PKDT48DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT48DI64.Search(const inBuff: TKDT48DI64_DynamicVecBuffer; var OutBuff: TKDT48DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT48DI64_DynamicVecBuffer; outBuffPtr: PKDT48DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT48DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT48DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT48DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT48DI64.Search(const inBuff: TKDT48DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT48DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT48DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT48DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT48DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT48DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT48DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT48DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT48DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT48DI64_Vec)) <> SizeOf(TKDT48DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT48DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT48DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT48DI64.PrintNodeTree(const NodePtr: PKDT48DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT48DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT48DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT48DI64.Vec(const s: SystemString): TKDT48DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT48DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT48DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT48DI64.Vec(const v: TKDT48DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT48DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT48DI64.Distance(const v1, v2: TKDT48DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT48DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT48DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT48DI64.Test; var TKDT48DI64_Test: TKDT48DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT48DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT48DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT48DI64_Test := TKDT48DI64.Create; n.Append('...'); SetLength(TKDT48DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT48DI64_Test.TestBuff) - 1 do for j := 0 to KDT48DI64_Axis - 1 do TKDT48DI64_Test.TestBuff[i][j] := i * KDT48DI64_Axis + j; {$IFDEF FPC} TKDT48DI64_Test.BuildKDTreeM(length(TKDT48DI64_Test.TestBuff), nil, @TKDT48DI64_Test.Test_BuildM); {$ELSE FPC} TKDT48DI64_Test.BuildKDTreeM(length(TKDT48DI64_Test.TestBuff), nil, TKDT48DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT48DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT48DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT48DI64_Test.TestBuff) - 1 do begin p := TKDT48DI64_Test.Search(TKDT48DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT48DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT48DI64_Test.TestBuff)); TKDT48DI64_Test.Search(TKDT48DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT48DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT48DI64_Test.Clear; { kMean test } TKDT48DI64_Test.BuildKDTreeWithCluster(TKDT48DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT48DI64_Test.Search(TKDT48DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT48DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT48DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT48DI64_Test); DoStatus(n); n := ''; end; function TKDT52DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DI64_Node; function SortCompare(const p1, p2: PKDT52DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT52DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT52DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT52DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT52DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT52DI64.GetData(const Index: NativeInt): PKDT52DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT52DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT52DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT52DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT52DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT52DI64.StoreBuffPtr: PKDT52DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT52DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT52DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT52DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT52DI64.BuildKDTreeWithCluster(const inBuff: TKDT52DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT52DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT52DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT52DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT52DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT52DI64.BuildKDTreeWithCluster(const inBuff: TKDT52DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT52DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildCall); var TempStoreBuff: TKDT52DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT52DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT52DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildMethod); var TempStoreBuff: TKDT52DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT52DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT52DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI64_BuildProc); var TempStoreBuff: TKDT52DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT52DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT52DI64.Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DI64_Node; var NearestNeighbour: PKDT52DI64_Node; function FindParentNode(const buffPtr: PKDT52DI64_Vec; NodePtr: PKDT52DI64_Node): PKDT52DI64_Node; var Next: PKDT52DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT52DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT52DI64_Node; const buffPtr: PKDT52DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT52DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT52DI64_Vec; const p1, p2: PKDT52DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT52DI64_Vec); var i, j: NativeInt; p, t: PKDT52DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT52DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT52DI64_Node(NearestNodes[0]); end; end; function TKDT52DI64.Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT52DI64.Search(const buff: TKDT52DI64_Vec; var SearchedDistanceMin: Double): PKDT52DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT52DI64.Search(const buff: TKDT52DI64_Vec): PKDT52DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT52DI64.SearchToken(const buff: TKDT52DI64_Vec): TPascalString; var p: PKDT52DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT52DI64.Search(const inBuff: TKDT52DI64_DynamicVecBuffer; var OutBuff: TKDT52DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT52DI64_DynamicVecBuffer; outBuffPtr: PKDT52DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT52DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT52DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT52DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT52DI64.Search(const inBuff: TKDT52DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT52DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT52DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT52DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT52DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT52DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT52DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT52DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT52DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT52DI64_Vec)) <> SizeOf(TKDT52DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT52DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT52DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT52DI64.PrintNodeTree(const NodePtr: PKDT52DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT52DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT52DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT52DI64.Vec(const s: SystemString): TKDT52DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT52DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT52DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT52DI64.Vec(const v: TKDT52DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT52DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT52DI64.Distance(const v1, v2: TKDT52DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT52DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT52DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT52DI64.Test; var TKDT52DI64_Test: TKDT52DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT52DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT52DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT52DI64_Test := TKDT52DI64.Create; n.Append('...'); SetLength(TKDT52DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT52DI64_Test.TestBuff) - 1 do for j := 0 to KDT52DI64_Axis - 1 do TKDT52DI64_Test.TestBuff[i][j] := i * KDT52DI64_Axis + j; {$IFDEF FPC} TKDT52DI64_Test.BuildKDTreeM(length(TKDT52DI64_Test.TestBuff), nil, @TKDT52DI64_Test.Test_BuildM); {$ELSE FPC} TKDT52DI64_Test.BuildKDTreeM(length(TKDT52DI64_Test.TestBuff), nil, TKDT52DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT52DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT52DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT52DI64_Test.TestBuff) - 1 do begin p := TKDT52DI64_Test.Search(TKDT52DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT52DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT52DI64_Test.TestBuff)); TKDT52DI64_Test.Search(TKDT52DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT52DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT52DI64_Test.Clear; { kMean test } TKDT52DI64_Test.BuildKDTreeWithCluster(TKDT52DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT52DI64_Test.Search(TKDT52DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT52DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT52DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT52DI64_Test); DoStatus(n); n := ''; end; function TKDT64DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DI64_Node; function SortCompare(const p1, p2: PKDT64DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT64DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT64DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT64DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT64DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT64DI64.GetData(const Index: NativeInt): PKDT64DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT64DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT64DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT64DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT64DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT64DI64.StoreBuffPtr: PKDT64DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT64DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT64DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT64DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT64DI64.BuildKDTreeWithCluster(const inBuff: TKDT64DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT64DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT64DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT64DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT64DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT64DI64.BuildKDTreeWithCluster(const inBuff: TKDT64DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT64DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildCall); var TempStoreBuff: TKDT64DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT64DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT64DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildMethod); var TempStoreBuff: TKDT64DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT64DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT64DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI64_BuildProc); var TempStoreBuff: TKDT64DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT64DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT64DI64.Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DI64_Node; var NearestNeighbour: PKDT64DI64_Node; function FindParentNode(const buffPtr: PKDT64DI64_Vec; NodePtr: PKDT64DI64_Node): PKDT64DI64_Node; var Next: PKDT64DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT64DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT64DI64_Node; const buffPtr: PKDT64DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT64DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT64DI64_Vec; const p1, p2: PKDT64DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT64DI64_Vec); var i, j: NativeInt; p, t: PKDT64DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT64DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT64DI64_Node(NearestNodes[0]); end; end; function TKDT64DI64.Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT64DI64.Search(const buff: TKDT64DI64_Vec; var SearchedDistanceMin: Double): PKDT64DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT64DI64.Search(const buff: TKDT64DI64_Vec): PKDT64DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT64DI64.SearchToken(const buff: TKDT64DI64_Vec): TPascalString; var p: PKDT64DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT64DI64.Search(const inBuff: TKDT64DI64_DynamicVecBuffer; var OutBuff: TKDT64DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT64DI64_DynamicVecBuffer; outBuffPtr: PKDT64DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT64DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT64DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT64DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT64DI64.Search(const inBuff: TKDT64DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT64DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT64DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT64DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT64DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT64DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT64DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT64DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT64DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT64DI64_Vec)) <> SizeOf(TKDT64DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT64DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT64DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT64DI64.PrintNodeTree(const NodePtr: PKDT64DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT64DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT64DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT64DI64.Vec(const s: SystemString): TKDT64DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT64DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT64DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT64DI64.Vec(const v: TKDT64DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT64DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT64DI64.Distance(const v1, v2: TKDT64DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT64DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT64DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT64DI64.Test; var TKDT64DI64_Test: TKDT64DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT64DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT64DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT64DI64_Test := TKDT64DI64.Create; n.Append('...'); SetLength(TKDT64DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT64DI64_Test.TestBuff) - 1 do for j := 0 to KDT64DI64_Axis - 1 do TKDT64DI64_Test.TestBuff[i][j] := i * KDT64DI64_Axis + j; {$IFDEF FPC} TKDT64DI64_Test.BuildKDTreeM(length(TKDT64DI64_Test.TestBuff), nil, @TKDT64DI64_Test.Test_BuildM); {$ELSE FPC} TKDT64DI64_Test.BuildKDTreeM(length(TKDT64DI64_Test.TestBuff), nil, TKDT64DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT64DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT64DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT64DI64_Test.TestBuff) - 1 do begin p := TKDT64DI64_Test.Search(TKDT64DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT64DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT64DI64_Test.TestBuff)); TKDT64DI64_Test.Search(TKDT64DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT64DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT64DI64_Test.Clear; { kMean test } TKDT64DI64_Test.BuildKDTreeWithCluster(TKDT64DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT64DI64_Test.Search(TKDT64DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT64DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT64DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT64DI64_Test); DoStatus(n); n := ''; end; function TKDT96DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DI64_Node; function SortCompare(const p1, p2: PKDT96DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT96DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT96DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT96DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT96DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT96DI64.GetData(const Index: NativeInt): PKDT96DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT96DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT96DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT96DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT96DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT96DI64.StoreBuffPtr: PKDT96DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT96DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT96DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT96DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT96DI64.BuildKDTreeWithCluster(const inBuff: TKDT96DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT96DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT96DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT96DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT96DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT96DI64.BuildKDTreeWithCluster(const inBuff: TKDT96DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT96DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildCall); var TempStoreBuff: TKDT96DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT96DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT96DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildMethod); var TempStoreBuff: TKDT96DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT96DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT96DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI64_BuildProc); var TempStoreBuff: TKDT96DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT96DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT96DI64.Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DI64_Node; var NearestNeighbour: PKDT96DI64_Node; function FindParentNode(const buffPtr: PKDT96DI64_Vec; NodePtr: PKDT96DI64_Node): PKDT96DI64_Node; var Next: PKDT96DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT96DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT96DI64_Node; const buffPtr: PKDT96DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT96DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT96DI64_Vec; const p1, p2: PKDT96DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT96DI64_Vec); var i, j: NativeInt; p, t: PKDT96DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT96DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT96DI64_Node(NearestNodes[0]); end; end; function TKDT96DI64.Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT96DI64.Search(const buff: TKDT96DI64_Vec; var SearchedDistanceMin: Double): PKDT96DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT96DI64.Search(const buff: TKDT96DI64_Vec): PKDT96DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT96DI64.SearchToken(const buff: TKDT96DI64_Vec): TPascalString; var p: PKDT96DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT96DI64.Search(const inBuff: TKDT96DI64_DynamicVecBuffer; var OutBuff: TKDT96DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT96DI64_DynamicVecBuffer; outBuffPtr: PKDT96DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT96DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT96DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT96DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT96DI64.Search(const inBuff: TKDT96DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT96DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT96DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT96DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT96DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT96DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT96DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT96DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT96DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT96DI64_Vec)) <> SizeOf(TKDT96DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT96DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT96DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT96DI64.PrintNodeTree(const NodePtr: PKDT96DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT96DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT96DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT96DI64.Vec(const s: SystemString): TKDT96DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT96DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT96DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT96DI64.Vec(const v: TKDT96DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT96DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT96DI64.Distance(const v1, v2: TKDT96DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT96DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT96DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT96DI64.Test; var TKDT96DI64_Test: TKDT96DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT96DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT96DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT96DI64_Test := TKDT96DI64.Create; n.Append('...'); SetLength(TKDT96DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT96DI64_Test.TestBuff) - 1 do for j := 0 to KDT96DI64_Axis - 1 do TKDT96DI64_Test.TestBuff[i][j] := i * KDT96DI64_Axis + j; {$IFDEF FPC} TKDT96DI64_Test.BuildKDTreeM(length(TKDT96DI64_Test.TestBuff), nil, @TKDT96DI64_Test.Test_BuildM); {$ELSE FPC} TKDT96DI64_Test.BuildKDTreeM(length(TKDT96DI64_Test.TestBuff), nil, TKDT96DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT96DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT96DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT96DI64_Test.TestBuff) - 1 do begin p := TKDT96DI64_Test.Search(TKDT96DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT96DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT96DI64_Test.TestBuff)); TKDT96DI64_Test.Search(TKDT96DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT96DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT96DI64_Test.Clear; { kMean test } TKDT96DI64_Test.BuildKDTreeWithCluster(TKDT96DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT96DI64_Test.Search(TKDT96DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT96DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT96DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT96DI64_Test); DoStatus(n); n := ''; end; function TKDT128DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DI64_Node; function SortCompare(const p1, p2: PKDT128DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT128DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT128DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT128DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT128DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT128DI64.GetData(const Index: NativeInt): PKDT128DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT128DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT128DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT128DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT128DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT128DI64.StoreBuffPtr: PKDT128DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT128DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT128DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT128DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT128DI64.BuildKDTreeWithCluster(const inBuff: TKDT128DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT128DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT128DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT128DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT128DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT128DI64.BuildKDTreeWithCluster(const inBuff: TKDT128DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT128DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildCall); var TempStoreBuff: TKDT128DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT128DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT128DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildMethod); var TempStoreBuff: TKDT128DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT128DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT128DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI64_BuildProc); var TempStoreBuff: TKDT128DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT128DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT128DI64.Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DI64_Node; var NearestNeighbour: PKDT128DI64_Node; function FindParentNode(const buffPtr: PKDT128DI64_Vec; NodePtr: PKDT128DI64_Node): PKDT128DI64_Node; var Next: PKDT128DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT128DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT128DI64_Node; const buffPtr: PKDT128DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT128DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT128DI64_Vec; const p1, p2: PKDT128DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT128DI64_Vec); var i, j: NativeInt; p, t: PKDT128DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT128DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT128DI64_Node(NearestNodes[0]); end; end; function TKDT128DI64.Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT128DI64.Search(const buff: TKDT128DI64_Vec; var SearchedDistanceMin: Double): PKDT128DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT128DI64.Search(const buff: TKDT128DI64_Vec): PKDT128DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT128DI64.SearchToken(const buff: TKDT128DI64_Vec): TPascalString; var p: PKDT128DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT128DI64.Search(const inBuff: TKDT128DI64_DynamicVecBuffer; var OutBuff: TKDT128DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT128DI64_DynamicVecBuffer; outBuffPtr: PKDT128DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT128DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT128DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT128DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT128DI64.Search(const inBuff: TKDT128DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT128DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT128DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT128DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT128DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT128DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT128DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT128DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT128DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT128DI64_Vec)) <> SizeOf(TKDT128DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT128DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT128DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT128DI64.PrintNodeTree(const NodePtr: PKDT128DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT128DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT128DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT128DI64.Vec(const s: SystemString): TKDT128DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT128DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT128DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT128DI64.Vec(const v: TKDT128DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT128DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT128DI64.Distance(const v1, v2: TKDT128DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT128DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT128DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT128DI64.Test; var TKDT128DI64_Test: TKDT128DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT128DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT128DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT128DI64_Test := TKDT128DI64.Create; n.Append('...'); SetLength(TKDT128DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT128DI64_Test.TestBuff) - 1 do for j := 0 to KDT128DI64_Axis - 1 do TKDT128DI64_Test.TestBuff[i][j] := i * KDT128DI64_Axis + j; {$IFDEF FPC} TKDT128DI64_Test.BuildKDTreeM(length(TKDT128DI64_Test.TestBuff), nil, @TKDT128DI64_Test.Test_BuildM); {$ELSE FPC} TKDT128DI64_Test.BuildKDTreeM(length(TKDT128DI64_Test.TestBuff), nil, TKDT128DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT128DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT128DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT128DI64_Test.TestBuff) - 1 do begin p := TKDT128DI64_Test.Search(TKDT128DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT128DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT128DI64_Test.TestBuff)); TKDT128DI64_Test.Search(TKDT128DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT128DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT128DI64_Test.Clear; { kMean test } TKDT128DI64_Test.BuildKDTreeWithCluster(TKDT128DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT128DI64_Test.Search(TKDT128DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT128DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT128DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT128DI64_Test); DoStatus(n); n := ''; end; function TKDT156DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DI64_Node; function SortCompare(const p1, p2: PKDT156DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT156DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT156DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT156DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT156DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT156DI64.GetData(const Index: NativeInt): PKDT156DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT156DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT156DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT156DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT156DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT156DI64.StoreBuffPtr: PKDT156DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT156DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT156DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT156DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT156DI64.BuildKDTreeWithCluster(const inBuff: TKDT156DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT156DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT156DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT156DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT156DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT156DI64.BuildKDTreeWithCluster(const inBuff: TKDT156DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT156DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildCall); var TempStoreBuff: TKDT156DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT156DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT156DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildMethod); var TempStoreBuff: TKDT156DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT156DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT156DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI64_BuildProc); var TempStoreBuff: TKDT156DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT156DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT156DI64.Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DI64_Node; var NearestNeighbour: PKDT156DI64_Node; function FindParentNode(const buffPtr: PKDT156DI64_Vec; NodePtr: PKDT156DI64_Node): PKDT156DI64_Node; var Next: PKDT156DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT156DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT156DI64_Node; const buffPtr: PKDT156DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT156DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT156DI64_Vec; const p1, p2: PKDT156DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT156DI64_Vec); var i, j: NativeInt; p, t: PKDT156DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT156DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT156DI64_Node(NearestNodes[0]); end; end; function TKDT156DI64.Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT156DI64.Search(const buff: TKDT156DI64_Vec; var SearchedDistanceMin: Double): PKDT156DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT156DI64.Search(const buff: TKDT156DI64_Vec): PKDT156DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT156DI64.SearchToken(const buff: TKDT156DI64_Vec): TPascalString; var p: PKDT156DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT156DI64.Search(const inBuff: TKDT156DI64_DynamicVecBuffer; var OutBuff: TKDT156DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT156DI64_DynamicVecBuffer; outBuffPtr: PKDT156DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT156DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT156DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT156DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT156DI64.Search(const inBuff: TKDT156DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT156DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT156DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT156DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT156DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT156DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT156DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT156DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT156DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT156DI64_Vec)) <> SizeOf(TKDT156DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT156DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT156DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT156DI64.PrintNodeTree(const NodePtr: PKDT156DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT156DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT156DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT156DI64.Vec(const s: SystemString): TKDT156DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT156DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT156DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT156DI64.Vec(const v: TKDT156DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT156DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT156DI64.Distance(const v1, v2: TKDT156DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT156DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT156DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT156DI64.Test; var TKDT156DI64_Test: TKDT156DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT156DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT156DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT156DI64_Test := TKDT156DI64.Create; n.Append('...'); SetLength(TKDT156DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT156DI64_Test.TestBuff) - 1 do for j := 0 to KDT156DI64_Axis - 1 do TKDT156DI64_Test.TestBuff[i][j] := i * KDT156DI64_Axis + j; {$IFDEF FPC} TKDT156DI64_Test.BuildKDTreeM(length(TKDT156DI64_Test.TestBuff), nil, @TKDT156DI64_Test.Test_BuildM); {$ELSE FPC} TKDT156DI64_Test.BuildKDTreeM(length(TKDT156DI64_Test.TestBuff), nil, TKDT156DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT156DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT156DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT156DI64_Test.TestBuff) - 1 do begin p := TKDT156DI64_Test.Search(TKDT156DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT156DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT156DI64_Test.TestBuff)); TKDT156DI64_Test.Search(TKDT156DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT156DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT156DI64_Test.Clear; { kMean test } TKDT156DI64_Test.BuildKDTreeWithCluster(TKDT156DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT156DI64_Test.Search(TKDT156DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT156DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT156DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT156DI64_Test); DoStatus(n); n := ''; end; function TKDT192DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DI64_Node; function SortCompare(const p1, p2: PKDT192DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT192DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT192DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT192DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT192DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT192DI64.GetData(const Index: NativeInt): PKDT192DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT192DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT192DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT192DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT192DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT192DI64.StoreBuffPtr: PKDT192DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT192DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT192DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT192DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT192DI64.BuildKDTreeWithCluster(const inBuff: TKDT192DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT192DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT192DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT192DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT192DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT192DI64.BuildKDTreeWithCluster(const inBuff: TKDT192DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT192DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildCall); var TempStoreBuff: TKDT192DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT192DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT192DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildMethod); var TempStoreBuff: TKDT192DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT192DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT192DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI64_BuildProc); var TempStoreBuff: TKDT192DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT192DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT192DI64.Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DI64_Node; var NearestNeighbour: PKDT192DI64_Node; function FindParentNode(const buffPtr: PKDT192DI64_Vec; NodePtr: PKDT192DI64_Node): PKDT192DI64_Node; var Next: PKDT192DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT192DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT192DI64_Node; const buffPtr: PKDT192DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT192DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT192DI64_Vec; const p1, p2: PKDT192DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT192DI64_Vec); var i, j: NativeInt; p, t: PKDT192DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT192DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT192DI64_Node(NearestNodes[0]); end; end; function TKDT192DI64.Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT192DI64.Search(const buff: TKDT192DI64_Vec; var SearchedDistanceMin: Double): PKDT192DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT192DI64.Search(const buff: TKDT192DI64_Vec): PKDT192DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT192DI64.SearchToken(const buff: TKDT192DI64_Vec): TPascalString; var p: PKDT192DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT192DI64.Search(const inBuff: TKDT192DI64_DynamicVecBuffer; var OutBuff: TKDT192DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT192DI64_DynamicVecBuffer; outBuffPtr: PKDT192DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT192DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT192DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT192DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT192DI64.Search(const inBuff: TKDT192DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT192DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT192DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT192DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT192DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT192DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT192DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT192DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT192DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT192DI64_Vec)) <> SizeOf(TKDT192DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT192DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT192DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT192DI64.PrintNodeTree(const NodePtr: PKDT192DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT192DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT192DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT192DI64.Vec(const s: SystemString): TKDT192DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT192DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT192DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT192DI64.Vec(const v: TKDT192DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT192DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT192DI64.Distance(const v1, v2: TKDT192DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT192DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT192DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT192DI64.Test; var TKDT192DI64_Test: TKDT192DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT192DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT192DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT192DI64_Test := TKDT192DI64.Create; n.Append('...'); SetLength(TKDT192DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT192DI64_Test.TestBuff) - 1 do for j := 0 to KDT192DI64_Axis - 1 do TKDT192DI64_Test.TestBuff[i][j] := i * KDT192DI64_Axis + j; {$IFDEF FPC} TKDT192DI64_Test.BuildKDTreeM(length(TKDT192DI64_Test.TestBuff), nil, @TKDT192DI64_Test.Test_BuildM); {$ELSE FPC} TKDT192DI64_Test.BuildKDTreeM(length(TKDT192DI64_Test.TestBuff), nil, TKDT192DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT192DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT192DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT192DI64_Test.TestBuff) - 1 do begin p := TKDT192DI64_Test.Search(TKDT192DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT192DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT192DI64_Test.TestBuff)); TKDT192DI64_Test.Search(TKDT192DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT192DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT192DI64_Test.Clear; { kMean test } TKDT192DI64_Test.BuildKDTreeWithCluster(TKDT192DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT192DI64_Test.Search(TKDT192DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT192DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT192DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT192DI64_Test); DoStatus(n); n := ''; end; function TKDT256DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DI64_Node; function SortCompare(const p1, p2: PKDT256DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT256DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT256DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT256DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT256DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT256DI64.GetData(const Index: NativeInt): PKDT256DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT256DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT256DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT256DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT256DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT256DI64.StoreBuffPtr: PKDT256DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT256DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT256DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT256DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT256DI64.BuildKDTreeWithCluster(const inBuff: TKDT256DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT256DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT256DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT256DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT256DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT256DI64.BuildKDTreeWithCluster(const inBuff: TKDT256DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT256DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildCall); var TempStoreBuff: TKDT256DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT256DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT256DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildMethod); var TempStoreBuff: TKDT256DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT256DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT256DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI64_BuildProc); var TempStoreBuff: TKDT256DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT256DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT256DI64.Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DI64_Node; var NearestNeighbour: PKDT256DI64_Node; function FindParentNode(const buffPtr: PKDT256DI64_Vec; NodePtr: PKDT256DI64_Node): PKDT256DI64_Node; var Next: PKDT256DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT256DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT256DI64_Node; const buffPtr: PKDT256DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT256DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT256DI64_Vec; const p1, p2: PKDT256DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT256DI64_Vec); var i, j: NativeInt; p, t: PKDT256DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT256DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT256DI64_Node(NearestNodes[0]); end; end; function TKDT256DI64.Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT256DI64.Search(const buff: TKDT256DI64_Vec; var SearchedDistanceMin: Double): PKDT256DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT256DI64.Search(const buff: TKDT256DI64_Vec): PKDT256DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT256DI64.SearchToken(const buff: TKDT256DI64_Vec): TPascalString; var p: PKDT256DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT256DI64.Search(const inBuff: TKDT256DI64_DynamicVecBuffer; var OutBuff: TKDT256DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT256DI64_DynamicVecBuffer; outBuffPtr: PKDT256DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT256DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT256DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT256DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT256DI64.Search(const inBuff: TKDT256DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT256DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT256DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT256DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT256DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT256DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT256DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT256DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT256DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT256DI64_Vec)) <> SizeOf(TKDT256DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT256DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT256DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT256DI64.PrintNodeTree(const NodePtr: PKDT256DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT256DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT256DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT256DI64.Vec(const s: SystemString): TKDT256DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT256DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT256DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT256DI64.Vec(const v: TKDT256DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT256DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT256DI64.Distance(const v1, v2: TKDT256DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT256DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT256DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT256DI64.Test; var TKDT256DI64_Test: TKDT256DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT256DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT256DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT256DI64_Test := TKDT256DI64.Create; n.Append('...'); SetLength(TKDT256DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT256DI64_Test.TestBuff) - 1 do for j := 0 to KDT256DI64_Axis - 1 do TKDT256DI64_Test.TestBuff[i][j] := i * KDT256DI64_Axis + j; {$IFDEF FPC} TKDT256DI64_Test.BuildKDTreeM(length(TKDT256DI64_Test.TestBuff), nil, @TKDT256DI64_Test.Test_BuildM); {$ELSE FPC} TKDT256DI64_Test.BuildKDTreeM(length(TKDT256DI64_Test.TestBuff), nil, TKDT256DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT256DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT256DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT256DI64_Test.TestBuff) - 1 do begin p := TKDT256DI64_Test.Search(TKDT256DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT256DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT256DI64_Test.TestBuff)); TKDT256DI64_Test.Search(TKDT256DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT256DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT256DI64_Test.Clear; { kMean test } TKDT256DI64_Test.BuildKDTreeWithCluster(TKDT256DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT256DI64_Test.Search(TKDT256DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT256DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT256DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT256DI64_Test); DoStatus(n); n := ''; end; function TKDT384DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DI64_Node; function SortCompare(const p1, p2: PKDT384DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT384DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT384DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT384DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT384DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT384DI64.GetData(const Index: NativeInt): PKDT384DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT384DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT384DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT384DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT384DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT384DI64.StoreBuffPtr: PKDT384DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT384DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT384DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT384DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT384DI64.BuildKDTreeWithCluster(const inBuff: TKDT384DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT384DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT384DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT384DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT384DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT384DI64.BuildKDTreeWithCluster(const inBuff: TKDT384DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT384DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildCall); var TempStoreBuff: TKDT384DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT384DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT384DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildMethod); var TempStoreBuff: TKDT384DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT384DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT384DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI64_BuildProc); var TempStoreBuff: TKDT384DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT384DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT384DI64.Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DI64_Node; var NearestNeighbour: PKDT384DI64_Node; function FindParentNode(const buffPtr: PKDT384DI64_Vec; NodePtr: PKDT384DI64_Node): PKDT384DI64_Node; var Next: PKDT384DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT384DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT384DI64_Node; const buffPtr: PKDT384DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT384DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT384DI64_Vec; const p1, p2: PKDT384DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT384DI64_Vec); var i, j: NativeInt; p, t: PKDT384DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT384DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT384DI64_Node(NearestNodes[0]); end; end; function TKDT384DI64.Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT384DI64.Search(const buff: TKDT384DI64_Vec; var SearchedDistanceMin: Double): PKDT384DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT384DI64.Search(const buff: TKDT384DI64_Vec): PKDT384DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT384DI64.SearchToken(const buff: TKDT384DI64_Vec): TPascalString; var p: PKDT384DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT384DI64.Search(const inBuff: TKDT384DI64_DynamicVecBuffer; var OutBuff: TKDT384DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT384DI64_DynamicVecBuffer; outBuffPtr: PKDT384DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT384DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT384DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT384DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT384DI64.Search(const inBuff: TKDT384DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT384DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT384DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT384DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT384DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT384DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT384DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT384DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT384DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT384DI64_Vec)) <> SizeOf(TKDT384DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT384DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT384DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT384DI64.PrintNodeTree(const NodePtr: PKDT384DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT384DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT384DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT384DI64.Vec(const s: SystemString): TKDT384DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT384DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT384DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT384DI64.Vec(const v: TKDT384DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT384DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT384DI64.Distance(const v1, v2: TKDT384DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT384DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT384DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT384DI64.Test; var TKDT384DI64_Test: TKDT384DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT384DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT384DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT384DI64_Test := TKDT384DI64.Create; n.Append('...'); SetLength(TKDT384DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT384DI64_Test.TestBuff) - 1 do for j := 0 to KDT384DI64_Axis - 1 do TKDT384DI64_Test.TestBuff[i][j] := i * KDT384DI64_Axis + j; {$IFDEF FPC} TKDT384DI64_Test.BuildKDTreeM(length(TKDT384DI64_Test.TestBuff), nil, @TKDT384DI64_Test.Test_BuildM); {$ELSE FPC} TKDT384DI64_Test.BuildKDTreeM(length(TKDT384DI64_Test.TestBuff), nil, TKDT384DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT384DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT384DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT384DI64_Test.TestBuff) - 1 do begin p := TKDT384DI64_Test.Search(TKDT384DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT384DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT384DI64_Test.TestBuff)); TKDT384DI64_Test.Search(TKDT384DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT384DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT384DI64_Test.Clear; { kMean test } TKDT384DI64_Test.BuildKDTreeWithCluster(TKDT384DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT384DI64_Test.Search(TKDT384DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT384DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT384DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT384DI64_Test); DoStatus(n); n := ''; end; function TKDT512DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DI64_Node; function SortCompare(const p1, p2: PKDT512DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT512DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT512DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT512DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT512DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT512DI64.GetData(const Index: NativeInt): PKDT512DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT512DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT512DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT512DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT512DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT512DI64.StoreBuffPtr: PKDT512DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT512DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT512DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT512DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT512DI64.BuildKDTreeWithCluster(const inBuff: TKDT512DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT512DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT512DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT512DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT512DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT512DI64.BuildKDTreeWithCluster(const inBuff: TKDT512DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT512DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildCall); var TempStoreBuff: TKDT512DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT512DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT512DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildMethod); var TempStoreBuff: TKDT512DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT512DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT512DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI64_BuildProc); var TempStoreBuff: TKDT512DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT512DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT512DI64.Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DI64_Node; var NearestNeighbour: PKDT512DI64_Node; function FindParentNode(const buffPtr: PKDT512DI64_Vec; NodePtr: PKDT512DI64_Node): PKDT512DI64_Node; var Next: PKDT512DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT512DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT512DI64_Node; const buffPtr: PKDT512DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT512DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT512DI64_Vec; const p1, p2: PKDT512DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT512DI64_Vec); var i, j: NativeInt; p, t: PKDT512DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT512DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT512DI64_Node(NearestNodes[0]); end; end; function TKDT512DI64.Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT512DI64.Search(const buff: TKDT512DI64_Vec; var SearchedDistanceMin: Double): PKDT512DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT512DI64.Search(const buff: TKDT512DI64_Vec): PKDT512DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT512DI64.SearchToken(const buff: TKDT512DI64_Vec): TPascalString; var p: PKDT512DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT512DI64.Search(const inBuff: TKDT512DI64_DynamicVecBuffer; var OutBuff: TKDT512DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT512DI64_DynamicVecBuffer; outBuffPtr: PKDT512DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT512DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT512DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT512DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT512DI64.Search(const inBuff: TKDT512DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT512DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT512DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT512DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT512DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT512DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT512DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT512DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT512DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT512DI64_Vec)) <> SizeOf(TKDT512DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT512DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT512DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT512DI64.PrintNodeTree(const NodePtr: PKDT512DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT512DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT512DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT512DI64.Vec(const s: SystemString): TKDT512DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT512DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT512DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT512DI64.Vec(const v: TKDT512DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT512DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT512DI64.Distance(const v1, v2: TKDT512DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT512DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT512DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT512DI64.Test; var TKDT512DI64_Test: TKDT512DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT512DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT512DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT512DI64_Test := TKDT512DI64.Create; n.Append('...'); SetLength(TKDT512DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT512DI64_Test.TestBuff) - 1 do for j := 0 to KDT512DI64_Axis - 1 do TKDT512DI64_Test.TestBuff[i][j] := i * KDT512DI64_Axis + j; {$IFDEF FPC} TKDT512DI64_Test.BuildKDTreeM(length(TKDT512DI64_Test.TestBuff), nil, @TKDT512DI64_Test.Test_BuildM); {$ELSE FPC} TKDT512DI64_Test.BuildKDTreeM(length(TKDT512DI64_Test.TestBuff), nil, TKDT512DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT512DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT512DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT512DI64_Test.TestBuff) - 1 do begin p := TKDT512DI64_Test.Search(TKDT512DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT512DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT512DI64_Test.TestBuff)); TKDT512DI64_Test.Search(TKDT512DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT512DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT512DI64_Test.Clear; { kMean test } TKDT512DI64_Test.BuildKDTreeWithCluster(TKDT512DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT512DI64_Test.Search(TKDT512DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT512DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT512DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT512DI64_Test); DoStatus(n); n := ''; end; function TKDT800DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DI64_Node; function SortCompare(const p1, p2: PKDT800DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT800DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT800DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT800DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT800DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT800DI64.GetData(const Index: NativeInt): PKDT800DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT800DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT800DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT800DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT800DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT800DI64.StoreBuffPtr: PKDT800DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT800DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT800DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT800DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT800DI64.BuildKDTreeWithCluster(const inBuff: TKDT800DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT800DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT800DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT800DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT800DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT800DI64.BuildKDTreeWithCluster(const inBuff: TKDT800DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT800DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildCall); var TempStoreBuff: TKDT800DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT800DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT800DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildMethod); var TempStoreBuff: TKDT800DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT800DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT800DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI64_BuildProc); var TempStoreBuff: TKDT800DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT800DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT800DI64.Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DI64_Node; var NearestNeighbour: PKDT800DI64_Node; function FindParentNode(const buffPtr: PKDT800DI64_Vec; NodePtr: PKDT800DI64_Node): PKDT800DI64_Node; var Next: PKDT800DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT800DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT800DI64_Node; const buffPtr: PKDT800DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT800DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT800DI64_Vec; const p1, p2: PKDT800DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT800DI64_Vec); var i, j: NativeInt; p, t: PKDT800DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT800DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT800DI64_Node(NearestNodes[0]); end; end; function TKDT800DI64.Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT800DI64.Search(const buff: TKDT800DI64_Vec; var SearchedDistanceMin: Double): PKDT800DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT800DI64.Search(const buff: TKDT800DI64_Vec): PKDT800DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT800DI64.SearchToken(const buff: TKDT800DI64_Vec): TPascalString; var p: PKDT800DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT800DI64.Search(const inBuff: TKDT800DI64_DynamicVecBuffer; var OutBuff: TKDT800DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT800DI64_DynamicVecBuffer; outBuffPtr: PKDT800DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT800DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT800DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT800DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT800DI64.Search(const inBuff: TKDT800DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT800DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT800DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT800DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT800DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT800DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT800DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT800DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT800DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT800DI64_Vec)) <> SizeOf(TKDT800DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT800DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT800DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT800DI64.PrintNodeTree(const NodePtr: PKDT800DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT800DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT800DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT800DI64.Vec(const s: SystemString): TKDT800DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT800DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT800DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT800DI64.Vec(const v: TKDT800DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT800DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT800DI64.Distance(const v1, v2: TKDT800DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT800DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT800DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT800DI64.Test; var TKDT800DI64_Test: TKDT800DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT800DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT800DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT800DI64_Test := TKDT800DI64.Create; n.Append('...'); SetLength(TKDT800DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT800DI64_Test.TestBuff) - 1 do for j := 0 to KDT800DI64_Axis - 1 do TKDT800DI64_Test.TestBuff[i][j] := i * KDT800DI64_Axis + j; {$IFDEF FPC} TKDT800DI64_Test.BuildKDTreeM(length(TKDT800DI64_Test.TestBuff), nil, @TKDT800DI64_Test.Test_BuildM); {$ELSE FPC} TKDT800DI64_Test.BuildKDTreeM(length(TKDT800DI64_Test.TestBuff), nil, TKDT800DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT800DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT800DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT800DI64_Test.TestBuff) - 1 do begin p := TKDT800DI64_Test.Search(TKDT800DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT800DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT800DI64_Test.TestBuff)); TKDT800DI64_Test.Search(TKDT800DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT800DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT800DI64_Test.Clear; { kMean test } TKDT800DI64_Test.BuildKDTreeWithCluster(TKDT800DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT800DI64_Test.Search(TKDT800DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT800DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT800DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT800DI64_Test); DoStatus(n); n := ''; end; function TKDT1024DI64.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DI64_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DI64_Node; function SortCompare(const p1, p2: PKDT1024DI64_Source; const axis: NativeInt): ShortInt; begin if p1^.buff[axis] = p2^.buff[axis] then begin if p1^.Index = p2^.Index then Result := 0 else if p1^.Index < p2^.Index then Result := -1 else Result := 1; end else if p1^.buff[axis] < p2^.buff[axis] then Result := -1 else Result := 1; end; procedure InternalSort(const SortBuffer: PKDT1024DI64_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT1024DI64_Source; begin repeat i := L; j := R; p := SortBuffer^[(L + R) shr 1]; repeat while SortCompare(SortBuffer^[i], p, axis) < 0 do Inc(i); while SortCompare(SortBuffer^[j], p, axis) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer^[i]; SortBuffer^[i] := SortBuffer^[j]; SortBuffer^[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, axis); L := i; until i >= R; end; var M: NativeInt; axis: NativeInt; kdBuffPtr: PKDT1024DI64_SourceBuffer; begin Result := nil; if PlanCount = 0 then Exit; if PlanCount = 1 then begin new(Result); Result^.Parent := nil; Result^.Right := nil; Result^.Left := nil; Result^.Vec := KDSourceBufferPtr^[0]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); end else begin axis := Depth mod KDT1024DI64_Axis; M := PlanCount div 2; kdBuffPtr := GetMemory(PlanCount * SizeOf(Pointer)); CopyPtr(@KDSourceBufferPtr^[0], @kdBuffPtr^[0], PlanCount * SizeOf(Pointer)); if PlanCount > 1 then InternalSort(@kdBuffPtr^[0], 0, PlanCount - 1, axis); new(Result); Result^.Parent := nil; Result^.Vec := kdBuffPtr^[M]; KDNodes[NodeCounter] := Result; Inc(NodeCounter); Result^.Left := InternalBuildKdTree(@kdBuffPtr^[0], M, Depth + 1); if Result^.Left <> nil then Result^.Left^.Parent := Result; Result^.Right := InternalBuildKdTree(@kdBuffPtr^[M + 1], PlanCount - (M + 1), Depth + 1); if Result^.Right <> nil then Result^.Right^.Parent := Result; FreeMemory(kdBuffPtr); end; end; function TKDT1024DI64.GetData(const Index: NativeInt): PKDT1024DI64_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT1024DI64.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT1024DI64.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT1024DI64.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT1024DI64_Node(KDNodes[i])); Inc(i); end; for i := 0 to length(KDStoreBuff) - 1 do KDStoreBuff[i].Token := ''; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); NodeCounter := 0; RootNode := nil; end; function TKDT1024DI64.StoreBuffPtr: PKDT1024DI64_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT1024DI64.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildCall); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1024DI64.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildMethod); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1024DI64.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildProc); var i, j: NativeInt; begin Clear; if PlanCount <= 0 then Exit; SetLength(KDStoreBuff, PlanCount); SetLength(KDBuff, PlanCount); SetLength(KDNodes, PlanCount); i := 0; while i < PlanCount do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; FillPtrByte(@KDStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT1024DI64.BuildKDTreeWithCluster(const inBuff: TKDT1024DI64_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT1024DI64_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT1024DI64_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT1024DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1024DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); SetLength(KArray, 0); end; SetLength(Source, 0); end; procedure TKDT1024DI64.BuildKDTreeWithCluster(const inBuff: TKDT1024DI64_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT1024DI64.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildCall); var TempStoreBuff: TKDT1024DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1024DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT1024DI64.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildMethod); var TempStoreBuff: TKDT1024DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1024DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; procedure TKDT1024DI64.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI64_BuildProc); var TempStoreBuff: TKDT1024DI64_DyanmicStoreBuffer; Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin Clear; SetLength(TempStoreBuff, PlanCount); i := 0; while i < PlanCount do begin TempStoreBuff[i].Index := i; TempStoreBuff[i].Token := ''; FillPtrByte(@TempStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI64_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI64_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI64_Axis, k, umlMax(Restarts, 1), KArray, OutIndex) = 1 then begin SetLength(KDStoreBuff, k); SetLength(KDBuff, k); SetLength(KDNodes, k); for i := 0 to k - 1 do begin KDBuff[i] := @KDStoreBuff[i]; KDStoreBuff[i].Index := i; KDStoreBuff[i].Token := ''; for j := 0 to KDT1024DI64_Axis - 1 do KDStoreBuff[i].buff[j] := KArray[j, i]; end; RootNode := InternalBuildKdTree(@KDBuff[0], k, 0); for i := 0 to length(OutIndex) - 1 do OutIndex[i] := TempStoreBuff[OutIndex[i]].Index; SetLength(KArray, 0); end; SetLength(TempStoreBuff, 0); SetLength(Source, 0); end; function TKDT1024DI64.Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DI64_Node; var NearestNeighbour: PKDT1024DI64_Node; function FindParentNode(const buffPtr: PKDT1024DI64_Vec; NodePtr: PKDT1024DI64_Node): PKDT1024DI64_Node; var Next: PKDT1024DI64_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT1024DI64_Axis; if buffPtr^[axis] > Next^.Vec^.buff[axis] then Next := Next^.Right else Next := Next^.Left; Depth := Depth + 1; end; end; procedure ScanSubtree(const NodePtr: PKDT1024DI64_Node; const buffPtr: PKDT1024DI64_Vec; const Depth: NativeInt; const NearestNodes: TCoreClassList); var Dist: Double; axis: NativeInt; begin if NodePtr = nil then Exit; Inc(SearchedCounter); if NearestNodes <> nil then NearestNodes.Add(NodePtr); Dist := Distance(buffPtr^, NodePtr^.Vec^.buff); if Dist < SearchedDistanceMin then begin SearchedDistanceMin := Dist; NearestNeighbour := NodePtr; end else if (Dist = SearchedDistanceMin) and (NodePtr^.Vec^.Index < NearestNeighbour^.Vec^.Index) then NearestNeighbour := NodePtr; axis := Depth mod KDT1024DI64_Axis; Dist := NodePtr^.Vec^.buff[axis] - buffPtr^[axis]; if Dist * Dist > SearchedDistanceMin then begin if NodePtr^.Vec^.buff[axis] > buffPtr^[axis] then ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes) else ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end else begin ScanSubtree(NodePtr^.Left, buffPtr, Depth + 1, NearestNodes); ScanSubtree(NodePtr^.Right, buffPtr, Depth + 1, NearestNodes); end; end; function SortCompare(const buffPtr: PKDT1024DI64_Vec; const p1, p2: PKDT1024DI64_Node): ShortInt; var d1, d2: Double; begin d1 := Distance(buffPtr^, p1^.Vec^.buff); d2 := Distance(buffPtr^, p2^.Vec^.buff); if d1 = d2 then begin if p1^.Vec^.Index = p2^.Vec^.Index then Result := 0 else if p1^.Vec^.Index < p2^.Vec^.Index then Result := -1 else Result := 1; end else if d1 < d2 then Result := -1 else Result := 1; end; procedure InternalSort(var SortBuffer: TCoreClassPointerList; L, R: NativeInt; const buffPtr: PKDT1024DI64_Vec); var i, j: NativeInt; p, t: PKDT1024DI64_Node; begin repeat i := L; j := R; p := SortBuffer[(L + R) shr 1]; repeat while SortCompare(buffPtr, SortBuffer[i], p) < 0 do Inc(i); while SortCompare(buffPtr, SortBuffer[j], p) > 0 do Dec(j); if i <= j then begin if i <> j then begin t := SortBuffer[i]; SortBuffer[i] := SortBuffer[j]; SortBuffer[j] := t; end; Inc(i); Dec(j); end; until i > j; if L < j then InternalSort(SortBuffer, L, j, buffPtr); L := i; until i >= R; end; var Parent: PKDT1024DI64_Node; begin Result := nil; SearchedDistanceMin := 0; SearchedCounter := 0; NearestNeighbour := nil; if NearestNodes <> nil then NearestNodes.Clear; if RootNode = nil then Exit; if Count = 0 then Exit; Parent := FindParentNode(@buff[0], RootNode); NearestNeighbour := Parent; SearchedDistanceMin := Distance(buff, Parent^.Vec^.buff); ScanSubtree(RootNode, @buff[0], 0, NearestNodes); if NearestNeighbour = nil then NearestNeighbour := RootNode; Result := NearestNeighbour; if NearestNodes <> nil then begin Result := NearestNeighbour; if NearestNodes.Count > 1 then InternalSort(NearestNodes.ListData^, 0, NearestNodes.Count - 1, @buff[0]); if NearestNodes.Count > 0 then Result := PKDT1024DI64_Node(NearestNodes[0]); end; end; function TKDT1024DI64.Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DI64_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT1024DI64.Search(const buff: TKDT1024DI64_Vec; var SearchedDistanceMin: Double): PKDT1024DI64_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1024DI64.Search(const buff: TKDT1024DI64_Vec): PKDT1024DI64_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1024DI64.SearchToken(const buff: TKDT1024DI64_Vec): TPascalString; var p: PKDT1024DI64_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT1024DI64.Search(const inBuff: TKDT1024DI64_DynamicVecBuffer; var OutBuff: TKDT1024DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1024DI64_DynamicVecBuffer; outBuffPtr: PKDT1024DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1024DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outBuffPtr := @OutBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT1024DI64_Node; begin p := Search(inBuffPtr^[pass]); outBuffPtr^[pass] := p^.Vec^.buff; outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT1024DI64_Node; begin if length(OutBuff) <> length(OutIndex) then Exit; if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutBuff[i] := p^.Vec^.buff; OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT1024DI64.Search(const inBuff: TKDT1024DI64_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1024DI64_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1024DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end; {$ENDIF FPC} begin if length(inBuff) <> length(OutIndex) then Exit; inBuffPtr := @inBuff; outIndexPtr := @OutIndex; GlobalMemoryHook.V := False; try {$IFDEF FPC} FPCParallelFor(@FPC_ParallelFor, 0, length(inBuff) - 1); {$ELSE FPC} DelphiParallelFor(0, length(inBuff) - 1, procedure(pass: Int64) var p: PKDT1024DI64_Node; begin p := Search(inBuffPtr^[pass]); outIndexPtr^[pass] := p^.Vec^.Index; end); {$ENDIF FPC} finally GlobalMemoryHook.V := True; end; end; {$ELSE parallel} var i: NativeInt; p: PKDT1024DI64_Node; begin if length(inBuff) <> length(OutIndex) then Exit; for i := 0 to length(inBuff) - 1 do begin p := Search(inBuff[i]); OutIndex[i] := p^.Vec^.Index; end; end; {$ENDIF parallel} procedure TKDT1024DI64.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT1024DI64_Axis; stream.write(st, 4); stream.write(ID, 4); stream.write(cnt, 8); i := 0; while i < cnt do begin stream.write(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec)); stream.write(KDStoreBuff[i].Index, 8); token_B := KDStoreBuff[i].Token.Bytes; token_L := length(token_B); stream.write(token_L, 4); if token_L > 0 then begin stream.write(token_B[0], token_L); SetLength(token_B, 0); end; Inc(i); end; end; procedure TKDT1024DI64.LoadFromStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin Clear; stream.read(st, 4); stream.read(ID, 4); if st <> SaveToken then RaiseInfo('kdtree token error!'); if ID <> KDT1024DI64_Axis then RaiseInfo('kdtree axis error!'); stream.read(cnt, 8); SetLength(KDStoreBuff, cnt); i := 0; try while i < cnt do begin if stream.read(KDStoreBuff[i].buff[0], SizeOf(TKDT1024DI64_Vec)) <> SizeOf(TKDT1024DI64_Vec) then begin Clear; Exit; end; if stream.read(KDStoreBuff[i].Index, 8) <> 8 then begin Clear; Exit; end; if stream.read(token_L, 4) <> 4 then begin Clear; Exit; end; if token_L > 0 then begin SetLength(token_B, token_L); if stream.read(token_B[0], token_L) <> token_L then begin Clear; Exit; end; KDStoreBuff[i].Token.Bytes := token_B; SetLength(token_B, 0); end else KDStoreBuff[i].Token := ''; Inc(i); end; except Clear; Exit; end; SetLength(KDBuff, cnt); SetLength(KDNodes, cnt); i := 0; while i < cnt do begin KDBuff[i] := @KDStoreBuff[i]; Inc(i); end; if cnt > 0 then RootNode := InternalBuildKdTree(@KDBuff[0], cnt, 0); end; procedure TKDT1024DI64.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1024DI64.LoadFromFile(FileName: SystemString); var fs: TCoreClassFileStream; begin try fs := TCoreClassFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); except Exit; end; try LoadFromStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1024DI64.PrintNodeTree(const NodePtr: PKDT1024DI64_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT1024DI64_Node); begin DoStatus('%s +%d (%s) ', [prefix, p^.Vec^.Index, Vec(p^.Vec^.buff)]); if p^.Left <> nil then DoPrintNode(prefix + ' |-----', p^.Left); if p^.Right <> nil then DoPrintNode(prefix + ' |-----', p^.Right); end; begin DoPrintNode('', NodePtr); end; procedure TKDT1024DI64.PrintBuffer; var i: NativeInt; begin for i := 0 to length(KDStoreBuff) - 1 do DoStatus('%d - %d : %s ', [i, KDStoreBuff[i].Index, Vec(KDStoreBuff[i].buff)]); end; class function TKDT1024DI64.Vec(const s: SystemString): TKDT1024DI64_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT1024DI64_Axis - 1 do Result[i] := 0; t := TTextParsing.Create(s, tsText, nil); if t.SplitChar(1, ', ', '', SplitOutput) > 0 then begin j := 0; for i := 0 to length(SplitOutput) - 1 do if umlGetNumTextType(SplitOutput[i]) <> ntUnknow then begin Result[j] := umlStrToInt(SplitOutput[i], 0); Inc(j); if j >= KDT1024DI64_Axis then Break; end; end; DisposeObject(t); end; class function TKDT1024DI64.Vec(const v: TKDT1024DI64_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT1024DI64_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT1024DI64.Distance(const v1, v2: TKDT1024DI64_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT1024DI64_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT1024DI64.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DI64_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT1024DI64.Test; var TKDT1024DI64_Test: TKDT1024DI64; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT1024DI64_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT1024DI64_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT1024DI64_Test := TKDT1024DI64.Create; n.Append('...'); SetLength(TKDT1024DI64_Test.TestBuff, 1000); for i := 0 to length(TKDT1024DI64_Test.TestBuff) - 1 do for j := 0 to KDT1024DI64_Axis - 1 do TKDT1024DI64_Test.TestBuff[i][j] := i * KDT1024DI64_Axis + j; {$IFDEF FPC} TKDT1024DI64_Test.BuildKDTreeM(length(TKDT1024DI64_Test.TestBuff), nil, @TKDT1024DI64_Test.Test_BuildM); {$ELSE FPC} TKDT1024DI64_Test.BuildKDTreeM(length(TKDT1024DI64_Test.TestBuff), nil, TKDT1024DI64_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT1024DI64_Test.SaveToStream(m64); m64.Position := 0; TKDT1024DI64_Test.LoadFromStream(m64); for i := 0 to length(TKDT1024DI64_Test.TestBuff) - 1 do begin p := TKDT1024DI64_Test.Search(TKDT1024DI64_Test.TestBuff[i]); if p^.Vec^.Index <> i then errored := True; if not p^.Vec^.Token.Same(umlIntToStr(i)) then errored := True; if errored then Break; end; DisposeObject(m64); if not errored then begin { parallel search test } n.Append('...parallel'); SetLength(TestResultBuff, length(TKDT1024DI64_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT1024DI64_Test.TestBuff)); TKDT1024DI64_Test.Search(TKDT1024DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT1024DI64_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT1024DI64_Test.Clear; { kMean test } TKDT1024DI64_Test.BuildKDTreeWithCluster(TKDT1024DI64_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT1024DI64_Test.Search(TKDT1024DI64_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT1024DI64_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT1024DI64_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT1024DI64_Test); DoStatus(n); n := ''; end; procedure Test_All; begin TKDT1DI64.Test(); TKDT2DI64.Test(); TKDT3DI64.Test(); TKDT4DI64.Test(); TKDT5DI64.Test(); TKDT6DI64.Test(); TKDT7DI64.Test(); TKDT8DI64.Test(); TKDT9DI64.Test(); TKDT10DI64.Test(); TKDT11DI64.Test(); TKDT12DI64.Test(); TKDT13DI64.Test(); TKDT14DI64.Test(); TKDT15DI64.Test(); TKDT16DI64.Test(); TKDT17DI64.Test(); TKDT18DI64.Test(); TKDT19DI64.Test(); TKDT20DI64.Test(); TKDT21DI64.Test(); TKDT22DI64.Test(); TKDT23DI64.Test(); TKDT24DI64.Test(); TKDT48DI64.Test(); TKDT52DI64.Test(); TKDT64DI64.Test(); TKDT96DI64.Test(); TKDT128DI64.Test(); TKDT156DI64.Test(); TKDT192DI64.Test(); TKDT256DI64.Test(); TKDT384DI64.Test(); TKDT512DI64.Test(); TKDT800DI64.Test(); TKDT1024DI64.Test(); end; initialization finalization end.
unit uCompilador; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Fgl ,SynLCHighlighter ,SynEditHighlighter; type TLCTypeOfProcess = (tpLCAttrName, tpLCComment, tpLCString, tpLCUnknown); TLCTypesProcessing = set of TLCTypeOfProcess; TLCDefParametro = record Name:String; IsEnd:Boolean; end; TLCListOfParametros = Array of TLCDefParametro; TLCTokenDef = record Texto : string; kind : TLCTokenKind; end; TLCArrayTokenDef = array of TLCTokenDef; TPtrLCArrayTokenDef = ^TLCArrayTokenDef; TPtrLCTokenDef = ^TLCTokenDef; TLCTipoBloco = (lcTBChave, lcTBSe, lcTBInicio, lcTBPara, lcTBEnquanto, lcTBParenteses, lcTBUnknown); TLCBloco = record Tipo: TLCTipoBloco; Ativo:Boolean; LinhaOrigem:Integer; ColunaOrigem:Integer; end; TLCTypeOfMessages = (lcTMUnknown, lcTMHint, lcTMWarning, lcTMError); Const LCDescriptionTypeOfMessages: Array[TLCTypeOfMessages] of string = ('Desconhecido','Sugestão', 'Atenção', 'Erro'); LCDescriptionBlocos: Array[TLCTipoBloco] of string = ('Chave', 'Se', 'Inicio', 'Para','Enquanto','Parenteses','Desconhecido'); Type { TLCMessages } TLCMessages = class private fColuna : Integer; fLinha : Integer; fTexto : String; fTextoEstatico : String; fTipo : TLCTypeOfMessages; protected public constructor Create; published property Texto:String read fTexto write fTexto; property TextoEstatico:String read fTextoEstatico write fTextoEstatico; property Linha:Integer read fLinha write fLinha; property Coluna:Integer read fColuna write fColuna; property Tipo:TLCTypeOfMessages read fTipo write fTipo; end; TLCListOfMessages = specialize TFPGObjectList<TLCMessages>; { TLCDefinitionOfFunction } TLCDefinitionOfFunction = Class private FDescription : String; FName : String; FParameters : TLCListOfParametros; FRowOfDefinition : Integer; FRowOfImplementation: Integer; protected public constructor Create; //destructor Destroy; virtual; procedure AddParam(aName:String; aIsEnd:Boolean); function GetTipText:String; published property Name:String read FName write FName; property Description:String read FDescription write FDescription; property Parameters:TLCListOfParametros read FParameters write FParameters; property RowOfDefinition:Integer read FRowOfDefinition write FRowOfDefinition; property RowOfImplementation:Integer read FRowOfImplementation write FRowOfImplementation; end; TLCListOfFunction = specialize TFPGObjectList<TLCDefinitionOfFunction>; //lista de bloques TLCProgressoCompilacao = procedure(Const pLinhaAtual:Integer; Const pTotalLinhas:Integer) of object; { TLCCompilador } TLCCompilador = class(TPersistent) private fIdentifiers: array[#0..#255] of ByteBool; FListOfFunctions: TLCListOfFunction; FListOfMessages: TLCListOfMessages; fNumberChar: array[char] of Boolean; fOnProgressoCompilacao : TLCProgressoCompilacao; fSpaceChar: array[char] of Boolean; fLines: TStrings; // conjunto de linhas a serem processadas fTypeOfToken: TLCTokenKind; fProcessing: TLCTypesProcessing; fTotalLinhasProcessar:Integer; fLine: PChar; // Linha Sendo processada fSizeLine: Integer; // Tamanho da linha fIndexCurLine:Integer; // Número da linha sendo processada fPosIniTok: Integer; // posição inicial do token na linha fCurPosInLine: Integer; // posição corrente do ponteiro na linha fHL: TSynLCHighlighter; fPermiteSenao:Boolean; fBlocos: array of TLCBloco; fListTokens: TLCArrayTokenDef; procedure DefineDefaultValidCaracters; function IdentKind(const pIsAttr:Boolean = false): TLCTokenKind; function IsLineEnd(pPosition: Integer): Boolean; procedure CommentMultiLineProc; procedure CommentInLineProc; procedure CRProc; procedure IdentProc(isAttr:Boolean = false); procedure ApostrofoProc; procedure LFProc; procedure NullProc; procedure MinusProc; procedure NumberProc; procedure PointProc; procedure SpaceProc; procedure StringProc; procedure StringMutlipeLinesProc; procedure SymbolProc; procedure UnknownProc; protected function GetLines: TStrings; virtual; procedure SetLines(Value: TStrings); virtual; public constructor Create; destructor Destroy; override; procedure Initialize; procedure SetLine(const NewValue: String; LineNumber: Integer); function IsEndOfRows: Boolean; function IsEndOfLine: Boolean; function NextRow:Boolean; function GetToken:String; procedure NextToken; procedure SkipSpaces(const ExtendToNextLine:Boolean; const SkipStrings:Boolean = true); procedure CompilarListaFuncoes(aList: TLCListOfFunction); procedure CompilarListaFuncoes; procedure AdicionarMensagem(pTipo:TLCTypeOfMessages; pTexto:String; pColuna, pLinha:Integer); procedure AdicionarBloco(const pTipoBloco: TLCTipoBloco; const pLinha, pColuna:Integer); function RemoverBloco(const pTipoBloco: TLCTipoBloco):Boolean; function FinalizarBloco(const pTipoBloco: TLCTipoBloco):Boolean; function SintaxeDefinir:Boolean; function SintaxeDefinirFuncao:Boolean; function SintaxeDefinirNumero:Boolean; function SintaxeSe:Boolean; function SintaxeEnquanto:Boolean; function SintaxeParenteses:Boolean; function SintaxePara:Boolean; function SintaxeFuncao(pTypeOfToken: TLCTokenKind):Boolean; function ChecarSintaxe:Boolean; Function SearchFunction(aList: TLCListOfFunction; aName:String):TLCDefinitionOfFunction; Function SearchFunction(aName:String):TLCDefinitionOfFunction; published property onProgressoCompilacao: TLCProgressoCompilacao read fOnProgressoCompilacao write fOnProgressoCompilacao; property Lines: TStrings read GetLines write SetLines; property ListOfFunctions:TLCListOfFunction read FListOfFunctions write FListOfFunctions; property ListOfMessages:TLCListOfMessages read FListOfMessages write FListOfMessages; property HL:TSynLCHighlighter read fHL write fHL; end; implementation { TLCMessages } constructor TLCMessages.Create; begin fColuna := -1; fLinha := -1; fTexto := ''; fTextoEstatico := ''; fTipo := lcTMUnknown; end; { TLCDefinitionOfFunction } constructor TLCDefinitionOfFunction.Create; begin FDescription := ''; FName := ''; FRowOfDefinition := -1; FRowOfImplementation := -1; SetLength(FParameters, 0); end; procedure TLCDefinitionOfFunction.AddParam(aName : String; aIsEnd : Boolean); var Param: TLCDefParametro; Index:Integer; begin Param.Name := aName; Param.IsEnd := aIsEnd; Index := Length(FParameters); setlength(FParameters, Index + 1); FParameters[Index] := Param; end; function TLCDefinitionOfFunction.GetTipText : String; var Param : TLCDefParametro; begin Result := ''; for Param in FParameters do begin if Result <> '' then begin Result += ','; end; Result += '"Numero '; if Param.IsEnd = True then begin Result += 'End '; end; Result += Param.Name + '"'; end; end; { TLCCompilador } function TLCCompilador.GetLines : TStrings; begin Result := FLines; end; procedure TLCCompilador.SetLines(Value : TStrings); begin FLines.Assign(Value); fTotalLinhasProcessar := FLines.Count; end; constructor TLCCompilador.Create; begin FLines := TStringList.Create(); FListOfFunctions := TLCListOfFunction.Create(true); FListOfMessages:= TLCListOfMessages.Create(true); fHL := nil; SetLength(fListTokens,0); SetLength(fBlocos,0); DefineDefaultValidCaracters; end; destructor TLCCompilador.Destroy; begin FreeAndNil(FListOfMessages); FreeAndNil(FListOfFunctions); FreeAndNil(FLines); inherited Destroy; end; procedure TLCCompilador.Initialize; begin FListOfMessages.Clear; SetLength(fBlocos,0); fPermiteSenao := False; fIndexCurLine := -1; fTypeOfToken := tLCUnknown; fProcessing := []; end; procedure TLCCompilador.SetLine(const NewValue : String; LineNumber : Integer); begin fLine := PChar(NewValue); fSizeLine := Length(NewValue); fIndexCurLine := LineNumber; fPosIniTok := 0; fCurPosInLine := 0; NextToken; end; function TLCCompilador.IsEndOfRows : Boolean; begin Result := fIndexCurLine >= fLines.Count; end; function TLCCompilador.IsEndOfLine : Boolean; begin Result := (fTypeOfToken = tLCEol) or IsLineEnd(fCurPosInLine); end; function TLCCompilador.NextRow : Boolean; begin inc(fIndexCurLine); if Assigned(fOnProgressoCompilacao) then begin fOnProgressoCompilacao(fIndexCurLine, fTotalLinhasProcessar); end; if IsEndOfRows = True then begin Result := False; Exit; end; SetLine(fLines[fIndexCurLine], fIndexCurLine); Result := True; end; function TLCCompilador.GetToken : String; var Len: LongInt; begin Len := fCurPosInLine - fPosIniTok; SetString(Result, (fLine + fPosIniTok), Len); end; procedure TLCCompilador.NextToken; begin fPosIniTok := fCurPosInLine; if fCurPosInLine = fSizeLine then begin fTypeOfToken := tLCEol; Exit; end; if (tpLCString in fProcessing) then begin StringMutlipeLinesProc; exit; end; if (tpLCComment in fProcessing) then begin CommentMultiLineProc; exit; end; if (tpLCAttrName in fProcessing) then begin IdentProc(true); fProcessing := fProcessing - [tpLCAttrName]; exit; end; case fLine[fCurPosInLine] of '@': CommentInLineProc; '/': CommentMultiLineProc; '}': SymbolProc; '{': SymbolProc; #0: NullProc; #10: LFProc; #13: CRProc; #1..#9, #11, #12, #14..#32: SpaceProc; '0'..'9': NumberProc; 'A'..'Z', 'a'..'z', '_': IdentProc; '-': MinusProc; '>': SymbolProc; '<': SymbolProc; '(': SymbolProc; ')': SymbolProc; ';': SymbolProc; ':': SymbolProc; '.': PointProc; #92: StringProc; // \ ']': SymbolProc; '[': SymbolProc; ',','+','*','|','=': SymbolProc; #34: StringProc; // " #39: ApostrofoProc; // ' else begin UnknownProc; end; end; end; procedure TLCCompilador.SkipSpaces(const ExtendToNextLine : Boolean; const SkipStrings : Boolean); var ListaProc: array[TLCTokenKind] of boolean = (false, true, false, false, false, true, false, false, true, false, false, true, false, true, false); begin //ListaProc[tLCSpace] := true; //ListaProc[tLCComment] := true; ListaProc[tLCString] := SkipStrings; NextToken; while (ExtendToNextLine = true) and (IsEndOfRows = false) and (IsEndOfLine = true) do begin NextRow; end; while (IsEndOfLine = false) and (ListaProc[fTypeOfToken]) do begin NextToken; while (ExtendToNextLine = true) and (IsEndOfRows = false) and (IsEndOfLine = true) do begin NextRow; end; end; end; procedure TLCCompilador.CompilarListaFuncoes; begin CompilarListaFuncoes(FListOfFunctions); end; procedure TLCCompilador.AdicionarMensagem(pTipo : TLCTypeOfMessages; pTexto : String; pColuna, pLinha : Integer); var oMsg: TLCMessages; begin oMsg := TLCMessages.Create; oMsg.Tipo := pTipo; oMsg.Texto := pTexto; oMsg.Linha := pLinha; oMsg.Coluna := pColuna; FListOfMessages.Add(oMsg); end; procedure TLCCompilador.AdicionarBloco(const pTipoBloco : TLCTipoBloco; const pLinha, pColuna : Integer); var iIndex:Integer; oBloco: TLCBloco; begin iIndex := Length(fBlocos); SetLength(fBlocos,iIndex + 1); oBloco.Tipo := pTipoBloco; oBloco.Ativo := True; oBloco.LinhaOrigem := pLinha; oBloco.ColunaOrigem := pColuna; fBlocos[iIndex] := oBloco; end; function TLCCompilador.RemoverBloco(const pTipoBloco : TLCTipoBloco) : Boolean; var iIndex:Integer; begin Result := true; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> pTipoBloco) then begin Result := false; Exit; end; SetLength(fBlocos,iIndex); end; function TLCCompilador.FinalizarBloco(const pTipoBloco : TLCTipoBloco) : Boolean; var iIndex:Integer; begin Result := true; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> pTipoBloco) or (fBlocos[iIndex].Ativo = False) then begin Result := false; Exit; end; fBlocos[iIndex].Ativo := False; end; function TLCCompilador.ChecarSintaxe : Boolean; var oTypeOfToken: TLCTokenKind; Token: String; iIndex, iPosIniToken, iLinhaErro: Integer; begin Result := true; FListOfMessages.Clear; Initialize; While (NextRow = true) do begin While (IsEndOfLine = False) do begin Token := AnsiUpperCase(GetToken); iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; Case Token of 'DEFINIR': begin SkipSpaces(True, False); if SintaxeDefinir = false then begin Result := false; exit; end; end; 'FUNCAO': begin SkipSpaces(True, False); if SintaxeDefinirFuncao = false then begin Result := false; exit; end; end; 'SE': begin AdicionarBloco(lcTBSe, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); if SintaxeSe = false then begin Result := false; exit; end; SkipSpaces(True, False); if AnsiUpperCase(GetToken) <> 'INICIO' then begin RemoverBloco(lcTBSe); AdicionarMensagem(lcTMHint, 'É recomendado incluir um Bloco INICIO/FIM para o "SE".', iPosIniToken, iLinhaErro); end; Continue; end; 'SENAO': begin if fPermiteSenao = false then begin AdicionarMensagem(lcTMWarning, 'Encontrado um "SENAO" sem um "SE" correspondente.', iPosIniToken, iLinhaErro); end; SkipSpaces(True, False); if (AnsiUpperCase(GetToken) <> 'INICIO') and (AnsiUpperCase(GetToken) <> 'SE') then begin AdicionarMensagem(lcTMHint, 'É recomendado incluir um Bloco INICIO/FIM para o "SENAO".', iPosIniToken, iLinhaErro); end; Continue; end; 'ENQUANTO': begin SkipSpaces(True, False); if SintaxeEnquanto = false then begin Result := false; exit; end; SkipSpaces(True, False); if AnsiUpperCase(GetToken) <> 'INICIO' then begin RemoverBloco(lcTBEnquanto); AdicionarMensagem(lcTMHint, 'É recomendado incluir um Bloco INICIO/FIM para o "ENQUANTO".', iPosIniToken, iLinhaErro); end; Continue; end; 'PARA': begin SkipSpaces(True, False); if SintaxePara = false then begin Result := false; exit; end; SkipSpaces(True, False); if AnsiUpperCase(GetToken) <> 'INICIO' then begin RemoverBloco(lcTBPara); AdicionarMensagem(lcTMHint, 'É recomendado incluir um Bloco INICIO/FIM para o "PARA".', iPosIniToken, iLinhaErro); end; Continue; end; 'INICIO': begin AdicionarBloco(lcTBInicio, fIndexCurLine + 1, fPosIniTok + 1); end; 'FIM': begin SkipSpaces(True, False); Token := GetToken; if Token <> ';' then begin AdicionarMensagem(lcTMHint, 'Depois de um "FIM" é recomendado um ";".', iPosIniToken, iLinhaErro); end; if RemoverBloco(lcTBInicio) = false then begin if RemoverBloco(lcTBSe) = false then begin Result := False; AdicionarMensagem(lcTMError, 'Encontrado um "FIM" sem um "INICIO" correspondente.', iPosIniToken, iLinhaErro); exit; end; RemoverBloco(lcTBInicio); end; if RemoverBloco(lcTBSe) = true then begin SkipSpaces(True, False); Token := UpperCase(GetToken); fPermiteSenao := (Token = 'SENAO'); Continue; end; end; '{': begin AdicionarBloco(lcTBChave, fIndexCurLine + 1, fPosIniTok + 1); end; '}': begin if RemoverBloco(lcTBChave) = false then begin if RemoverBloco(lcTBSe) = false then begin Result := False; AdicionarMensagem(lcTMError, 'Encontrado um "}" sem um "{" correspondente.', iPosIniToken, iLinhaErro); exit; end; RemoverBloco(lcTBInicio); end; if RemoverBloco(lcTBSe) = true then begin SkipSpaces(True, False); Token := UpperCase(GetToken); fPermiteSenao := (Token = 'SENAO'); Continue; end; end; '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); if SintaxeParenteses = false then begin Result := false; exit; end; end; ')': begin if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Encontrado um ")" sem um "(" correspondente.', iPosIniToken, iLinhaErro); exit; end; end; 'VAPARA': begin SkipSpaces(True, False); if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Nome "%s" é inválido para um "label".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; else begin Token := AnsiUpperCase(GetToken); if fTypeOfToken in [tLCReservedWord, tLCCustomFunction] then begin if Token = 'EXECSQL' then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCIdentifier, tLCString]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Parâmetro inválido.', iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, fTypeOfToken = tLCString); end else begin oTypeOfToken := fTypeOfToken; SkipSpaces(True, False); if SintaxeFuncao(oTypeOfToken) = false then begin Result := false; exit; end; SkipSpaces(True, False); end; Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end else if fTypeOfToken in [tLCIdentifier, tLCVariable] then begin SkipSpaces(True, False); Token := GetToken; if (Token = '+') or (Token = '-') then begin NextToken; if Token <> GetToken then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era esperado um símbolo "%s" mas foi identificado "%s".',[Token, GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Continue; end; if Token = '[' then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCNumber, tLCIdentifier]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado um "Número" ou "Variável" mas foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Token := GetToken; if Token = ']' then begin SkipSpaces(True, False); Token := GetToken; end; end; if Token = '=' then begin SkipSpaces(True, False); if (fTypeOfToken = tLCSymbol) and (GetToken <> '(') and (GetToken <> '-') then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é inválido.',[GetToken]), iPosIniToken, iLinhaErro); exit; end; if fTypeOfToken = tLCReservedWord then begin oTypeOfToken := fTypeOfToken; SkipSpaces(True, False); if SintaxeFuncao(oTypeOfToken) = false then begin Result := false; exit; end; SkipSpaces(True, False); if GetToken <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end else begin while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); if fTypeOfToken = tLCSymbol then begin if Token = ';' then begin break; end; if Token = '(' then begin if SintaxeParenteses = false then begin Result := false; exit; end; end else if Token = '[' then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCNumber, tLCIdentifier]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado um "Número" ou "Variável" mas foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Token := GetToken; if Token = ']' then begin SkipSpaces(True, False); Continue; end; end else if Token = '+' then begin SkipSpaces(True, False); Token := UpperCase(GetToken); if Token = '(' then begin Continue; end; if not (fTypeOfToken in [tLCNumber, tLCIdentifier, tLCString, tLCVariable]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado um "Número" ou um "Texto" ou "Variável de Ambiente" para foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; end else if Token = '.' then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCNumber, tLCIdentifier, tLCAttributeName]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Sintaxe Inválida.', iPosIniToken, iLinhaErro); exit; end; end else begin SkipSpaces(True, False); Token := UpperCase(GetToken); if Token = '(' then begin Continue; end; if not (fTypeOfToken in [tLCNumber, tLCIdentifier, tLCVariable]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado um número para foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); if fTypeOfToken <> tLCSymbol then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado "Operador", mas foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; Continue; end; end else if fTypeOfToken in [tLCNumber, tLCString, tLCIdentifier, tLCVariable] then begin SkipSpaces(True, fTypeOfToken = tLCString); if fTypeOfToken <> tLCSymbol then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Era aguardado "Operador", mas foi informado "%s".',[GetToken]), iPosIniToken, iLinhaErro); exit; end; Continue; end else if fTypeOfToken in [tLCKey] then begin SkipSpaces(True, False); if SintaxeFuncao(tLCKey) = false then begin Result := false; exit; end; SkipSpaces(True, False); if GetToken <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; Continue; end else begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Sintaxe inválida.', iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, fTypeOfToken = tLCString); end; end; end else if Token = '.' then begin NextToken; if fTypeOfToken = tLCAttributeName then begin Token := UpperCase(GetToken); if Token = 'SQL' then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCIdentifier, tLCString]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Parâmetro inválido.', iPosIniToken, iLinhaErro); exit; end; end else begin SkipSpaces(True, False); if SintaxeFuncao(tLCAttributeName) = false then begin Result := false; exit; end; end; SkipSpaces(True, (fTypeOfToken = tLCString)); if GetToken <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Continue; end; while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); if Token = '(' then begin if SintaxeParenteses = false then begin Result := false; exit; end; SkipSpaces(True, False); end; if Token = ';' then begin break; end; SkipSpaces(True, False); end; end else if Token = '(' then begin if SintaxeFuncao(tLCIdentifier) = false then begin Result := false; exit; end; SkipSpaces(True, False); if GetToken <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end else if Token = ':' then begin SkipSpaces(True, False); Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end else if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Comando Desconhecido "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; end; end; SkipSpaces(True, False); end; end; for iIndex:= 0 to High(fBlocos) do begin Result := False; iLinhaErro := fBlocos[iIndex].LinhaOrigem; iPosIniToken := fBlocos[iIndex].ColunaOrigem; AdicionarMensagem(lcTMError, Format('Faltou Finalizar o Bloco "%s".',[LCDescriptionBlocos[fBlocos[iIndex].Tipo]]), iPosIniToken, iLinhaErro); end; end; procedure TLCCompilador.CompilarListaFuncoes(aList : TLCListOfFunction); var iRowDef:Integer; NomeFuncao, Token: String; EhEnd: Boolean; Funcao: TLCDefinitionOfFunction; begin aList.Clear; Initialize; While (NextRow = true) do begin While (IsEndOfLine = False) do begin Token := GetToken; if AnsiUpperCase(Token) = 'DEFINIR' then begin SkipSpaces(True, True); Token := GetToken; if AnsiUpperCase(Token) = 'FUNCAO' then begin SkipSpaces(True, True); NomeFuncao := GetToken; iRowDef := fIndexCurLine + 1; // fIndexCurLine é base ZERO // Buscar os parametros SkipSpaces(True, True); Token := GetToken; if Token = '(' then begin SkipSpaces(True, True); Token := GetToken; if (AnsiUpperCase(Token) = 'NUMERO') then begin Funcao := TLCDefinitionOfFunction.Create; Funcao.Name := NomeFuncao; Funcao.RowOfDefinition := iRowDef; while (IsEndOfRows = false) do begin if (AnsiUpperCase(Token) = 'NUMERO') then begin EhEnd := False; SkipSpaces(True, True); Token := GetToken; if (AnsiUpperCase(Token) = 'END') then begin EhEnd := true; SkipSpaces(True, True); Token := GetToken; end; Funcao.AddParam(Token, EhEnd); end; SkipSpaces(True, True); Token := GetToken; if Token = ')' then begin aList.Add(Funcao); Break; end; end; end else begin if Token = ')' then begin Funcao := TLCDefinitionOfFunction.Create; Funcao.Name := NomeFuncao; Funcao.RowOfDefinition := iRowDef; aList.Add(Funcao); Break; end; end; end; end; end else if AnsiUpperCase(Token) = 'FUNCAO' then begin SkipSpaces(True, True); NomeFuncao := GetToken; Funcao := SearchFunction(aList, NomeFuncao); if Funcao <> nil then begin Funcao.RowOfImplementation := fIndexCurLine + 1; // fIndexCurLine é base ZERO end; end; SkipSpaces(True, True); end; end; end; function TLCCompilador.SearchFunction(aList : TLCListOfFunction; aName : String) : TLCDefinitionOfFunction; var i: integer; sName:String; begin Result := nil; if aName = '' then begin exit; end; for i := 0 to aList.Count-1 do begin sName := UpCase(aList[i].Name); if sName = UpCase(aName) then begin Result := aList[i]; exit; end; end; end; function TLCCompilador.SearchFunction(aName : String) : TLCDefinitionOfFunction; begin Result := SearchFunction(FListOfFunctions, aName); end; procedure TLCCompilador.DefineDefaultValidCaracters; var I: Char; begin for I := #0 to #255 do begin case I of '_', '0'..'9', 'a'..'z', 'A'..'Z': fIdentifiers[I] := True; else fIdentifiers[I] := False; end; fNumberChar[I]:=(I in ['0'..'9']); fSpaceChar[I]:=(I in [#1..#9, #11, #12, #14..#32]); end; end; function TLCCompilador.IdentKind(const pIsAttr : Boolean) : TLCTokenKind; begin if fHL <> nil then begin Result := fHL.IdentKind(pIsAttr, GetToken); Exit; end; Result := tLCIdentifier; // default value if pIsAttr = true then begin Result := tLCAttributeName; end; end; function TLCCompilador.IsLineEnd(pPosition : Integer) : Boolean; begin Result := (pPosition > fSizeLine) or (fLine[pPosition] = #10) or (fLine[pPosition] = #13); end; procedure TLCCompilador.CommentMultiLineProc; begin if (tpLCComment in fProcessing) = false then begin fTypeOfToken := tLCSymbol; inc(fCurPosInLine); if (fLine[fCurPosInLine] = '*') then begin inc(fCurPosInLine); fProcessing := fProcessing + [tpLCComment]; fTypeOfToken := tLCComment; CommentMultiLineProc; end; end else begin fTypeOfToken := tLCComment; while not IsLineEnd(fCurPosInLine) do begin if (fLine[fCurPosInLine] = '*') and (fLine[fCurPosInLine + 1] = '/') then begin Inc(fCurPosInLine, 2); fProcessing := fProcessing - [tpLCComment]; fTypeOfToken := tLCUnknown; break; end; inc(fCurPosInLine); end; // while Lines end; // else-if end; procedure TLCCompilador.CommentInLineProc; begin fTypeOfToken := tLCComment; Inc(fCurPosInLine); while (IsLineEnd(fCurPosInLine) = false) and (fLine[fCurPosInLine] <> '@') do begin Inc(fCurPosInLine); end; if (fLine[fCurPosInLine] in ['@']) then begin Inc(fCurPosInLine); end; end; procedure TLCCompilador.CRProc; begin fTypeOfToken := tLCSpace; inc(fCurPosInLine); if fLine[fCurPosInLine] = #10 then begin inc(fCurPosInLine); end; end; procedure TLCCompilador.IdentProc(isAttr : Boolean); begin inc(fCurPosInLine); while fIdentifiers[fLine[fCurPosInLine]] do begin inc(fCurPosInLine); end; fTypeOfToken := IdentKind(isAttr); end; procedure TLCCompilador.ApostrofoProc; begin inc(fCurPosInLine,3); fTypeOfToken := tLCString; end; procedure TLCCompilador.LFProc; begin fTypeOfToken := tLCSpace; inc(fCurPosInLine); end; procedure TLCCompilador.NullProc; begin fTypeOfToken := tLCNull; if fCurPosInLine < fSizeLine then begin inc(fCurPosInLine); end; end; procedure TLCCompilador.MinusProc; begin fTypeOfToken := tLCSymbol; inc(fCurPosInLine); if fNumberChar[fLine[fCurPosInLine]] = true then begin dec(fCurPosInLine); NumberProc; end; end; procedure TLCCompilador.NumberProc; begin inc(fCurPosInLine); fTypeOfToken := tLCNumber; if fCurPosInLine < fSizeLine then begin while (fNumberChar[fLine[fCurPosInLine]]) do begin inc(fCurPosInLine); end; if (fLine[fCurPosInLine] = '.') and (fLine[fCurPosInLine + 1] <> '.') then begin inc(fCurPosInLine); while (fNumberChar[fLine[fCurPosInLine]]) do begin inc(fCurPosInLine); end; end; if (fLine[fCurPosInLine] = 'e') or (fLine[fCurPosInLine] = 'E') then begin inc(fCurPosInLine); if (fLine[fCurPosInLine] = '+') or (fLine[fCurPosInLine] = '-') then begin inc(fCurPosInLine); end; while (fNumberChar[fLine[fCurPosInLine]]) do begin inc(fCurPosInLine); end; end; end; end; procedure TLCCompilador.PointProc; begin fTypeOfToken := tLCSymbol; inc(fCurPosInLine); if (fIdentifiers[fLine[fCurPosInLine]] = true) then begin fProcessing := fProcessing + [tpLCAttrName]; end; end; function TLCCompilador.SintaxeDefinir : Boolean; Var sOldToken, Token:String; iPosIniToken, iLinhaErro:Integer; begin Result := true; if fTypeOfToken <> tLCDataType then begin iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; sOldToken := GetToken; NextToken; Token := GetToken; if Token = '.' then begin NextToken; while (IsEndOfLine = false) and (fTypeOfToken <> tLCSpace) do begin if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '.' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; NextToken; if IsEndOfLine = true then begin NextRow; end; end; SkipSpaces(True, False); if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Identificador "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; end else begin Result := False; AdicionarMensagem(lcTMError, Format('Tipo de Variável "%s" é Inválido.', [sOldToken]), iPosIniToken, iLinhaErro); exit; end; end else begin Token := AnsiUpperCase(GetToken); if SameText('FUNCAO', Token) then begin SkipSpaces(True, False); if SintaxeDefinirFuncao = false then begin Result := false; exit; end; end else if SameText('NUMERO', Token) then begin SkipSpaces(True, False); if SintaxeDefinirNumero = false then begin Result := false; exit; end; end else begin SkipSpaces(True, False); if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Identificador "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); end; Token := GetToken; if Token <> ';' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um ";".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; end; function TLCCompilador.SintaxeDefinirFuncao : Boolean; Var Token:String; bPrimeiro:Boolean; iPosIniToken, iLinhaErro:Integer; begin Result := True; bPrimeiro := true; if not (fTypeOfToken in [tLCIdentifier, tLCCustomFunction]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Nome da Função "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '(' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era esperado um "(".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); while (IsEndOfLine = false) do begin Token := AnsiUpperCase(GetToken); if Token <> 'NUMERO' then begin if (Token = ')') And (bPrimeiro = true) then begin SkipSpaces(True, False); break; end; Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Tipo do Parâmetro esperado é "Número" mas foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; bPrimeiro := false; SkipSpaces(True, False); Token := AnsiUpperCase(GetToken); if Token = 'END' then begin SkipSpaces(True, False); end; if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Nome do Parâmetro "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token = ')' then begin SkipSpaces(True, False); break; end else if Token <> ',' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" é Inválido neste local. Era aguardado uma ",".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end else begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Identificador "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); end; end; end; function TLCCompilador.SintaxeDefinirNumero : Boolean; Var Token:String; iPosIniToken, iLinhaErro:Integer; begin Result := True; if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Nome "%s" para Variável é Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token = ';' then begin exit; end; if Token = '[' then begin SkipSpaces(True, False); if fTypeOfToken <> tLCNumber then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Número "%s" Inválido.', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); Token := GetToken; if Token <> ']' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" Inválido. Era esperado "]".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; SkipSpaces(True, False); end; end; end; function TLCCompilador.SintaxeSe : Boolean; Var Token:String; iIndex, iLinhaErro, iPosIniToken:integer; begin Result := True; if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '(' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "(" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); Case Token of '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); end; ')': begin if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Tentativa de Fechar Parenteses antes de Abrir', iPosIniToken, iLinhaErro); exit; end; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> lcTBParenteses) then begin break; end; SkipSpaces(True, False); Token := UpperCase(GetToken); if Token = ')' then begin Continue; end; if (Token <> 'E') and (Token <> 'OU') and (fTypeOfToken <> tLCSymbol) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "E" ou "OU" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; ';', 'INICIO': begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se ")" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; SkipSpaces(True, False); end; end; function TLCCompilador.SintaxeEnquanto : Boolean; Var Token:String; iIndex, iPosIniToken, iLinhaErro:Integer; begin Result := True; if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '(' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "(" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); Case Token of '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); end; ')': begin if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Tentativa de Fechar Parenteses antes de Abrir', iPosIniToken, iLinhaErro); exit; end; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> lcTBParenteses) then begin break; end; SkipSpaces(True, False); Token := UpperCase(GetToken); if Token = ')' then begin Continue; end; if (Token <> 'E') and (Token <> 'OU') and (fTypeOfToken <> tLCSymbol) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "E" ou "OU" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; ';', 'INICIO': begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se ")" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; SkipSpaces(True, False); end; end; function TLCCompilador.SintaxeParenteses : Boolean; Var Token:String; iIndex, iPosIniToken, iLinhaErro:Integer; begin Result := True; while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); Case Token of '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); end; ')': begin if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Tentativa de Fechar Parenteses antes de Abrir', iPosIniToken, iLinhaErro); exit; end; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> lcTBParenteses) then begin break; end; end; ';', '{', '}', 'SE', 'ENQUANTO', 'INICIO', 'FIM': begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se ")" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; SkipSpaces(True, False); end; end; function TLCCompilador.SintaxePara : Boolean; Var Token:String; iIndex, iPosIniToken, iLinhaErro:Integer; begin Result := True; if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '(' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "(" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); Case Token of '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); end; ')': begin if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Tentativa de Fechar Parenteses antes de Abrir', iPosIniToken, iLinhaErro); exit; end; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> lcTBParenteses) then begin break; end; end; '{', '}', 'SE', 'ENQUANTO', 'INICIO', 'FIM': begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se ")" para foi encontrado "%s".', [GetToken]), iPosIniToken, iLinhaErro); exit; end; end; SkipSpaces(True, False); end; end; function TLCCompilador.SintaxeFuncao(pTypeOfToken : TLCTokenKind) : Boolean; Var Token:String; iExpressao, iIndex, iPosIniToken, iLinhaErro:Integer; bFoiVirgula:Boolean; begin Result := True; bFoiVirgula := False; iExpressao := 0; if fTypeOfToken = tLCSymbol then begin Token := GetToken; if Token <> '(' then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Esperava-se "(" para foi encontrado "%s".', [Token]), iPosIniToken, iLinhaErro); exit; end; end; AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); SkipSpaces(True, False); while (IsEndOfLine = false) do begin Token := UpperCase(GetToken); Case Token of ',': begin bFoiVirgula := true; end; '(': begin AdicionarBloco(lcTBParenteses, fIndexCurLine + 1, fPosIniTok + 1); inc(iExpressao); end; ')': begin if bFoiVirgula = true then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Faltou informar parâmetro.', iPosIniToken, iLinhaErro); exit; end; if RemoverBloco(lcTBParenteses) = false then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Tentativa de Fechar Parenteses antes de Abrir', iPosIniToken, iLinhaErro); exit; end; iIndex := High(fBlocos); if (iIndex = -1) or (fBlocos[iIndex].Tipo <> lcTBParenteses) then begin break; end; dec(iExpressao); end; else begin bFoiVirgula := False; if ((pTypeOfToken in [tLCKey,tLCReservedWord]) and not (fTypeOfToken in [tLCKey, tLCString, tLCNumber, tLCIdentifier, tLCVariable])) or ((pTypeOfToken = tLCAttributeName) and not (fTypeOfToken in [tLCDataType, tLCString, tLCNumber, tLCIdentifier, tLCVariable])) or ((pTypeOfToken in [tLCCustomFunction, tLCIdentifier]) and not (fTypeOfToken in [tLCKey, tLCNumber, tLCIdentifier, tLCVariable])) then begin if ((pTypeOfToken = tLCKey) and (AnsiUpperCase(GetToken) <> 'GRAVAR')) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, 'Parâmetro inválido.', iPosIniToken, iLinhaErro); exit; end; end; SkipSpaces(True, (fTypeOfToken = tLCString)); Token := GetToken; if fTypeOfToken <> tLCSymbol then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Símbolo "%s" inválido.',[Token]), iPosIniToken, iLinhaErro); exit; end; if Token = '.' then begin SkipSpaces(True, False); if fTypeOfToken <> tLCIdentifier then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Identificador "%s" inválido.',[GetToken]), iPosIniToken, iLinhaErro); exit; end; end; if iExpressao = 0 then begin if (Token = '+') or (Token = '-') or (Token = '/') or (Token = '*') then begin SkipSpaces(True, False); if not (fTypeOfToken in [tLCIdentifier,tLCNumber]) then begin Result := False; iLinhaErro := fIndexCurLine + 1; iPosIniToken := fPosIniTok + 1; AdicionarMensagem(lcTMError, Format('Identificador ou número "%s" inválido.',[GetToken]), iPosIniToken, iLinhaErro); exit; end; continue; end; if Token <> ',' then begin continue; end; bFoiVirgula := true; end else begin if Token = ')' then begin continue; end; end; end; end; SkipSpaces(True, False); end; end; procedure TLCCompilador.SpaceProc; begin inc(fCurPosInLine); fTypeOfToken := tLCSpace; while fSpaceChar[fLine[fCurPosInLine]] do begin inc(fCurPosInLine); end; end; procedure TLCCompilador.StringProc; begin fTypeOfToken := tLCString; fProcessing := fProcessing - [tpLCString]; Inc(fCurPosInLine); While (IsLineEnd(fCurPosInLine) = false) do begin case (fLine[fCurPosInLine]) of #34: begin Inc(fCurPosInLine); if (fLine[fCurPosInLine] = #34) then begin Inc(fCurPosInLine); end else begin break; end; end; #92: begin Inc(fCurPosInLine); if not (fLine[fCurPosInLine] in [#34, #92]) then // \" \\ begin fProcessing := fProcessing + [tpLCString]; break; end; Inc(fCurPosInLine); end; else begin Inc(fCurPosInLine); end; end; // case end; // while end; procedure TLCCompilador.StringMutlipeLinesProc; begin fTypeOfToken := tLCString; while not IsLineEnd(fCurPosInLine) do begin case fLine[fCurPosInLine] of #34: // #34 = " begin if (fLine[fCurPosInLine + 1] = #34) then begin Inc(fCurPosInLine, 2); end else begin inc(fCurPosInLine); fProcessing := fProcessing - [tpLCString]; break; end; end; #92: // #92 = \ begin Inc(fCurPosInLine); if (fLine[fCurPosInLine] in [#34, #92]) then // \" \\ begin Inc(fCurPosInLine); end; end; else begin inc(fCurPosInLine); end; end; // case end; // while end; procedure TLCCompilador.SymbolProc; begin inc(fCurPosInLine); fTypeOfToken := tLCSymbol; end; procedure TLCCompilador.UnknownProc; begin inc(fCurPosInLine); While (fLine[fCurPosInLine] in [#128..#191]) // continued utf8 subcode or (fLine[fCurPosInLine] <> #0) do begin inc(fCurPosInLine); end; fTypeOfToken := tLCUnknown; end; end.
unit uROR_TreeGrid; interface {$IFNDEF NOVTREE} uses SysUtils, Classes, Controls, Windows, uROR_GridView, OvcFiler, VirtualTrees, uROR_Utilities, Graphics; type TCCRTreeGridColumn = class; TCCRTreeGrid = class; TCCRTreeGridSortEvent = procedure(aSender: TCCRTreeGrid; var aColumn: TColumnIndex; var aDirection: TSortDirection) of object; TCCRTreeGrid = class(TVirtualStringTree) private fColor: TColor; fItemUpdateLock: Integer; fOnSort: TCCRTreeGridSortEvent; procedure findCallback(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean); function getField(aFieldIndex: Integer): TCCRTreeGridColumn; procedure setColor(const aColor: TColor); protected procedure ConstructNode(aNode: PVirtualNode); virtual; function DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; override; procedure DoFreeNode(Node: PVirtualNode); override; procedure DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var Text: WideString); override; procedure DoHeaderClick(Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure DoSort(aColumn: TColumnIndex); virtual; function formatFieldValue(aNode: PVirtualNode; aFieldIndex: Integer): String; function getAsBoolean(aNode: PVirtualNode; aFieldIndex: Integer): Boolean; function getAsDateTime(aNode: PVirtualNode; aFieldIndex: Integer): TDateTime; function getAsDouble(aNode: PVirtualNode; aFieldIndex: Integer): Double; function getAsInteger(aNode: PVirtualNode; aFieldIndex: Integer): Integer; function getAsString(aNode: PVirtualNode; aFieldIndex: Integer): String; function getFormatted(aNode: PVirtualNode; aFieldIndex: Integer): String; function GetColumnClass: TVirtualTreeColumnClass; override; procedure setAsBoolean(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Boolean); procedure setAsDateTime(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: TDateTime); procedure setAsDouble(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Double); procedure setAsInteger(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Integer); procedure setAsString(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: String); procedure SetEnabled(aValue: Boolean); override; procedure UpdateStringValues(aNode: PVirtualNode; const aFieldIndex: Integer = -1); property ItemUpdateLock: Integer read fItemUpdateLock; public constructor Create(anOwner: TComponent); override; function AddChild(Parent: PVirtualNode; UserData: Pointer = nil): PVirtualNode; procedure AppendRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'; const numStrPerItem: Integer = 1); procedure AssignRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'); procedure BeginItemUpdate(aNode: PVirtualNode); virtual; procedure EndItemUpdate(aNode: PVirtualNode); virtual; function Find(const aValue: String; const aField: Integer; aParent: PVirtualNode = nil; const Recursive: Boolean = False): PVirtualNode; function GetDataType(aFieldIndex: Integer): TCCRGridDataType; procedure GetRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'); function GetRawNodeData(aNode: PVirtualNode; anIndexList: array of Integer; const Separator: String = '^'): String; function InsertNode(Node: PVirtualNode; Mode: TVTNodeAttachMode; UserData: Pointer = nil): PVirtualNode; procedure LoadLayout(aStorage: TOvcAbstractStore; const aSection: String); virtual; procedure SaveLayout(aStorage: TOvcAbstractStore; const aSection: String); virtual; procedure SetRawNodeData(aNode: PVirtualNode; const RawData: String; anIndexList: array of Integer; const Separator: String = '^'); procedure SortData; virtual; property AsBoolean[aNode: PVirtualNode; anIndex: Integer]: Boolean read getAsBoolean write setAsBoolean; property AsDateTime[aNode: PVirtualNode; anIndex: Integer]: TDateTime read getAsDateTime write setAsDateTime; property AsDouble[aNode: PVirtualNode; anIndex: Integer]: Double read getAsDouble write setAsDouble; property AsInteger[aNode: PVirtualNode; anIndex: Integer]: Integer read getAsInteger write setAsInteger; property AsString[aNode: PVirtualNode; anIndex: Integer]: String read getAsString write setAsString; property Fields[aFieldIndex: Integer]: TCCRTreeGridColumn read getField; property Formatted[aNode: PVirtualNode; anIndex: Integer]: String read getFormatted; published property Align; property Anchors; property BevelEdges; property BevelInner; property BevelOuter; property BevelKind default bkNone; property BevelWidth; property BiDiMode; property BorderStyle; property BorderWidth; property ChangeDelay; property Ctl3D; property Constraints; property DragKind; property DragCursor; property DragMode; property Enabled; property Font; property Images; property Indent; property ParentBiDiMode; property ParentColor default False; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property StateImages; property TabOrder; property TabStop default True; property Visible; property Color: TColor read fColor write setColor default clWindow; property OnSort: TCCRTreeGridSortEvent read fOnSort write fOnSort; end; TCCRTreeGridColumn = class(TVirtualTreeColumn) private fAllowSort: Boolean; fDataType: TCCRGridDataType; fFMDTOptions: TFMDateTimeMode; fFormat: String; public constructor Create(aCollection: TCollection); override; procedure Assign(Source: TPersistent); override; published property AllowSort: Boolean read fAllowSort write fAllowSort default True; property DataType: TCCRGridDataType read fDataType write fDataType default gftString; property FMDTOptions: TFMDateTimeMode read fFMDTOptions write fFMDTOptions default fmdtShortDateTime; property Format: String read fFormat write fFormat; end; {$ENDIF} implementation {$IFNDEF NOVTREE} uses uROR_Resources; type SearchDescriptor = record Field: Integer; Value: String; end; ///////////////////////////////// TCCRTreeGrid \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ constructor TCCRTreeGrid.Create(anOwner: TComponent); begin inherited; BevelKind := bkNone; fColor := clWindow; NodeDataSize := SizeOf(TCCRFieldDataArray); ParentColor := False; TreeOptions.SelectionOptions := TreeOptions.SelectionOptions + [toFullRowSelect]; TabStop := True; end; function TCCRTreeGrid.AddChild(Parent: PVirtualNode; UserData: Pointer): PVirtualNode; begin Result := inherited AddChild(Parent, UserData); if Assigned(Result) then ConstructNode(Result); end; procedure TCCRTreeGrid.AppendRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'; const numStrPerItem: Integer = 1); var i, j: Integer; buf: String; vn: PVirtualNode; begin BeginUpdate; try i := 0; while i < RawData.Count do begin buf := RawData[i]; Inc(i); for j:=2 to numStrPerItem do begin if i >= RawData.Count then Break; buf := buf + Separator + RawData[i]; Inc(i); end; vn := AddChild(RootNode); SetRawNodeData(vn, buf, anIndexList, Separator); end; finally EndUpdate; end; end; procedure TCCRTreeGrid.AssignRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'); begin BeginUpdate; try Clear; AppendRawData(RawData, anIndexList, Separator); finally EndUpdate; end; end; procedure TCCRTreeGrid.BeginItemUpdate(aNode: PVirtualNode); begin if fItemUpdateLock = 0 then BeginUpdate; Inc(fItemUpdateLock); end; procedure TCCRTreeGrid.EndItemUpdate(aNode: PVirtualNode); begin if fItemUpdateLock > 0 then begin Dec(fItemUpdateLock); if fItemUpdateLock = 0 then begin UpdateStringValues(aNode); EndUpdate; end; end; end; procedure TCCRTreeGrid.ConstructNode(aNode: PVirtualNode); var pfda: PCCRFieldDataArray; begin pfda := GetNodeData(aNode); SetLength(pfda^, Header.Columns.Count); end; function TCCRTreeGrid.DoCompare(Node1, Node2: PVirtualNode; Column: TColumnIndex): Integer; var dt1, dt2, dt: TCCRGridDataType; iv1, iv2: Integer; dv1, dv2: Double; bv1, bv2: Boolean; pfda1, pfda2: PCCRFieldDataArray; begin Result := 0; if (Column < 0) or (Column >= Header.Columns.Count) then Exit; dt := Fields[Column].DataType; if dt = gftMUMPS then begin pfda1 := GetNodeData(Node1); pfda2 := GetNodeData(Node2); //--- Get the actual data types dt1 := pfda1^[Column].MType; dt2 := pfda2^[Column].MType; //--- If they are different, perform MUMPS-like comparison. //--- Otherwise, skip to the regular comparison of values. if dt1 <> dt2 then begin //--- Item1 if getAsString(Node1, Column) = '' then Dec(Result, 1) else if dt1 = gftDouble then Inc(Result, 1) else if dt1 = gftString then Inc(Result, 2); //--- Item2 if getAsString(Node2, Column) = '' then Inc(Result, 1) else if dt2 = gftDouble then Dec(Result, 1) else if dt2 = gftString then Dec(Result, 2); { dv1\dv2 | empty | number | string --------+-------+--------+--------- empty | 0 | -2 | -3 --------+-------+--------+--------- number | 2 | cmp. | -1 --------+-------+--------+--------- string | 3 | 1 | cmp. } if Result < -1 then Result := -1; if Result > 1 then Result := 1; end else dt := dt1; end; //--- Regular comparison of field values case dt of gftBoolean: begin bv1 := getAsBoolean(Node1, Column); bv2 := getAsBoolean(Node2, Column); if bv1 > bv2 then Result := 1 else if bv1 < bv2 then Result := -1; end; gftDateTime, gftDouble, gftFMDate: begin dv1 := getAsDouble(Node1, Column); dv2 := getAsDouble(Node2, Column); if dv1 > dv2 then Result := 1 else if dv1 < dv2 then Result := -1; end; gftInteger: begin iv1 := getAsInteger(Node1, Column); iv2 := getAsInteger(Node2, Column); if iv1 > iv2 then Result := 1 else if iv1 < iv2 then Result := -1; end; gftString: Result := CompareStr( getAsString(Node1, Column), getAsString(Node2, Column)); end; end; procedure TCCRTreeGrid.DoFreeNode(Node: PVirtualNode); var pfda: PCCRFieldDataArray; begin try pfda := GetNodeData(Node); Finalize(pfda^); except end; inherited; end; procedure TCCRTreeGrid.DoGetText(Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var Text: WideString); begin if TextType = ttNormal then Text := formatFieldValue(Node, Column); inherited DoGetText(Node, Column, TextType, Text); end; procedure TCCRTreeGrid.DoHeaderClick(Column: TColumnIndex; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button <> mbLeft) or (Shift <> []) then inherited DoHeaderClick(Column, Button, Shift, X, Y) else if Fields[Column].AllowSort then DoSort(Column); end; procedure TCCRTreeGrid.DoSort(aColumn: TColumnIndex); var dir: TSortDirection; begin if aColumn <> Header.SortColumn then dir := sdAscending else if Header.SortDirection = sdAscending then dir := sdDescending else dir := sdAscending; if not (toAutoSort in TreeOptions.AutoOptions) then begin if Assigned(OnSort) then OnSort(Self, aColumn, dir); //--- Header.SortColumn := aColumn; Header.SortDirection := dir; //--- if not Assigned(OnSort) then SortTree(aColumn, dir); end else begin Header.SortColumn := aColumn; Header.SortDirection := dir; end; end; function TCCRTreeGrid.Find(const aValue: String; const aField: Integer; aParent: PVirtualNode; const Recursive: Boolean): PVirtualNode; var sd: SearchDescriptor; begin Result := nil; if Recursive then begin sd.Field := aField; sd.Value := aValue; Result := IterateSubtree(aParent, findCallback, @sd); end else begin Result := GetFirstChild(aParent); while Assigned(Result) do if AsString[Result,aField] = aValue then Break else Result := GetNextSibling(Result); end; end; procedure TCCRTreeGrid.findCallback(Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean); begin with SearchDescriptor(Data^) do Abort := (AsString[Node,Field] = Value); end; function TCCRTreeGrid.formatFieldValue(aNode: PVirtualNode; aFieldIndex: Integer): String; var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin Result := ''; pfda := GetNodeData(aNode); if (aFieldIndex < 0) or (aFieldIndex > High(pfda^)) then Exit; dt := GetDataType(aFieldIndex); if dt = gftUnknown then Exit; //--- Get the default external value of the field case dt of gftBoolean: Result := BooleanToString( pfda^[aFieldIndex].VBoolean, Fields[aFieldIndex].Format); gftDateTime: if pfda^[aFieldIndex].VDateTime > 0 then Result := FormatDateTime( Fields[aFieldIndex].Format, pfda^[aFieldIndex].VDateTime); gftDouble: Result := FormatFloat( Fields[aFieldIndex].Format, pfda^[aFieldIndex].VDouble); gftFMDate: if pfda^[aFieldIndex].VDouble > 0 then Result := FMDateTimeStr( FloatToStr(pfda^[aFieldIndex].VDouble), Fields[aFieldIndex].FMDTOptions); gftInteger: if Fields[aFieldIndex].Format <> '' then Result := Format( Fields[aFieldIndex].Format, [pfda^[aFieldIndex].VInteger]) else Result := IntToStr(pfda^[aFieldIndex].VInteger); gftString, gftMUMPS: if Fields[aFieldIndex].Format <> '' then Result := Format( Fields[aFieldIndex].Format, [pfda^[aFieldIndex].VString]) else Result := pfda^[aFieldIndex].VString; end; end; function TCCRTreeGrid.getAsBoolean(aNode: PVirtualNode; aFieldIndex: Integer): Boolean; var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin Result := False; pfda := GetNodeData(aNode); if aFieldIndex <= High(pfda^) then begin dt := GetDataType(aFieldIndex); if dt = gftMUMPS then dt := pfda^[aFieldIndex].MType; case dt of gftBoolean: Result := pfda^[aFieldIndex].VBoolean; gftDateTime: Result := (pfda^[aFieldIndex].VDateTime > 0); gftDouble: Result := (pfda^[aFieldIndex].VDouble <> 0); gftFMDate: Result := (pfda^[aFieldIndex].VDouble > 0); gftInteger: Result := (pfda^[aFieldIndex].VInteger <> 0); gftString: Result := StrToBoolDef(pfda^[aFieldIndex].VString, False); end; end; end; function TCCRTreeGrid.getAsDateTime(aNode: PVirtualNode; aFieldIndex: Integer): TDateTime; var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin Result := 0; pfda := GetNodeData(aNode); if aFieldIndex <= High(pfda^) then begin dt := GetDataType(aFieldIndex); if dt = gftMUMPS then dt := pfda^[aFieldIndex].MType; case dt of gftBoolean: Result := -1; gftDateTime: Result := pfda^[aFieldIndex].VDateTime; gftDouble, gftFMDate: Result := pfda^[aFieldIndex].VDouble; gftInteger: Result := pfda^[aFieldIndex].VInteger; gftString: Result := StrToFloatDef(pfda^[aFieldIndex].VString, 0); end; end; if Result < 0 then raise EConvertError.Create(RSC0020); end; function TCCRTreeGrid.getAsDouble(aNode: PVirtualNode; aFieldIndex: Integer): Double; var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin Result := 0; pfda := GetNodeData(aNode); if aFieldIndex <= High(pfda^) then begin dt := GetDataType(aFieldIndex); if dt = gftMUMPS then dt := pfda^[aFieldIndex].MType; case dt of gftBoolean: if pfda^[aFieldIndex].VBoolean then Result := 1 else Result := 0; gftDateTime: Result := pfda^[aFieldIndex].VDateTime; gftDouble, gftFMDate: Result := pfda^[aFieldIndex].VDouble; gftInteger: Result := pfda^[aFieldIndex].VInteger; gftString: Result := StrToFloatDef(pfda^[aFieldIndex].VString, 0); end; end; end; function TCCRTreeGrid.getAsInteger(aNode: PVirtualNode; aFieldIndex: Integer): Integer; var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin Result := 0; pfda := GetNodeData(aNode); if aFieldIndex <= High(pfda^) then begin dt := GetDataType(aFieldIndex); if dt = gftMUMPS then dt := pfda^[aFieldIndex].MType; case dt of gftBoolean: if pfda^[aFieldIndex].VBoolean then Result := 1 else Result := 0; gftDateTime: Result := Trunc(pfda^[aFieldIndex].VDateTime); gftDouble, gftFMDate: Result := Trunc(pfda^[aFieldIndex].VDouble); gftInteger: Result := pfda^[aFieldIndex].VInteger; gftString: Result := StrToIntDef(pfda^[aFieldIndex].VString, 0); end; end; end; function TCCRTreeGrid.getAsString(aNode: PVirtualNode; aFieldIndex: Integer): String; var pfda: PCCRFieldDataArray; begin Result := ''; if Assigned(aNode) then begin pfda := GetNodeData(aNode); if (aFieldIndex >= 0) and (aFieldIndex <= High(pfda^)) then Result := pfda^[aFieldIndex].VString; end; end; function TCCRTreeGrid.GetColumnClass: TVirtualTreeColumnClass; begin Result := TCCRTreeGridColumn; end; function TCCRTreeGrid.GetDataType(aFieldIndex: Integer): TCCRGridDataType; begin Result := gftUnknown; if (aFieldIndex >= 0) and (aFieldIndex < Header.Columns.Count) then Result := Fields[aFieldIndex].DataType; end; function TCCRTreeGrid.getField(aFieldIndex: Integer): TCCRTreeGridColumn; begin Result := inherited Header.Columns[aFieldIndex] as TCCRTreeGridColumn; end; function TCCRTreeGrid.getFormatted(aNode: PVirtualNode; aFieldIndex: Integer): String; begin if (aFieldIndex < 0) or (aFieldIndex >= Header.Columns.Count) then Result := '' else Result := formatFieldValue(aNode, aFieldIndex); end; procedure TCCRTreeGrid.GetRawData(RawData: TStrings; anIndexList: array of Integer; const Separator: String = '^'); var buf: String; vn: PVirtualNode; begin RawData.BeginUpdate; try RawData.Clear; vn := GetFirstChild(RootNode); while Assigned(vn) do begin buf := GetRawNodeData(vn, anIndexList, Separator); RawData.Add(buf); vn := getNextSibling(vn); end; finally RawData.EndUpdate; end; end; function TCCRTreeGrid.GetRawNodeData(aNode: PVirtualNode; anIndexList: array of Integer; const Separator: String = '^'): String; var i, ifld, lastFld: Integer; begin Result := ''; if Assigned(aNode) then begin lastFld := Header.Columns.Count - 1; for i:=0 to High(anIndexList) do begin ifld := anIndexList[i]; if (ifld >= 0) and (ifld <= lastFld) then Result := Result + AsString[aNode,ifld] + Separator else Result := Result + Separator; end; end; end; function TCCRTreeGrid.InsertNode(Node: PVirtualNode; Mode: TVTNodeAttachMode; UserData: Pointer): PVirtualNode; begin Result := inherited InsertNode(Node, Mode, UserData); if Assigned(Result) then ConstructNode(Result); end; procedure TCCRTreeGrid.LoadLayout(aStorage: TOvcAbstractStore; const aSection: String); var i, n, wd: Integer; begin try aStorage.Open; try n := Header.Columns.Count - 1; for i:=0 to n do begin wd := aStorage.ReadInteger(aSection, Fields[i].GetNamePath, -1); if wd >= 0 then Fields[i].Width := wd; end; finally aStorage.Close; end; except end; end; procedure TCCRTreeGrid.SaveLayout(aStorage: TOvcAbstractStore; const aSection: String); var i, n: Integer; begin try aStorage.Open; try n := Header.Columns.Count - 1; for i:=0 to n do aStorage.WriteInteger(aSection, Fields[i].GetNamePath, Fields[i].Width); finally aStorage.Close; end; except end; end; procedure TCCRTreeGrid.setAsBoolean(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Boolean); var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin if not Assigned(aNode) then Exit; dt := GetDataType(aFieldIndex); if dt = gftUnknown then Exit; pfda := GetNodeData(aNode); if aFieldIndex > High(pfda^) then SetLength(pfda^, aFieldIndex+1); if dt = gftMUMPS then begin pfda^[aFieldIndex].MType := gftDouble; dt := gftDouble; end; case dt of gftBoolean: pfda^[aFieldIndex].VBoolean := aValue; gftDateTime, gftFMDate: raise EConvertError.Create(RSC0020); gftDouble: if aValue then pfda^[aFieldIndex].VDouble := 1 else pfda^[aFieldIndex].VDouble := 0; gftInteger: if aValue then pfda^[aFieldIndex].VInteger := 1 else pfda^[aFieldIndex].VInteger := 0; gftString: pfda^[aFieldIndex].VString := BoolToStr(aValue); end; UpdateStringValues(aNode, aFieldIndex); end; procedure TCCRTreeGrid.setAsDateTime(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: TDateTime); begin setAsDouble(aNode, aFieldIndex, aValue); end; procedure TCCRTreeGrid.setAsDouble(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Double); var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin if not Assigned(aNode) then Exit; dt := GetDataType(aFieldIndex); if dt = gftUnknown then Exit; pfda := GetNodeData(aNode); if aFieldIndex > High(pfda^) then SetLength(pfda^, aFieldIndex+1); if dt = gftMUMPS then begin pfda^[aFieldIndex].MType := gftDouble; dt := gftDouble; end; case dt of gftBoolean: pfda^[aFieldIndex].VBoolean := (aValue <> 0); gftDateTime: pfda^[aFieldIndex].VDateTime := aValue; gftDouble, gftFMDate: pfda^[aFieldIndex].VDouble := aValue; gftInteger: pfda^[aFieldIndex].VInteger := Trunc(aValue); gftString: pfda^[aFieldIndex].VString := FloatToStr(aValue); end; UpdateStringValues(aNode, aFieldIndex); end; procedure TCCRTreeGrid.setAsInteger(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: Integer); var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin if not Assigned(aNode) then Exit; dt := GetDataType(aFieldIndex); if dt = gftUnknown then Exit; pfda := GetNodeData(aNode); if aFieldIndex > High(pfda^) then SetLength(pfda^, aFieldIndex+1); if dt = gftMUMPS then begin pfda^[aFieldIndex].MType := gftDouble; dt := gftDouble; end; case dt of gftBoolean: pfda^[aFieldIndex].VBoolean := (aValue <> 0); gftDateTime: pfda^[aFieldIndex].VDateTime := aValue; gftDouble, gftFMDate: pfda^[aFieldIndex].VDouble := aValue; gftInteger: pfda^[aFieldIndex].VInteger := aValue; gftString: pfda^[aFieldIndex].VString := IntToStr(aValue); end; UpdateStringValues(aNode, aFieldIndex); end; procedure TCCRTreeGrid.setAsString(aNode: PVirtualNode; aFieldIndex: Integer; const aValue: String); var dt: TCCRGridDataType; pfda: PCCRFieldDataArray; begin if not Assigned(aNode) then Exit; dt := GetDataType(aFieldIndex); if dt = gftUnknown then Exit; pfda := GetNodeData(aNode); if aFieldIndex > High(pfda^) then SetLength(pfda^, aFieldIndex+1); case dt of gftBoolean: pfda^[aFieldIndex].VBoolean := StrToBoolDef(aValue, False); gftDateTime: pfda^[aFieldIndex].VDateTime := StrToDateTimeDef(aValue, 0); gftDouble, gftFMDate: pfda^[aFieldIndex].VDouble := StrToFloatDef(aValue, 0); gftInteger: pfda^[aFieldIndex].VInteger := StrToIntDef(aValue, 0); gftMUMPS: try pfda^[aFieldIndex].VDouble := StrToFloat(aValue); pfda^[aFieldIndex].MType := gftDouble; except pfda^[aFieldIndex].VString := aValue; pfda^[aFieldIndex].MType := gftString; end; gftString: pfda^[aFieldIndex].VString := aValue; end; UpdateStringValues(aNode, aFieldIndex); end; procedure TCCRTreeGrid.setColor(const aColor: TColor); begin if aColor <> fColor then begin fColor := aColor; if Enabled then inherited Color := aColor; end; end; procedure TCCRTreeGrid.SetEnabled(aValue: Boolean); begin if aValue <> Enabled then begin inherited; if aValue then inherited Color := fColor else inherited Color := clBtnFace; end; end; procedure TCCRTreeGrid.SetRawNodeData(aNode: PVirtualNode; const RawData: String; anIndexList: array of Integer; const Separator: String = '^'); var i, ip, n: Integer; begin if not Assigned(aNode) then Exit; n := header.Columns.Count - 1; if n > High(anIndexList) then n := High(anIndexList); BeginItemUpdate(aNode); try for i:=0 to n do begin ip := anIndexList[i]; if ip > 0 then AsString[aNode,i] := Piece(RawData, Separator, ip); end; finally EndItemUpdate(aNode); end; end; procedure TCCRTreeGrid.SortData; var dir: TSortDirection; col: TColumnIndex; begin col := Header.SortColumn; dir := Header.SortDirection; if Assigned(OnSort) then OnSort(Self, col, dir) else SortTree(col, dir); end; procedure TCCRTreeGrid.UpdateStringValues(aNode: PVirtualNode; const aFieldIndex: Integer); var i, n: Integer; pfda: PCCRFieldDataArray; procedure update_field(const aFieldIndex: Integer); var dt: TCCRGridDataType; begin dt := GetDataType(aFieldIndex); if (dt = gftUnknown) or (aFieldIndex > High(pfda^)) then Exit; //--- Update the internal string value of the field with pfda^[aFieldIndex] do begin if dt = gftMUMPS then dt := MType; case dt of gftBoolean: VString := BoolToStr(VBoolean); gftDateTime: VString := FloatToStr(VDateTime); gftDouble, gftFMDate: VString := FloatToStr(VDouble); gftInteger: VString := IntToStr(VInteger); end; end; end; begin if not Assigned(aNode) then Exit; pfda := GetNodeData(aNode); if ItemUpdateLock = 0 then if aFieldIndex >= 0 then update_field(aFieldIndex) else begin n := Header.Columns.Count - 1; for i:=0 to n do update_field(i); end; end; ////////////////////////////// TCCRTreeGridColumn \\\\\\\\\\\\\\\\\\\\\\\\\\\\ constructor TCCRTreeGridColumn.Create(aCollection: TCollection); begin inherited; fAllowSort := True; fDataType := gftString; fFMDTOptions := fmdtShortDateTime; end; procedure TCCRTreeGridColumn.Assign(Source: TPersistent); begin if Source is TCCRTreeGridColumn then with TCCRTreeGridColumn(Source) do begin Self.AllowSort := AllowSort; Self.DataType := DataType; Self.FMDTOptions := FMDTOptions; Self.Format := Format; end; inherited; end; {$ENDIF} end.
unit UAFDefs; interface {------------------------type defintions-----------------------} Type UAF_FILE_TYPE = (UAF_TYPE_UNKNOWN, { Invalid or Unknow File } UAF_TYPE_ADF, { Bliss Audio Data Files } UAF_TYPE_WAV, { Microsoft RIFF wav Files } UAF_TYPE_AU, { Sun AU file format } UAF_TYPE_AIFF, { Apple Wave format } UAF_TYPE_RAW); { Raw input stream } Type UAF_File = Record FrameRate : Double; Channels : Word; Quantization : Word; Frames : LongInt; FrameSize : Word; FileRecord : Pointer; FileType : UAF_FILE_TYPE; SubType : Integer; FrameSizeIn : Word; { Just the input frame size } End; {---------------------Function and subroutines------------------------} Function UAF_open ( Var uaf : uaf_file; { ADF handle } fname : String; { File name to open } mode : char; { r,w for Read Write } ForceType : UAF_FILE_TYPE { If non-zero, force the type } ) : Boolean; external 'uafdll.dll'; Function UAF_create ( Var uaf : uaf_file; { ADF handle } fname : String; { File name to open } ftype : UAF_FILE_TYPE; { Type of audio file } subformat : Word; { Subtype } srate : Double; { Sampling rate } nchannels : Word; { Channels 1 or 2 } bits : Word { Bits /sample } ) : Boolean; external 'uafdll.dll'; Function UAF_close ( var uaf : uaf_file { ADF handle } ) : Boolean; external 'uafdll.dll'; Function UAF_read ( Var uaf : uaf_file; { ADF handle } buffer : Pointer; { Buffer } nFrames : LongInt; { how many words } lpos : LongInt { Position to read } ) : LongInt; external 'uafdll.dll'; Function UAF_write ( Var uaf : uaf_file; { ADF handle } buffer : Pointer; { Buffer } nFrames : LongInt; { how many words } lpos : LongInt { Position to read } ) : LongInt; external 'uafdll.dll'; Function UAF_CreateFromUAF(Var uafin, uafout : uaf_file; fname : String) : Boolean; external 'uafdll.dll'; Function UAF_SaveSection(Var uafin, uafout : uaf_file; lstart, lend : LongInt) : Boolean; external 'uafdll.dll'; Procedure UAF_Copy_Marks(Var uafin, uafout : uaf_file); external 'uafdll.dll'; Function FindMinMaxUAF(FileIn : String; Var Min, Max : Real; OverrideType : UAF_FILE_TYPE) : Boolean; external 'uafdll.dll'; Function UAFTypeFromExtension (fname : String) : UAF_FILE_TYPE; external 'uafdll.dll'; Function UAF_ErrorMessage : PChar; External 'uafdll.dll'; Function UAF_Identity(UAFIn : UAF_File) : PChar; External 'uafdll.dll'; Function UAF_Description(UAFIn : UAF_File) : PChar; External 'uafdll.dll'; implementation end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConfig.Consts; interface const strRedirectItem = 'RedirectItem'; strPublicPathsItem = 'PublicPathsItem'; strAuthorizationItem = 'AuthorizationItem'; strPackagesItem = 'PackagesItem'; strData = 'Data'; strServerLimits = 'Server.Limits'; strServerKeys = 'Server.Keys'; strServerConnectionDev = 'Server.Connection.Dev'; strServerAPICrossDomain = 'Server.APICrossDomain'; strServerThreadsDev = 'Server.Threads.Dev'; strServerEdgeHTTP = 'Server.EdgeHTTP'; strServerTenants = 'Server.Tenants'; strServerRoots = 'Server.Roots'; strServerPushGCM = 'Server.Push.GCM'; strServerPushAPNS = 'Server.Push.APNS'; strServerPublicPaths = 'Server.PublicPaths'; strServerRedirect = 'Server.Redirect'; strServerAuthorization = 'Server.Authorization'; strServerPackages = 'Server.Packages'; resourcestring strAddGroups = 'Add Groups'; strGroupPrompt = 'Group'; strAddUsers = 'Add Users'; strUserPrompt = 'User'; strResModuleFiles = 'Resource Module Files'; strAreYouSureExit = 'Are you sure you want to cancel without saving?'; strMimeInputQuery = 'Add MIME file type masks'; strFileExtInputQuery = 'Add File Extension'; strFileExtPrompt = 'Extension'; strMimePrompt = 'MIME Mask'; strSelectDirPrompt = 'Select Directory'; strRSLogFileDesc = 'RAD Server Log Files'; strKeyFileDesc = 'Key Files'; strRootCertFileDesc = 'Root Certificate Files'; strCertFileDesc = 'Certificate Files'; strConfigMissing = 'The configuration file does not exist.'; // Data strInstanceNameHelp = 'InterBase connection parameters'; strSEPasswordHelp = 'SEPassword connects to an encrypted database'; strPooledHelp = 'Set Pooled=0 to disable connection pooled, Pooled=1 to enable. Default value is 1.'; strPooledMax = 'Set PooledMax=10 to limit maximum pooled connection. Default value is 50.'; // Server strMaxConnectionsHelp = 'Set MaxConnections=10 to limit maximum concurrent HTTP requests. Default is 32.'; strMaxUsersHelp = 'Set MaxUsers=3 to limit the number of users in the EMS database. This value is only used when less than the maximum users permitted by the EMS runtime license.'; strMasterSecretHelp = 'MasterSecret may be blank. If blank then the EMS server will not support'; strAppSecretHelp = 'AppSecret may be blank. If AppSecret is not blank all requests must include the AppSecret.'; strApplicationIDHelp = 'ApplicationID may be blank. If ApplicationID is not blank, all requests must include the ApplicationID.'; strHTTPSHelp = 'The following options enable HTTPS support. Set HTTPS=1 to enable HTTPS, HTTPS=0 to disable.'; strRootCertFileHelp = 'When using a self-signed certificate, RootCertFile is left blank.'; strCrossDomainHelp = 'Write here the domains allowed to call the API. Used for Cross-Domains Set CrossDomain=* to allow access to any domain.'; strThreadPoolHelp = 'Set ThreadPool=1 to enable thread pool scheduler, ThreadPool=0 to disable.'; strThreadPoolSizeHelp = 'ThreadPoolSize indicates how many threads are available to handle requests'; strListenQueueHelp = 'ListenQueue indicates how many requests can be queued when all threads are busy'; strKeepAliveHelp = 'Set KeepAlive=1 to enable HTTP connections to keep alive, KeepAlive=0 to disable.'; strMultiTenantModeHelp = 'The MultiTenantMode option is used to turn on the Multi-Tenant mode. If the Multi-Tenant mode is turned on, then TenantId and TenantSecret is required to access EMS Server.'; strDefaultTenantIdHelp = 'Default Tenant is used only in the Single Tenant mode.'; strTenantIDCookieNameHelp = 'Define custom cookie name to store TenantId in EMS Console.'; strResourcesHelp = 'Specifies the root path for resources'; strServerLoggingAppendHelp = ''; // Push Notifications strApiKeyHelp = 'These settings are needed to send push notificatons to an Android device'; strApiURLHelp = 'Set send message REST API URL. Default value is https://fcm.googleapis.com/fcm/send'; strCertificateFileNameHelp = 'Name of .p12 or .pem file'; strCertificateFilePasswordHelp = 'Password of certificate file. Leave blank if file does not have a password.'; strProductionEnvironmentHelp = 'Set ProductionEnvironment=1 when the certificate has been created for production. Set ProductionEnvironment=0 when the certificate has been created for development. Default value is 0 (development).'; // Lists strPackagesHelp = 'This section is for extension packages. Extension packages are used to register custom resource endpoints'; strRedirectsHelp = 'This section is for setting resource redirects. Redirects cause custom resources to handle a client request, rather than the ' + 'resource identified in the request URL. A redirect may apply to all endpoints in a resource, or to a particular endpoint. ' + 'The destination resource must have an endpoint that handles the HTTP method (e.g.; GET, POST, PUT, DELETE) and URL segments of the client request. ' + 'Endpoint names are not used to resolve the destination endpoint.'; strPublicPathsHelp = 'This section is for directories that contain public files, such as .html. ' + 'The "directory" value indicates the physical location of the static files. ' + 'The optional "default" value indicates a file that will be dispatched by default when browsing to the root of the virtual directory. ' + 'The optional "mimes" value is an array of MIME file type masks. And optional "extensions" ' + 'value is an array of file extensions. Only these files will be accessible from this directory. ' + 'The optional "charset" value specifies default charset for the files in the directory.'; strAuthorizationHelp = 'This section is for setting authorization requirements for resources and endpoints. ' + 'Authorization can be set on built-in resource (e.g.; Users) and on custom resources. ' + 'Note that when MasterSecret authentication is used, these requirements are ignored. ' + 'Resource settings apply to all endpoints in the resource. ' + 'Endpoint settings override the settings for the resource. ' + 'By default, all resource are public.'; implementation end.
{***********************************<_INFO>************************************} { <Проект> Компоненты медиа-преобразования } { } { <Область> Мультимедиа } { } { <Задача> Преобразователь PCM. Декларация } { } { <Автор> Фадеев Р.В. } { } { <Дата> 21.01.2011 } { } { <Примечание> Отсутствует } { } { <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" } { } {***********************************</_INFO>***********************************} unit MediaProcessing.Transformer.PCM; interface uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global; type TMediaProcessor_Transformer_Pcm=class (TMediaProcessor,IMediaProcessor_Transformer_Pcm) private FSomeSetting : integer; //Пример настройки protected procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; class function MetaInfo:TMediaProcessorInfo; override; property SomeSetting : integer read FSomeSetting; public constructor Create; override; destructor Destroy; override; function HasCustomProperties: boolean; override; procedure ShowCustomProperiesDialog;override; end; implementation uses Controls,MediaProcessing.Transformer.Pcm.SettingsDialog; { TMediaProcessor_Transformer_Pcm } constructor TMediaProcessor_Transformer_Pcm.Create; begin inherited; end; //------------------------------------------------------------------------------ destructor TMediaProcessor_Transformer_Pcm.Destroy; begin inherited; end; //------------------------------------------------------------------------------ function TMediaProcessor_Transformer_Pcm.HasCustomProperties: boolean; begin result:=true; end; //------------------------------------------------------------------------------ class function TMediaProcessor_Transformer_Pcm.MetaInfo: TMediaProcessorInfo; begin result.Clear; result.TypeID:=IMediaProcessor_Transformer_Pcm; result.Name:='Преобразование'; result.Description:='Выполняет различные преобразования аудиопотока'; result.SetInputStreamType(stPCM); result.OutputStreamType:=stPCM; result.ConsumingLevel:=0; end; //------------------------------------------------------------------------------ procedure TMediaProcessor_Transformer_Pcm.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; FSomeSetting:=aReader.ReadInteger('SomeSetting',0); end; //------------------------------------------------------------------------------ procedure TMediaProcessor_Transformer_Pcm.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; aWriter.WriteInteger('SomeSetting', FSomeSetting); end; //------------------------------------------------------------------------------ procedure TMediaProcessor_Transformer_Pcm.ShowCustomProperiesDialog; var aDialog: TfmPcmTransformer_Settings; begin aDialog:=TfmPcmTransformer_Settings.Create(nil); try if aDialog.ShowModal=mrOK then begin //Разместите здесь свой код по сохранению настроек FSomeSetting:=1; end; finally aDialog.Free; end; end; initialization MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Transformer_Pcm); end.
unit uMaquina; interface uses uIMaquina, Classes, uTroco, System.Generics.Collections, System.Math; type TMaquinaDinheiro = class(TInterfacedObject, IMaquina) public function MontarTroco(aTroco: Double): TList; end; implementation function TMaquinaDinheiro.MontarTroco(aTroco: Double): TList; var LTroco : TTroco; LListaTroco : TList; LCedula : TCedula; LQuantidade : Integer; Troco : Double; begin LListaTroco := TList.Create; Troco := RoundTo(aTroco, -2); for LCedula := Low(CValorCedula) to High(CValorCedula) do begin LQuantidade := 0; while Troco >= CValorCedula[LCedula] do begin LQuantidade := LQuantidade + 1; Troco := Troco - CValorCedula[LCedula]; end; LTroco := TTroco.Create(LCedula, LQuantidade); LListaTroco.Add(LTroco); end; Result := LListaTroco; end; end.
unit Functions; interface uses Values, Variables, Codes, Strings; const STR_RETURN = 'ret'; type TFunctions = class; TFunction = class private FFunctions: TFunctions; FID: TID; FType_: TType_; FArguments: TArguments; FCode: TCode; function GetIndex(): Integer; public constructor Create(AFunctions: TFunctions; AIndex: Integer = -1); destructor Destroy(); override; function Compile(AText: String): Boolean; function Run(const AArguments: TValues; AClass: TValue = nil): TValue; overload; function Run(AClass: TValue = nil): TValue; overload; function Run(const AArguments: array of Variant; AClass: TValue = nil): TValue; overload; property Functions: TFunctions read FFunctions; property Index: Integer read GetIndex; property ID: TID read FID; property Type_: TType_ read FType_; property Arguments: TArguments read FArguments; property Code: TCode read FCode; end; TFunctionArray = array of TFunction; TFunctions = class private FFunctions: TFunctionArray; FOnDefine: TDefineProc; FOnVariable: TVariableFunc; FOnFunction: TFunctionFunc; FOnMethod: TFunctionFunc; function GetFunction(Index: Integer): TFunction; function GetCount(): Integer; procedure DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts = []); function DoVariable(const AID: TID): TValue; function DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; function DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue = nil): TValue; public constructor Create(); destructor Destroy(); override; procedure Add(AFunction: TFunction; AIndex: Integer = -1); procedure Delete(AIndex: Integer); procedure Clear(); function IndexOf(AFunction: TFunction): Integer; function FunctionByID(const AID: TID): TFunction; function Run(const AID: TID; const AArguments: TValues): TValue; overload; function Run(const AID: TID): TValue; overload; function Run(const AID: TID; const AArguments: array of Variant): TValue; overload; property Functions[Index: Integer]: TFunction read GetFunction; default; property Count: Integer read GetCount; property OnDefine: TDefineProc read FOnDefine write FOnDefine; property OnVariable: TVariableFunc read FOnVariable write FOnVariable; property OnFunction: TFunctionFunc read FOnFunction write FOnFunction; property OnMethod: TFunctionFunc read FOnMethod write FOnMethod; end; implementation uses SysUtils; { TFunction } { private } function TFunction.GetIndex(): Integer; begin if Assigned(FFunctions) then Result := FFunctions.IndexOf(Self) else Result := -1; end; { public } constructor TFunction.Create(AFunctions: TFunctions; AIndex: Integer); begin inherited Create(); FFunctions := nil; FID := ''; FType_ := TYPE_VOID; SetLength(FArguments, 0); FCode := TCode.Create(); if Assigned(AFunctions) then AFunctions.Add(Self, AIndex); end; destructor TFunction.Destroy; begin FCode.Free(); SetLength(FArguments, 0); inherited; end; function TFunction.Compile(AText: String): Boolean; var lHeader, lCode: String; function DoCompileHeader(): Boolean; var lName, lID, lType_: String; lExts: TType_Exts; lArguments: TStringArray; I: Integer; begin Cut(lHeader, lName, 1, Pos('(', lHeader) - 1); lName := Trim(lName); Type_ID(lName, lType_, lID); if lName = '' then Result := False else if Assigned(Functions) then Result := not Assigned(Functions.FunctionByID(lID)) else Result := True; if Result then begin FType_ := Values.Type_(lType_); FID := lID; Brackets(lHeader, ',', lArguments); SetLength(FArguments, High(lArguments) + 1); for I := 0 to High(lArguments) do begin Type_ID(lArguments[I], lType_, lID); lExts := []; if lType_ <> '' then while lType_[1] in Type_Exts do begin if lType_[1] = '$' then lExts := lExts + [teGlobal] else if lType_[1] = '@' then lExts := lExts + [teRef]; Delete(lType_, 1, 1); end; FArguments[I].ID := lID; FArguments[I].Type_ := Values.Type_(lType_); FArguments[I].Exts := lExts; end; end; end; { DoCompileHeader } begin FID := ''; FType_ := TYPE_VOID; SetLength(FArguments, 0); FCode.Clear(); Prepare(AText); if Pos(':', AText) = 0 then begin lCode := AText; Result := True; end else begin NameValue(AText, ':', lHeader, lCode); Result := DoCompileHeader(); end; if Result then Result := FCode.Compile(lCode); end; function TFunction.Run(const AArguments: TValues; AClass: TValue): TValue; var I, lReturn: Integer; begin FCode.Variables.Clear(); for I := 0 to High(FArguments) do FCode.Variables.Define(FArguments[I].ID, FArguments[I].Type_, FArguments[I].Exts).Value := AArguments[I]; if FType_ > TYPE_VOID then begin lReturn := FCode.Variables.Count; FCode.Variables.Define(STR_RETURN, FType_); end else lReturn := -1; FCode.RunAsBlock(AClass).Free(); if lReturn = -1 then Result := TValue.Create() else Result := ValueCopy(FCode.Variables[lReturn].Value); FCode.Variables.Clear(); if Result.Type_ < TYPE_VOID then begin Result.Free(); Result := TValue.Create(); end; end; function TFunction.Run(AClass: TValue): TValue; var I: Integer; lArguments: TValues; begin SetLength(lArguments, High(FArguments) + 1); for I := 0 to High(lArguments) do lArguments[I] := TValue.Create(FArguments[I].Type_); Result := Run(lArguments, AClass); for I := 0 to High(lArguments) do lArguments[I].Free(); SetLength(lArguments, 0); end; function TFunction.Run(const AArguments: array of Variant; AClass: TValue): TValue; var I: Integer; lArguments: TValues; begin SetLength(lArguments, High(AArguments) + 1); for I := 0 to High(lArguments) do begin lArguments[I] := TValue.Create(FArguments[I].Type_); lArguments[I].V := AArguments[I]; end; Result := Run(lArguments, AClass); for I := 0 to High(lArguments) do lArguments[I].Free(); SetLength(lArguments, 0); end; { TFunctions } { private } function TFunctions.GetFunction(Index: Integer): TFunction; begin if (Index < 0) or (Index > High(FFunctions)) then Result := nil else Result := FFunctions[Index]; end; function TFunctions.GetCount(): Integer; begin Result := High(FFunctions) + 1; end; procedure TFunctions.DoDefine(const AID: TID; AType_: TType_; AExts: TType_Exts); begin if Assigned(FOnDefine) then FOnDefine(AID, AType_, AExts); end; function TFunctions.DoVariable(const AID: TID): TValue; begin if Assigned(FOnVariable) then Result := FOnVariable(AID) else Result := nil; end; function TFunctions.DoFunction(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; var lFunction: TFunction; begin lFunction := FunctionByID(AID); if Assigned(lFunction) then Result := lFunction.Run(AArguments) else if Assigned(FOnFunction) then Result := FOnFunction(AID, AArguments, AClass) else Result := nil; end; function TFunctions.DoMethod(const AID: TID; const AArguments: TValues; AClass: TValue): TValue; begin if Assigned(FOnMethod) then Result := FOnMethod(AID, AArguments, AClass) else Result := nil; end; { public } constructor TFunctions.Create(); begin inherited Create(); SetLength(FFunctions, 0); FOnDefine := nil; FOnVariable := nil; FOnFunction := nil; FOnMethod := nil; end; destructor TFunctions.Destroy(); begin Clear(); inherited; end; procedure TFunctions.Add(AFunction: TFunction; AIndex: Integer); var I: Integer; begin if (AIndex < -1) or (AIndex > High(FFunctions) + 1) then Exit; if IndexOf(AFunction) > -1 then Exit; SetLength(FFunctions, High(FFunctions) + 2); if AIndex = -1 then AIndex := High(FFunctions) else for I := High(FFunctions) downto AIndex + 1 do FFunctions[I] := FFunctions[I - 1]; FFunctions[AIndex] := AFunction; AFunction.FFunctions := Self; AFunction.Code.OnDefine := DoDefine; AFunction.Code.OnVariable := DoVariable; AFunction.Code.OnFunction := DoFunction; AFunction.Code.OnMethod := DoMethod; end; procedure TFunctions.Delete(AIndex: Integer); var I: Integer; begin if (AIndex < 0) or (AIndex > High(FFunctions)) then Exit; FFunctions[AIndex].Free(); for I := AIndex to High(FFunctions) - 1 do FFunctions[I] := FFunctions[I + 1]; SetLength(FFunctions, High(FFunctions)); end; procedure TFunctions.Clear(); var I: Integer; begin for I := 0 to High(FFunctions) do FFunctions[I].Free(); SetLength(FFunctions, 0); end; function TFunctions.IndexOf(AFunction: TFunction): Integer; var I: Integer; begin Result := -1; for I := 0 to High(FFunctions) do if AFunction = FFunctions[I] then begin Result := I; Exit; end; end; function TFunctions.FunctionByID(const AID: TID): TFunction; var I: Integer; begin Result := nil; for I := High(FFunctions) downto 0 do if AID = FFunctions[I].ID then begin Result := FFunctions[I]; Exit; end; end; function TFunctions.Run(const AID: TID; const AArguments: TValues): TValue; var lFunction: TFunction; begin lFunction := FunctionByID(AID); if Assigned(lFunction) then Result := lFunction.Run(AArguments) else Result := TValue.Create(); end; function TFunctions.Run(const AID: TID): TValue; var I: Integer; lFunction: TFunction; lArguments: TValues; begin lFunction := FunctionByID(AID); if Assigned(lFunction) then begin SetLength(lArguments, High(lFunction.FArguments) + 1); for I := 0 to High(lArguments) do lArguments[I] := TValue.Create(lFunction.FArguments[I].Type_); Result := lFunction.Run(lArguments); for I := 0 to High(lArguments) do lArguments[I].Free; SetLength(lArguments, 0); end else Result := TValue.Create(); end; function TFunctions.Run(const AID: TID; const AArguments: array of Variant): TValue; var I: Integer; lFunction: TFunction; lArguments: TValues; begin lFunction := FunctionByID(AID); if Assigned(lFunction) then begin SetLength(lArguments, High(AArguments) + 1); for I := 0 to High(lArguments) do begin lArguments[I] := TValue.Create(lFunction.FArguments[I].Type_); lArguments[I].V := AArguments[I]; end; Result := lFunction.Run(lArguments); for I := 0 to High(lArguments) do lArguments[I].Free; SetLength(lArguments, 0); end else Result := TValue.Create(); end; end.
unit JSON; interface uses SysUtils; function getJsonStr(key, str: string):string; function getJsonInt(key, str: string):integer; function getJsonBool(key, str: string):boolean; function getJsonArray(key, str: string):string; implementation function getJsonStr(key, str: string):string; var keypos: byte; begin keypos := Pos(key, str); if keypos <> 0 then begin result := Copy(str, keypos + Length(key) + 3, MaxInt); result := Copy(result, 0, Pos('"', result) - 1); end else result := ''; end; function getJsonInt(key, str: string):integer; var res: string; keypos: byte; begin keypos := Pos(key, str); if keypos <> 0 then begin res := Copy(str, Pos(key, str) + Length(key) + 2, MaxInt); if Pos(',', res) > 0 then res := Copy(res, 0, Pos(',', res) - 1) else if Pos('}', res) > 0 then res := Copy(res, 0, Pos('}', res) - 1) else if Pos(']', res) > 0 then res := Copy(res, 0, Pos(']', res) - 1); result := StrToInt(res); end else result := 0; end; function getJsonBool(key, str: string):boolean; var res: string; keypos: byte; begin result := false; keypos := Pos(key, str); if keypos <> 0 then begin res := Copy(str, Pos(key, str) + Length(key) + 2, MaxInt); if Pos(',', res) > 0 then res := Copy(res, 0, Pos(',', res) - 1) else if Pos('}', res) > 0 then res := Copy(res, 0, Pos('}', res) - 1) else if Pos(']', res) > 0 then res := Copy(res, 0, Pos(']', res) - 1); if res = 'true' then result := true; end else result := false; end; function getJsonArray(key, str: string):string; var keypos: Byte; begin keypos := Pos(key, str); if keypos <> 0 then begin result := Copy(str, keypos + Length(key) + 3, MaxInt); result := Copy(result, 0, LastDelimiter(']', result) - 1); end else result := ''; end; end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFilePLY<p> PLY (Stanford Triangle Format) vector file format implementation.<p> <b>History :</b><font size=-1><ul> <li>16/10/08 - UweR - Compatibility fix for Delphi 2009 <li>31/03/07 - DaStr - Added $I GLScene.inc <li>05/06/03 - SG - Separated from GLVectorFileObjects.pas </ul></font> } unit GLFilePLY; interface {$I GLScene.inc} uses System.Classes, System.SysUtils, GLVectorFileObjects, GLApplicationFileIO, FileMD2, TypesMD2; type // TGLPLYVectorFile // {: The PLY vector file aka Stanford Triangle Format.<p> This is a format for storing graphical objects that are described as a collection of polygons. The format is extensible, supports variations and subformats. This importer only works for the simplest variant (triangles without specified normals, and will ignore most header specifications. } TGLPLYVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream : TStream); override; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses GLUtils; // ------------------ // ------------------ TGLPLYVectorFile ------------------ // ------------------ // Capabilities // class function TGLPLYVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead]; end; // LoadFromStream // procedure TGLPLYVectorFile.LoadFromStream(aStream : TStream); var i, nbVertices, nbFaces : Integer; sl : TStringList; mesh : TMeshObject; fg : TFGVertexIndexList; p : PChar; begin sl:=TStringList.Create; try sl.LoadFromStream(aStream{$IFDEF Unicode}, TEncoding.ASCII{$ENDIF}); mesh:=TMeshObject.CreateOwned(Owner.MeshObjects); mesh.Mode:=momFaceGroups; if sl[0]<>'ply' then raise Exception.Create('Not a valid ply file !'); nbVertices:=0; nbFaces:=0; i:=0; while i<sl.Count do begin if sl[i]='end_header' then Break; if Copy(sl[i], 1, 14)='element vertex' then nbVertices:=StrToIntDef(Copy(sl[i], 16, MaxInt), 0); if Copy(sl[i], 1, 12)='element face' then nbFaces:=StrToIntDef(Copy(sl[i], 14, MaxInt), 0); Inc(i); end; Inc(i); // vertices mesh.Vertices.Capacity:=nbVertices; while (i<sl.Count) and (nbVertices>0) do begin p:=PChar(sl[i]); mesh.Vertices.Add(ParseFloat(p), ParseFloat(p), ParseFloat(p));//AffineVectorMake(StrToFloatDef(tl[0]), StrToFloatDef(tl[1]), StrToFloatDef(tl[2])));} Dec(nbVertices); Inc(i); end; // faces fg:=TFGVertexIndexList.CreateOwned(mesh.FaceGroups); fg.Mode:=fgmmTriangles; fg.VertexIndices.Capacity:=nbFaces*3; while (i<sl.Count) and (nbFaces>0) do begin p:=PChar(sl[i]); ParseInteger(p); // skip index fg.VertexIndices.Add(ParseInteger(p), ParseInteger(p), ParseInteger(p)); Dec(nbFaces); Inc(i); end; mesh.BuildNormals(fg.VertexIndices, momTriangles); finally sl.Free; end; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('ply', 'Stanford triangle format', TGLPLYVectorFile); end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeSmoothFuncEdit; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, {$ENDIF} TeeSpline, TeeBaseFuncEdit, TeCanvas; type TSmoothFuncEditor = class(TBaseFunctionEditor) CBInterp: TCheckBox; Label1: TLabel; Edit1: TEdit; UpDown1: TUpDown; procedure CBInterpClick(Sender: TObject); private { Private declarations } protected procedure ApplyFormChanges; override; procedure SetFunction; override; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} procedure TSmoothFuncEditor.ApplyFormChanges; begin inherited; with TSmoothingFunction(IFunction) do begin Interpolate:=CBInterp.Checked; Factor:=UpDown1.Position; end; end; procedure TSmoothFuncEditor.SetFunction; begin inherited; if Assigned(IFunction) then with TSmoothingFunction(IFunction) do begin CBInterp.Checked:=Interpolate; UpDown1.Position:=Factor; end; end; procedure TSmoothFuncEditor.CBInterpClick(Sender: TObject); begin EnableApply; end; initialization RegisterClass(TSmoothFuncEditor); end.
program sort; const count = 500; type pair = record first : integer; second : integer end; pair_array = array [1 .. count] of pair; var tab : ^pair_array; tab_sorted : ^pair_array; a : integer; function mod(a : integer; b : integer) : integer; var c : integer; begin c := a div b; mod := a - (b * c) end; procedure generate_input(input : ^pair_array); const base = 991; modulus = 4001; var i : integer; c : integer; begin c := base; for i := 1 to count do begin input^[i].first := i; input^[i].second := c; c := c * base; c := mod(c, modulus) end end; procedure sort(input : ^pair_array; output : ^pair_array); var mask : array [1 .. count] of boolean; i : integer; j : integer; k : integer; l : integer; begin for i := 1 to count do mask[i] := true; for i := 1 to count do begin l := 10000000; k := -1; for j := 1 to count do if mask[j] and (input^[j].second < l) then begin l := input^[j].second; k := j end; mask[k] := false; output^[i].first := input^[k].first; output^[i].second := input^[k].second end end; function result_hash(result : ^pair_array) : integer; const base = 101; modulus = 10000019; var i : integer; c : integer; begin c := 0; for i := 1 to count do begin c := c * base; c := mod(c, modulus); c := c + (result^[i].first); c := mod(c, modulus) end; result_hash := c end; procedure print_array(a : ^pair_array); var i : integer; begin for i := 1 to count do begin putint(a^[i].first); putch(' '); putint(a^[i].second); putch(chr(10)) end end; begin tab := [pair_array]; tab_sorted := [pair_array]; generate_input(tab); sort(tab, tab_sorted); if result_hash(tab_sorted) = 5374486 then begin putch('O'); putch('K') end else begin putch('F'); putch('A'); putch('I'); putch('L') end; putch(chr(10)) end.
unit DelphiGenerics; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TQueue } generic TQueue<T> = class Items: array of T; {: Положить в очередь} procedure Enqueue(Value: T); {: Взять из очереди} function Dequeue: T; {: Количество элементов} function Count: integer; end; implementation { TQueue } procedure TQueue.Enqueue(Value: T); begin SetLength(Items, Length(Items) + 1); Items[Length(Items) - 1] := Value; end; function TQueue.Dequeue: T; var i: integer; begin Result := Items[0]; for i := Low(Items) to High(Items) - 1 do Items[i] := Items[i + 1]; SetLength(Items, Length(Items) - 1); end; function TQueue.Count: integer; begin Result := Length(Items); end; end.
unit YahtzeeServer; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses SyncObjs, Generics.Collections, Classes, IdGlobal, IdTCPConnection, YahtzeeClasses; type TConnectMessage = class(TObject) public Connection: TIdTCPConnection; Msg: TMessage; end; {$IFNDEF FPC} TConnectMessages = TThreadedQueue<TConnectMessage>; {$ELSE} TConnectMessages = TThreadList<TConnectMessage>; {$ENDIF} TServerDispatcher = class(TThread) protected procedure Execute; override; public end; TPlayer = class; TPlayersList = TThreadList<TPlayer>; TMessageTemplate = record Category: TMsgCategory; Method: Byte; end; TMessageList = class(TObject) Player: TPlayer; Name: AnsiString; Template: TMessageTemplate; Data: TQueue<AnsiString>; Process: Boolean; Complete: Boolean; Counter: Cardinal; constructor Create(APlayer: TPlayer); destructor Destroy; override; procedure ProcessList; procedure Elapsed; end; TMessageLists = TThreadList<TMessageList>; TZone = class(TObject) protected FPlayers: TPlayersList; function GetCount: Integer; function GetPlayers(AIndex: Integer): TPlayer; public Desc: AnsiString; constructor Create; virtual; destructor Destroy; override; class function Name: AnsiString; virtual; abstract; procedure Remove(APlayer: TPlayer); virtual; procedure Add(APlayer: TPlayer); virtual; function PlayerByConnection(AConnection: TIdTCPConnection): TPlayer; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); virtual; abstract; property PlayerCount: Integer read GetCount; property Players[AIndex: Integer]: TPlayer read GetPlayers; default; end; TSystemZone = class(TZone) public destructor Destroy; override; class function Name: AnsiString; override; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; function PlayerByName(AName: AnsiString): TPlayer; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; procedure PlayersKeepAliveDecrement(Ams: Integer); procedure PlayersKeepAliveExpire; end; TLimboZone = class(TZone) public class function Name: AnsiString; override; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; procedure BumpCounter; procedure ExpirePlayers; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; end; TLobbyZone = class; TLobbyRoom = class(TZone) public Lobby: TLobbyZone; Password: AnsiString; destructor Destroy; override; class function Name: AnsiString; override; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; end; TLobbyRooms = TThreadList<TLobbyRoom>; TLobbyZone = class(TZone) private FRooms: TLobbyRooms; public constructor Create; override; destructor Destroy; override; class function Name: AnsiString; override; function RoomByName(ADesc: AnsiString): TLobbyRoom; procedure RemoveRoom(ADesc: AnsiString); function AddRoom(ADesc, APassword: AnsiString): TLobbyRoom; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; end; TPlayZone = class; TPlaySlot = record Player: TPlayer; Name: AnsiString; State: TPlayerState; Score: Word; ScoreSheet: TScoreSheet; RollNo: Integer; Dice: TDice; Keepers: TDieSet; First: Boolean; FirstRoll: Integer; end; TPlayGame = class(TZone) public Play: TPlayZone; Password: AnsiString; Lock: TCriticalSection; State: TGameState; Round: Word; Turn: Integer; Slots: array[0..5] of TPlaySlot; SlotCount: Integer; ReadyCount: Integer; constructor Create; override; destructor Destroy; override; class function Name: AnsiString; override; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; procedure SendGameStatus(APlayer: TPlayer); procedure SendSlotStatus(APlayer: TPlayer; ASlot: Integer); end; TPlayGames = TThreadList<TPlayGame>; TPlayZone = class(TZone) private FGames: TPlayGames; public constructor Create; override; destructor Destroy; override; class function Name: AnsiString; override; function GameByName(ADesc: AnsiString): TPlayGame; procedure RemoveGame(ADesc: AnsiString); function AddGame(ADesc, APassword: AnsiString): TPlayGame; procedure Remove(APlayer: TPlayer); override; procedure Add(APlayer: TPlayer); override; procedure ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); override; end; TZoneClass = class of TZone; TZones = TThreadList<TZone>; {$IFNDEF FPC} TExpireZones = TThreadedQueue<TZone>; {$ELSE} TExpireZones = TThreadList<TZone>; {$ENDIF} {$IFNDEF FPC} TExpirePlayers = TThreadedQueue<TPlayer>; {$ELSE} TExpirePlayers = TThreadList<TPlayer>; {$ENDIF} TPlayer = class(TObject) public Connection: TIdTCPConnection; Zones: TZones; Name: AnsiString; Client: TNamedHost; Counter: Integer; KeepAliveCntr: Integer; NeedKeepAlive: Integer; SendKeepAlive: Boolean; Messages: TMessages; InputBuffer: TIdBytes; constructor Create(AConnection: TIdTCPConnection); destructor Destroy; override; procedure AddZone(AZone: TZone); procedure RemoveZone(AZone: TZone); procedure RemoveZoneByClass(AZoneClass: TZoneClass); procedure ClearZones; function FindZoneByClass(AZoneClass: TZoneClass): TZone; function FindZoneByNameDesc(AName, ADesc: AnsiString): TZone; procedure SendServerError(AMessage: AnsiString); procedure KeepAliveReset; procedure KeepAliveDecrement(Ams: Integer); end; procedure RollDice(ASet: TDieSet; var ADice: TDice); var SystemZone: TSystemZone; LimboZone: TLimboZone; LobbyZone: TLobbyZone; PlayZone: TPlayZone; // MessageLock: TCriticalSection; ServerMsgs: TConnectMessages; ServerDisp: TServerDispatcher; ListMessages: TMessageLists; ExpireZones: TExpireZones; ExpirePlayers: TExpirePlayers; const LIT_SYS_VERNAME: AnsiString = 'alpha'; {$IFDEF ANDROID} LIT_SYS_PLATFRM: AnsiString = 'android'; {$ELSE} {$IFDEF UNIX} {$IFDEF LINUX} LIT_SYS_PLATFRM: AnsiString = 'linux'; {$ELSE} LIT_SYS_PLATFRM: AnsiString = 'unix'; {$ENDIF} {$ELSE} LIT_SYS_PLATFRM: AnsiString = 'mswindows'; {$ENDIF} {$ENDIF} LIT_SYS_VERSION: AnsiString = '0.00.80A'; implementation uses SysUtils; const ARR_LIT_SYS_INFO: array[0..4] of AnsiString = ( 'Yahtzee development system', '--------------------------', 'Early alpha stage', 'By Daniel England', 'For Ecclestial Solutions'); LIT_ERR_CLIENTID: AnsiString = 'Invalid client ident'; LIT_ERR_CONNCTID: AnsiString = 'Invalid connect ident'; LIT_ERR_SERVERUN: AnsiString = 'Unrecognised command'; LIT_ERR_LBBYJINV: AnsiString = 'Invalid lobby join'; LIT_ERR_LBBYPINV: AnsiString = 'Invalid lobby part'; LIT_ERR_LBBYLINV: AnsiString = 'Invalid lobby list'; LIT_ERR_TEXTPINV: AnsiString = 'Invalid text peer'; LIT_ERR_PLAYJINV: AnsiString = 'Invalid play join'; LIT_ERR_PLAYPINV: AnsiString = 'Invalid play part'; LIT_ERR_PLAYLINV: AnsiString = 'Invalid play list'; LIT_ERR_PLAYPWDR: AnsiString = 'Play password mismatch'; LIT_ERR_PLAYGMST: AnsiString = 'Play in progress or full'; LIT_ERR_PLAYNORL: AnsiString = 'Play rolls complete'; procedure RollDice(ASet: TDieSet; var ADice: TDice); var i: Integer; begin for i:= 1 to 5 do if i in ASet then ADice[i - 1]:= Random(6) + 1; end; procedure DoDestroyListMessages; var i: Integer; begin with ListMessages.LockList do try for i:= Count - 1 downto 0 do Items[i].Free; Clear; finally ListMessages.UnlockList; end; ListMessages.Free; end; { TZone } procedure TZone.Add(APlayer: TPlayer); {$IFDEF FPC} var s: string; {$ENDIF} begin FPlayers.Add(APlayer); APlayer.Zones.Add(Self); {$IFNDEF FPC} DebugMsgs.PushItem('Client added to zone ' + Name + ' (' + Desc + ').'); {$ELSE} s:= 'Client added to zone ' + Name + ' (' + Desc + ').'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} end; constructor TZone.Create; begin inherited Create; FPlayers:= TPlayersList.Create; end; destructor TZone.Destroy; var {$IFDEF FPC} s: string; {$ENDIF} i: Integer; begin {$IFNDEF FPC} DebugMsgs.PushItem('Destroying zone ' + Name + ' (' + Desc + ')'); {$ELSE} s:= 'Destroying zone ' + Name + ' (' + Desc + ')'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} with FPlayers.LockList do try for i:= Count - 1 downto 0 do Remove(Items[i]); finally FPlayers.UnlockList; end; FPlayers.Free; inherited; end; function TZone.GetCount: Integer; begin with FPlayers.LockList do try Result:= Count; finally FPlayers.UnlockList; end; end; function TZone.GetPlayers(AIndex: Integer): TPlayer; begin with FPlayers.LockList do try Result:= Items[AIndex]; finally FPlayers.UnlockList; end; end; function TZone.PlayerByConnection(AConnection: TIdTCPConnection): TPlayer; var i: Integer; begin Result:= nil; with FPlayers.LockList do try for i:= 0 to Count - 1 do if Items[i].Connection = AConnection then begin Result:= Items[i]; Exit; end; finally FPlayers.UnlockList; end; end; procedure TZone.Remove(APlayer: TPlayer); {$IFDEF FPC} var s: string; {$ENDIF} begin FPlayers.Remove(APlayer); APlayer.Zones.Remove(Self); {$IFNDEF FPC} DebugMsgs.PushItem('Client removed from zone ' + Name + '(' + Desc + ').'); {$ELSE} s:= 'Client removed from zone ' + Name + '(' + Desc + ').'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} end; { TSystemZone } procedure TSystemZone.Add(APlayer: TPlayer); begin inherited; LimboZone.Add(APlayer); end; destructor TSystemZone.Destroy; begin inherited; end; class function TSystemZone.Name: AnsiString; begin Result:= 'system'; end; function TSystemZone.PlayerByName(AName: AnsiString): TPlayer; var i: Integer; begin Result:= nil; with FPlayers.LockList do try for i:= 0 to Count - 1 do if CompareText(string(Items[i].Name), string(AName)) = 0 then begin Result:= Items[i]; Exit; end; finally FPlayers.UnlockList; end; end; procedure TSystemZone.PlayersKeepAliveDecrement(Ams: Integer); var i: Integer; begin with FPlayers.LockList do try for i:= 0 to Count - 1 do if not Assigned(LimboZone.PlayerByConnection(Items[i].Connection)) then Items[i].KeepAliveDecrement(Ams); finally FPlayers.UnlockList; end; end; procedure TSystemZone.PlayersKeepAliveExpire; var i: Integer; begin with FPlayers.LockList do try for i:= Count - 1 downto 0 do if Items[i].NeedKeepAlive <= 0 then Self.Remove(Items[i]); finally FPlayers.UnlockList; end; end; procedure TSystemZone.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var i: Integer; a: TPlayer; m: TMessage; n: AnsiString; ml: TMessageList; begin if (AMessage.Category = mcText) and (AMessage.Method = 0) then begin ml:= TMessageList.Create(APlayer); for i:= 0 to High(ARR_LIT_SYS_INFO) do ml.Data.Enqueue(ARR_LIT_SYS_INFO[i]); m:= TMessage.Create; m.Category:= mcText; m.Method:= $01; m.Params.Add(ml.Name); m.Params.Add(AnsiString(ARR_LIT_NAM_CATEGORY[mcSystem])); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} ListMessages.Add(ml); AHandled:= True; end else if (AMessage.Category = mcSystem) then begin APlayer.Connection.Disconnect; AHandled:= True; end else if (AMessage.Category = mcText) and (AMessage.Method = $02) then begin AHandled:= True; AMessage.ExtractParams; if AMessage.Params.Count > 0 then begin n:= Copy(AMessage.Params[0], 1, 8); with ListMessages.LockList do try for i:= 0 to Count - 1 do begin ml:= Items[i]; if CompareText(string(ml.Name), string(n)) = 0 then begin if not ml.Complete then ml.Process:= True; Break; end; end; finally ListMessages.UnlockList; end; end; end else if (AMessage.Category = mcText) and (AMessage.Method = $04) then begin AMessage.ExtractParams; if AMessage.Params.Count > 0 then begin n:= Copy(AMessage.Params[0], 1, 8); a:= PlayerByName(n); if Assigned(a) then begin m:= TMessage.Create; m.Assign(AMessage); m.Params[0]:= APlayer.Name; m.DataFromParams; {$IFNDEF FPC} a.Messages.PushItem(m); {$ELSE} a.Messages.Add(m); {$ENDIF} end; end else APlayer.SendServerError(LIT_ERR_TEXTPINV); AHandled:= True; end else if (AMessage.Category = mcConnect) and (AMessage.Method = 1) then begin AMessage.ExtractParams; if (AMessage.Params.Count = 1) and (Length(AMessage.Params[0]) > 1) then begin n:= Copy(AMessage.Params[0], 1, 8); a:= PlayerByName(n); if not Assigned(a) then begin m:= TMessage.Create; m.Assign(AMessage); m.Params.Add(APlayer.Name); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} APlayer.Name:= n; end else APlayer.SendServerError(LIT_ERR_CONNCTID); end else APlayer.SendServerError(LIT_ERR_CONNCTID); AHandled:= True; end else if (AMessage.Category = mcClient) and (AMessage.Method = 2) then begin APlayer.KeepAliveReset; AHandled:= True; end; end; procedure TSystemZone.Remove(APlayer: TPlayer); begin inherited; APlayer.ClearZones; // if Assigned(APlayer.Connection) // and APlayer.Connection.Connected then // APlayer.Connection.Disconnect; {$IFNDEF FPC} ExpirePlayers.PushItem(APlayer); {$ELSE} ExpirePlayers.Add(APlayer); {$ENDIF} end; { TLimboZone } procedure TLimboZone.Add(APlayer: TPlayer); begin inherited; APlayer.Counter:= 0; end; procedure TLimboZone.BumpCounter; var i: Integer; p: TPlayer; {$IFDEF FPC} s: string; {$ENDIF} begin with FPlayers.LockList do try for i:= 0 to Count - 1 do begin p:= Items[i]; {$IFNDEF FPC} DebugMsgs.PushItem('Bumping client auth wait count.'); {$ELSE} s:= 'Bumping client auth wait count.'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} p.Counter:= p.Counter + 1; end; finally FPlayers.UnlockList; end; end; procedure TLimboZone.ExpirePlayers; var i: Integer; p: TPlayer; {$IFDEF FPC} s: string; {$ENDIF} begin with FPlayers.LockList do try for i:= Count - 1 downto 0 do begin p:= Items[i]; if Assigned(p.Client) and (Length(p.Name) > 0) then begin {$IFNDEF FPC} DebugMsgs.PushItem('Client auth move to lobby/play.'); {$ELSE} s:= 'Client auth move to lobby/play.'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} LimboZone.Remove(p); LobbyZone.Add(p); PlayZone.Add(p); end else if p.Counter >= 600 then begin {$IFNDEF FPC} DebugMsgs.PushItem('Client auth failure.'); {$ELSE} s:= 'Client auth failure.'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} p.Connection.Disconnect; end; end; finally FPlayers.UnlockList; end; end; class function TLimboZone.Name: AnsiString; begin Result:= 'limbo'; end; procedure TLimboZone.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var c: TNamedHost; begin if (AMessage.Category = mcClient) and (AMessage.Method = 1) then begin if not Assigned(APlayer.Client) then begin AMessage.ExtractParams; if AMessage.Params.Count = 3 then begin c:= TNamedHost.Create; c.Name:= AMessage.Params[0]; c.Host:= AMessage.Params[1]; c.Version:= AMessage.Params[2]; APlayer.Client:= c; end else APlayer.SendServerError(LIT_ERR_CLIENTID); end else APlayer.SendServerError(LIT_ERR_CLIENTID); AHandled:= True; end; end; procedure TLimboZone.Remove(APlayer: TPlayer); begin inherited; end; { TLobbyRoom } procedure TLobbyRoom.Add(APlayer: TPlayer); var i: Integer; procedure JoinMessageFromPeer(APeer: TPlayer; AName: AnsiString); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $01; m.Params.Add(Desc); m.Params.Add(AName); m.DataFromParams; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin inherited; with FPlayers.LockList do try for i:= 0 to Count - 1 do JoinMessageFromPeer(Items[i], APlayer.Name); finally FPlayers.UnlockList; end; end; destructor TLobbyRoom.Destroy; begin // FDisposing:= True; if Assigned(Lobby) then Lobby.RemoveRoom(Desc); inherited; end; class function TLobbyRoom.Name: AnsiString; begin Result:= 'room'; end; procedure TLobbyRoom.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var i: Integer; procedure PeerMessageFromPlayer(APeer: TPlayer; AMessage: TMessage); var m: TMessage; begin m:= TMessage.Create; m.Assign(AMessage); m.Category:= mcLobby; m.Method:= $04; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin if AMessage.Category = mcLobby then if AMessage.Method = 4 then begin AMessage.ExtractParams; if (AMessage.Params.Count > 2) and (CompareText(string(Desc), string(AMessage.Params[0])) = 0) then begin AMessage.Params[1]:= Copy(AMessage.Params[1], Low(AnsiString), 8); AMessage.DataFromParams; with FPlayers.LockList do try for i:= 0 to Count - 1 do PeerMessageFromPlayer(Items[i], AMessage); finally FPlayers.UnlockList; end; AHandled:= True; end; end; end; procedure TLobbyRoom.Remove(APlayer: TPlayer); var i: Integer; procedure PartMessageFromPeer(APeer: TPlayer; AName: AnsiString); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $02; m.Params.Add(Desc); m.Params.Add(AName); m.DataFromParams; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin with FPlayers.LockList do try for i:= 0 to Count - 1 do PartMessageFromPeer(Items[i], APlayer.Name); finally FPlayers.UnlockList; end; inherited; if PlayerCount = 0 then {$IFNDEF FPC} ExpireZones.PushItem(Self); {$ELSE} ExpireZones.Add(Self); {$ENDIF} end; { TPlayer } procedure TPlayer.AddZone(AZone: TZone); begin Zones.Add(AZone); end; procedure TPlayer.ClearZones; var i: Integer; z: TZone; begin with Zones.LockList do try for i:= Count - 1 downto 0 do begin z:= Items[i]; z.Remove(Self); end; finally Zones.UnlockList; end; end; constructor TPlayer.Create(AConnection: TIdTCPConnection); begin inherited Create; Zones:= TZones.Create; Zones.Duplicates:= dupError; Connection:= AConnection; Name:= ''; Client:= nil; KeepAliveReset; {$IFNDEF FPC} Messages:= TMessages.Create(128); {$ELSE} Messages:= TMessages.Create; {$ENDIF} end; destructor TPlayer.Destroy; var m: TMessage; begin {$IFNDEF FPC} while Messages.QueueSize > 0 do begin m:= Messages.PopItem; m.Free; end; {$ELSE} with Messages.LockList do try while Count > 0 do begin m:= Items[0]; Delete(0); m.Free; end; finally Messages.UnlockList; end; {$ENDIF} if Assigned(Client) then Client.Free; Messages.Free; Zones.Free; inherited; end; function TPlayer.FindZoneByClass(AZoneClass: TZoneClass): TZone; var i: Integer; begin Result:= nil; with Zones.LockList do try for i:= 0 to Count - 1 do if Items[i] is AZoneClass then begin Result:= Items[i]; Exit; end; finally Zones.UnlockList; end; end; function TPlayer.FindZoneByNameDesc(AName, ADesc: AnsiString): TZone; var i: Integer; begin Result:= nil; with Zones.LockList do try for i:= 0 to Count - 1 do if (CompareText(string(Items[i].Name), string(AName)) = 0) and (CompareText(string(Items[i].Desc), string(ADesc)) = 0) then begin Result:= Items[i]; Exit; end; finally Zones.UnlockList; end; end; procedure TPlayer.KeepAliveDecrement(Ams: Integer); var m: TMessage; begin if KeepAliveCntr > 0 then Dec(KeepAliveCntr, Ams) else begin if SendKeepAlive then begin SendKeepAlive:= False; m:= TMessage.Create; m.Category:= mcServer; m.Method:= 2; {$IFNDEF FPC} Messages.PushItem(m); {$ELSE} Messages.Add(m); {$ENDIF} end; Dec(NeedKeepAlive, Ams); end; end; procedure TPlayer.KeepAliveReset; begin KeepAliveCntr:= 10000; NeedKeepAlive:= 5000; SendKeepAlive:= True; end; procedure TPlayer.RemoveZone(AZone: TZone); begin AZone.Remove(Self); end; procedure TPlayer.RemoveZoneByClass(AZoneClass: TZoneClass); var z: TZone; begin repeat z:= FindZoneByClass(AZoneClass); if Assigned(z) then z.Remove(Self); until not Assigned(z); end; procedure TPlayer.SendServerError(AMessage: AnsiString); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcServer; m.Method:= 0; m.Params.Add(AMessage); m.DataFromParams; {$IFNDEF FPC} Messages.PushItem(m); {$ELSE} Messages.Add(m); {$ENDIF} end; { TLobbyZone } procedure TLobbyZone.Add(APlayer: TPlayer); begin inherited; end; function TLobbyZone.AddRoom(ADesc, APassword: AnsiString): TLobbyRoom; begin Result:= RoomByName(ADesc); if not Assigned(Result) then begin Result:= TLobbyRoom.Create; Result.Desc:= ADesc; Result.Lobby:= Self; Result.Password:= APassword; FRooms.Add(Result); end; end; constructor TLobbyZone.Create; begin inherited; FRooms:= TLobbyRooms.Create; end; destructor TLobbyZone.Destroy; var i: Integer; begin with FRooms.LockList do try for i:= Count - 1 downto 0 do begin Items[i].Lobby:= nil; Items[i].Free; end; finally FRooms.UnlockList; end; FRooms.Free; inherited; end; class function TLobbyZone.Name: AnsiString; begin Result:= 'lobby'; end; procedure TLobbyZone.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var r: TLobbyRoom; s: AnsiString; m: TMessage; ml: TMessageList; i: Integer; p: AnsiString; begin if AMessage.Category = mcLobby then if AMessage.Method = 1 then begin AMessage.ExtractParams; if (AMessage.Params.Count > 0) and (AMessage.Params.Count < 3) then begin s:= Copy(AMessage.Params[0], Low(AnsiString), 8); r:= RoomByName(AMessage.Params[0]); if AMessage.Params.Count = 2 then p:= AMessage.Params[1] else p:= ''; if not Assigned(r) then r:= AddRoom(s, p); if CompareText(string(p), string(r.Password)) = 0 then with APlayer.Zones.LockList do try if not Contains(r) then r.Add(APlayer); finally APlayer.Zones.UnlockList; end else begin m:= TMessage.Create; m.Category:= mcLobby; m.Method:= $00; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; end else APlayer.SendServerError(LIT_ERR_LBBYJINV); AHandled:= True; end else if AMessage.Method = 2 then begin AMessage.ExtractParams; r:= RoomByName(AMessage.Params[0]); if Assigned(r) then r.Remove(APlayer) else APlayer.SendServerError(LIT_ERR_LBBYPINV); AHandled:= True; end else if AMessage.Method = $03 then begin AHandled:= True; AMessage.ExtractParams; r:= nil; if AMessage.Params.Count > 0 then begin r:= RoomByName(AMessage.Params[0]); if not Assigned(r) then begin APlayer.SendServerError(LIT_ERR_LBBYLINV); Exit; end; end; ml:= TMessageList.Create(APlayer); if AMessage.Params.Count > 0 then with r.FPlayers.LockList do try if (Length(r.Password) = 0) or Contains(APlayer) then for i:= 0 to Count - 1 do ml.Data.Enqueue(Items[i].Name); finally r.FPlayers.UnlockList; end else with FRooms.LockList do try for i:= 0 to Count - 1 do if Length(Items[i].Password) = 0 then ml.Data.Enqueue(Items[i].Desc); finally FRooms.UnlockList; end; m:= TMessage.Create; m.Category:= mcText; m.Method:= $01; m.Params.Add(ml.Name); m.Params.Add(AnsiString(ARR_LIT_NAM_CATEGORY[mcLobby])); if AMessage.Params.Count > 0 then m.Params.Add(r.Desc); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} ListMessages.Add(ml); end end; procedure TLobbyZone.Remove(APlayer: TPlayer); begin inherited; APlayer.RemoveZoneByClass(TLobbyRoom); end; procedure TLobbyZone.RemoveRoom(ADesc: AnsiString); var r: TLobbyRoom; begin r:= RoomByName(ADesc); if Assigned(r) then FRooms.Remove(r); end; function TLobbyZone.RoomByName(ADesc: AnsiString): TLobbyRoom; var i: Integer; begin Result:= nil; with FRooms.LockList do try for i:= 0 to Count - 1 do if CompareText(string(Items[i].Desc), string(ADesc)) = 0 then begin Result:= Items[i]; Exit; end; finally FRooms.UnlockList; end; end; { TServerDispatcher } procedure TServerDispatcher.Execute; var cm: TConnectMessage; p: TPlayer; handled: Boolean; z: TZone; i: Integer; {$IFDEF FPC} s: string; {$ENDIF} begin while not Terminated do begin Sleep(100); {$IFNDEF FPC} if ServerMsgs.QueueSize > 0 then begin cm:= ServerMsgs.PopItem; {$ELSE} cm:= nil; with ServerMsgs.LockList do try if Count > 0 then begin cm:= Items[0]; Delete(0); end; finally ServerMsgs.UnlockList; end; if Assigned(cm) then begin {$ENDIF} try p:= SystemZone.PlayerByConnection(cm.Connection); handled:= False; z:= nil; with p.Zones.LockList do try for i:= 0 to Count - 1 do begin z:= Items[i]; z.ProcessPlayerMessage(p, cm.Msg, handled); if handled then Break; z:= nil; end; finally p.Zones.UnlockList; end; if handled then begin p.KeepAliveReset; {$IFNDEF FPC} DebugMsgs.PushItem('Handled in ' + z.Name + ' zone.') {$ELSE} s:= 'Handled in ' + z.Name + ' zone.'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} end else begin p.SendServerError(LIT_ERR_SERVERUN); {$IFNDEF FPC} DebugMsgs.PushItem('Unhandled message.'); {$ELSE} s:= 'Unhandled message.'; UniqueString(s); DebugMsgs.Add(s); {$ENDIF} end; finally cm.Msg.Free; cm.Free; end; end; end; end; { TMessageList } constructor TMessageList.Create(APlayer: TPlayer); var s: AnsiString; i, u, p: Integer; f: Boolean; begin inherited Create; Player:= APlayer; s:= APlayer.Name; p:= Length(s) + 1; if p > 8 then p:= 8; if Length(s) < p then SetLength(s, p); Dec(p); u:= 0; repeat s[p + Low(AnsiString)]:= AnsiChar(u + Ord(AnsiChar('0'))); f:= False; with ListMessages.LockList do try for i:= 0 to Count - 1 do if CompareText(string(Items[i].Name), string(s)) = 0 then begin f:= True; Break; end; finally ListMessages.UnlockList; end; if not f then begin Name:= s; end else Inc(u); until (not f) or (u > 9); if u > 9 then raise Exception.Create('Out of room for Message List on client!'); Data:= TQueue<AnsiString>.Create; Template.Category:= mcText; Template.Method:= $03; Process:= True; Complete:= False; end; destructor TMessageList.Destroy; begin Data.Free; inherited; end; procedure TMessageList.Elapsed; begin Inc(Counter); if Counter >= 6000 then Complete:= True; end; procedure TMessageList.ProcessList; var c: Integer; m: TMessage; begin c:= 0; while (Data.Count > 0) and (c < 15) do begin m:= TMessage.Create; m.Category:= Template.Category; m.Method:= Template.Method; m.Params.Add(Name); m.Params.Add(Data.Dequeue); m.DataFromParams; {$IFNDEF FPC} Player.Messages.PushItem(m); {$ELSE} Player.Messages.Add(m); {$ENDIF} Inc(c); end; m:= TMessage.Create; m.Category:= mcText; m.Method:= $02; m.Params.Add(Name); m.Params.Add(AnsiString(IntToStr(Data.Count))); m.DataFromParams; {$IFNDEF FPC} Player.Messages.PushItem(m); {$ELSE} Player.Messages.Add(m); {$ENDIF} Process:= False; Complete:= Data.Count = 0; Counter:= 0; end; { TPlayGame } procedure TPlayGame.Add(APlayer: TPlayer); var i: Integer; s: Integer; // m: TMessage; procedure JoinMessageFromPeer(APeer: TPlayer; AName: AnsiString; ASlot: Integer); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $01; m.Params.Add(Desc); m.Params.Add(AName); m.Params.Add(AnsiChar(ASlot + $30)); // m.Params.Add(AnsiChar(Ord(State))); m.DataFromParams; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin Lock.Acquire; try if SlotCount < 6 then begin Inc(SlotCount); inherited; s:= -1; for i:= 0 to 5 do if not Assigned(Slots[i].Player) then begin s:= i; FillChar(Slots[i], SizeOf(TPlaySlot), 0); FillChar(Slots[i].ScoreSheet, SizeOf(TScoreSheet), $FF); Slots[i].Player:= APlayer; Slots[i].Name:= APlayer.Name; Slots[i].State:= psIdle; Break; end; Assert(s > -1, 'Failure in Play Game Add Player'); for i:= 0 to 5 do if Assigned(Slots[i].Player) then JoinMessageFromPeer(Slots[i].Player, APlayer.Name, s); SendGameStatus(APlayer); end; finally Lock.Release; end; end; constructor TPlayGame.Create; var i: Integer; begin inherited; Lock:= TCriticalSection.Create; for i:= 0 to 5 do FillChar(Slots[i].ScoreSheet, SizeOf(TScoreSheet), $FF); end; destructor TPlayGame.Destroy; begin if Assigned(Play) then Play.RemoveGame(Desc); Lock.Free; inherited; end; class function TPlayGame.Name: AnsiString; begin Result:= 'game'; end; procedure TPlayGame.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var s, i, j: Integer; p: TPlayerState; m: TMessage; f: Boolean; d: TDieSet; n: TScoreLocation; r: Word; u: TDieSet; o: TScoreLocation; procedure PeerMessageFromPlayer(APeer: TPlayer; AMessage: TMessage); var m: TMessage; begin m:= TMessage.Create; m.Assign(AMessage); m.Category:= mcPlay; m.Method:= $04; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin if AMessage.Category = mcPlay then if AMessage.Method = 4 then begin AMessage.ExtractParams; if (AMessage.Params.Count > 2) and (CompareText(string(Desc), string(AMessage.Params[0])) = 0) then begin AMessage.Params[1]:= Copy(AMessage.Params[1], Low(AnsiString), 8); AMessage.DataFromParams; with FPlayers.LockList do try for i:= 0 to Count - 1 do PeerMessageFromPlayer(Items[i], AMessage); finally FPlayers.UnlockList; end; AHandled:= True; end; end else if AMessage.Method = $07 then begin // AMessage.ExtractParams; AHandled:= True; // if AMessage.Params.Count = 2 then if Length(AMessage.Data) = 2 then begin Lock.Acquire; try // s:= Ord(AMessage.Params[0][Low(AnsiString)]); s:= AMessage.Data[0]; if (s > 5) or (s < 0) then Exit; // p:= TPlayerState(Ord(AMessage.Params[1][Low(AnsiString)])); p:= TPlayerState(AMessage.Data[1]); if (State >= gsPreparing) or (p = psNone) then Exit else if (p = psIdle) and (Slots[s].State = psReady) then Dec(ReadyCount) else if (p = psReady) and (Slots[s].State = psIdle) then Inc(ReadyCount); f:= False; if (State = gsWaiting) and (SlotCount > 1) and (ReadyCount = SlotCount) then begin f:= True; State:= gsPreparing; p:= psPreparing; ReadyCount:= 0; for i:= 0 to 5 do if Slots[i].State = psReady then Slots[i].State:= p; end; Slots[s].State:= p; if not f then for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, s); if f then begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then for j:= 0 to 5 do SendSlotStatus(Slots[i].Player, j); for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendGameStatus(Slots[i].Player); end; finally Lock.Release; end; end; end else if AMessage.Method = $08 then begin // AMessage.ExtractParams; AHandled:= True; // if AMessage.Params.Count = 2 then if Length(AMessage.Data) = 2 then begin Lock.Acquire; try // s:= Ord(AMessage.Params[0][Low(AnsiString)]); // d:= ByteToDieSet(Ord(AMessage.Params[1][Low(AnsiString)])); s:= AMessage.Data[0]; d:= ByteToDieSet(AMessage.Data[1]); if Slots[s].State = psPreparing then begin RollDice(VAL_SET_DICEALL, Slots[s].Dice); Slots[s].FirstRoll:= 0; for i:= 0 to 4 do Slots[s].FirstRoll:= Slots[s].FirstRoll + Slots[s].Dice[i]; Inc(ReadyCount); end else begin if Slots[s].RollNo = 3 then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $00; m.Params.Add(LIT_ERR_PLAYNORL); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} Exit; end; if Slots[s].RollNo = 0 then d:= VAL_SET_DICEALL; RollDice(d, Slots[s].Dice); Slots[s].RollNo:= Slots[s].RollNo + 1; // YAHTZEE BONANZA! // for i:= 1 to 4 do // Slots[s].Dice[i]:= Slots[s].Dice[0]; end; for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; SetLength(m.Data, 6); // m.Params.Add(AnsiChar(Ord(s))); m.Data[0]:= s; for j:= 0 to 4 do // m.Params.Add(AnsiChar(Slots[s].Dice[j])); m.Data[1 + j]:= Slots[s].Dice[j]; // m.DataFromParams; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; if Slots[s].State = psPreparing then begin Slots[s].State:= psWaiting; for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, s); end; if (State = gsPreparing) and (ReadyCount = SlotCount) then begin s:= 0; j:= Slots[0].FirstRoll; for i:= 1 to 5 do if Slots[i].FirstRoll > j then begin s:= i; j:= Slots[i].FirstRoll; end; Slots[s].First:= True; Slots[s].State:= psPlaying; Slots[s].RollNo:= 0; Round:= 1; Turn:= s; for i:= 0 to 4 do Slots[s].Dice[i]:= 0; State:= gsPlaying; for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendGameStatus(Slots[i].Player); for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin SendSlotStatus(Slots[i].Player, s); m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; SetLength(m.Data, 6); m.Data[0]:= s; for j:= 0 to 4 do m.Data[1 + j]:= Slots[s].Dice[j]; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; finally Lock.Release; end; end; end else if AMessage.Method = $09 then begin AHandled:= True; if Length(AMessage.Data) = 3 then begin Lock.Acquire; try s:= AMessage.Data[0]; // d:= AMessage.Data[1]; f:= Boolean(AMessage.Data[2]); if (Turn = s) and (Slots[s].RollNo > 0) then begin if f then Include(Slots[s].Keepers, AMessage.Data[1]) else Exclude(Slots[s].Keepers, AMessage.Data[1]); for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Assign(AMessage); {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; finally Lock.Release; end; end; end else if AMessage.Method = $0A then begin AHandled:= True; if Length(AMessage.Data) = 2 then begin Lock.Acquire; try s:= AMessage.Data[0]; n:= TScoreLocation(AMessage.Data[1]); u:= []; r:= VAL_KND_SCOREINVALID; o:= slAces; if (Turn = s) and (Slots[s].RollNo > 0) then if IsYahtzee(Slots[s].Dice) then begin if IsYahtzeeBonus(Slots[s].ScoreSheet, o) then begin if n in YahtzeeBonusStealLocs(Slots[s].ScoreSheet, Slots[s].Dice) then r:= YahtzeeBonusStealScore(n, Slots[s].Dice); end else if (n = slYahtzee) and (Slots[s].ScoreSheet[slYahtzee] = VAL_KND_SCOREINVALID) then r:= 50; end else if Slots[s].ScoreSheet[n] = VAL_KND_SCOREINVALID then r:= MakeScoreForLocation(n, Slots[s].Dice, u); m:= TMessage.Create; m.Assign(AMessage); SetLength(m.Data, Length(m.Data) + 2); m.Data[2]:= Hi(r); m.Data[3]:= Lo(r); {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} if o > slAces then begin m:= TMessage.Create; m.Assign(AMessage); SetLength(m.Data, Length(m.Data) + 2); m.Data[1]:= Ord(o); m.Data[2]:= Hi(100); m.Data[3]:= Lo(100); {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; finally Lock.Release; end; end; end else if AMessage.Method = $0B then begin AHandled:= True; if Length(AMessage.Data) = 2 then begin Lock.Acquire; try s:= AMessage.Data[0]; n:= TScoreLocation(AMessage.Data[1]); u:= []; r:= VAL_KND_SCOREINVALID; o:= slAces; if (Turn = s) and (Slots[s].RollNo > 0) then if IsYahtzee(Slots[s].Dice) then begin if IsYahtzeeBonus(Slots[s].ScoreSheet, o) then begin if n in YahtzeeBonusStealLocs(Slots[s].ScoreSheet, Slots[s].Dice) then r:= YahtzeeBonusStealScore(n, Slots[s].Dice); end else if (n = slYahtzee) and (Slots[s].ScoreSheet[slYahtzee] = VAL_KND_SCOREINVALID) then r:= 50; end else if Slots[s].ScoreSheet[n] = VAL_KND_SCOREINVALID then r:= MakeScoreForLocation(n, Slots[s].Dice, u); if r <> VAL_KND_SCOREINVALID then begin Slots[s].ScoreSheet[n]:= r; Slots[s].Score:= Slots[s].Score + r; for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Assign(AMessage); SetLength(m.Data, Length(m.Data) + 2); m.Data[2]:= Hi(r); m.Data[3]:= Lo(r); {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; if (n in [slAces..slSixes]) and (Slots[s].ScoreSheet[slUpperBonus] = VAL_KND_SCOREINVALID) then begin r:= 0; for i:= Ord(slAces) to Ord(slSixes) do if Slots[s].ScoreSheet[TScoreLocation(i)] = VAL_KND_SCOREINVALID then begin r:= VAL_KND_SCOREINVALID; Break; end else Inc(r, Slots[s].ScoreSheet[TScoreLocation(i)]); if r <> VAL_KND_SCOREINVALID then begin if r > 63 then r:= 35 else r:= 0; Slots[s].ScoreSheet[slUpperBonus]:= r; Slots[s].Score:= Slots[s].Score + r; for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Assign(AMessage); SetLength(m.Data, Length(m.Data) + 2); m.Data[1]:= Ord(slUpperBonus); m.Data[2]:= Hi(r); m.Data[3]:= Lo(r); {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; end; if o > slAces then begin Slots[s].ScoreSheet[o]:= 100; Slots[s].Score:= Slots[s].Score + 100; for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Assign(AMessage); SetLength(m.Data, Length(m.Data) + 2); m.Data[1]:= Ord(o); m.Data[2]:= Hi(100); m.Data[3]:= Lo(100); {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; if Turn = s then begin Slots[s].State:= psWaiting; Slots[s].RollNo:= 0; f:= False; while True do begin Inc(Turn); if Turn > 5 then Turn:= 0; if Slots[Turn].First then begin f:= True; Inc(Round); if Round > 13 then begin State:= gsFinished; Turn:= -1; r:= 0; for i:= 0 to 5 do if Slots[i].Score > r then r:= Slots[i].Score; for i:= 0 to 5 do if Slots[i].State > psIdle then if Slots[i].Score = r then Slots[i].State:= psWinner else Slots[i].State:= psFinished; Break; end; end; if Assigned(Slots[Turn].Player) and (Slots[Turn].State = psWaiting) then Break; end; if Turn > -1 then begin Slots[Turn].State:= psPlaying; Slots[Turn].Keepers:= []; for i:= 0 to 4 do Slots[Turn].Dice[i]:= 0; Slots[Turn].RollNo:= 0; end; if f and (State = gsFinished) then begin for i:= 0 to 5 do for j:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, j); end else begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, s); for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, Turn); for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; SetLength(m.Data, 6); m.Data[0]:= Turn; for j:= 0 to 4 do m.Data[1 + j]:= Slots[Turn].Dice[j]; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} for j:= 1 to 5 do begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $09; SetLength(m.Data, 3); m.Data[0]:= Turn; m.Data[1]:= j; m.Data[2]:= 0; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; end; if f then begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendGameStatus(Slots[i].Player); end; end; end; finally Lock.Release; end; end; end; end; procedure TPlayGame.Remove(APlayer: TPlayer); var i, j: Integer; s: Integer; r: Integer; m: TMessage; f: Boolean; procedure PartMessageFromPeer(APeer: TPlayer; AName: AnsiString; ASlot: Integer); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $02; m.Params.Add(Desc); m.Params.Add(AName); m.Params.Add(AnsiString(IntToStr(ASlot))); m.DataFromParams; {$IFNDEF FPC} APeer.Messages.PushItem(m); {$ELSE} APeer.Messages.Add(m); {$ENDIF} end; begin Lock.Acquire; try s:= -1; for i:= 0 to 5 do if Slots[i].Player = APlayer then begin s:= i; Break; end; if s = -1 then Exit; Dec(SlotCount); for i:= 0 to 5 do if Assigned(Slots[i].Player) then PartMessageFromPeer(Slots[i].Player, APlayer.Name, s); Slots[s].Player:= nil; f:= False; if State = gsFinished then // Do nothing - dummy message will be sent else if State = gsPreparing then begin Slots[s].State:= psNone; if SlotCount = 1 then begin ReadyCount:= 0; f:= True; State:= gsWaiting; for i:= 0 to 5 do if Assigned(Slots[i].Player) then Slots[i].State:= psIdle; end; end else if State > gsPreparing then begin if Slots[s].State = psPlaying then begin //dengland Optimise this with handling in message $0B, above while True do begin Inc(Turn); if Turn > 5 then Turn:= 0; if Slots[Turn].First then begin f:= True; Inc(Round); if Round > 13 then begin State:= gsFinished; Turn:= -1; r:= 0; for i:= 0 to 5 do if Slots[i].Score > r then r:= Slots[i].Score; for i:= 0 to 5 do if Slots[i].State > psIdle then if Slots[i].Score = r then Slots[i].State:= psWinner else Slots[i].State:= psFinished; Break; end; end; if Assigned(Slots[Turn].Player) and (Slots[Turn].State = psWaiting) then Break; end; if Turn > -1 then begin Slots[Turn].State:= psPlaying; Slots[Turn].Keepers:= []; for i:= 0 to 4 do Slots[Turn].Dice[i]:= 0; Slots[Turn].RollNo:= 0; end; if f and (State = gsFinished) then begin for i:= 0 to 5 do for j:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, j); end else begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, s); for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, Turn); for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $08; SetLength(m.Data, 6); m.Data[0]:= Turn; for j:= 0 to 4 do m.Data[1 + j]:= Slots[Turn].Dice[j]; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} for j:= 1 to 5 do begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $09; SetLength(m.Data, 3); m.Data[0]:= Turn; m.Data[1]:= j; m.Data[2]:= 0; {$IFNDEF FPC} Slots[i].Player.Messages.PushItem(m); {$ELSE} Slots[i].Player.Messages.Add(m); {$ENDIF} end; end; end; if f then begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendGameStatus(Slots[i].Player); end; end; if State <> gsFinished then begin Slots[s].State:= psFinished; if SlotCount = 1 then begin f:= True; State:= gsFinished; for i:= 0 to 5 do if Assigned(Slots[i].Player) then Slots[i].State:= psWinner; end; end; end else Slots[s].State:= psNone; //dengland This is really nasty when the game has ended or control otherwise changed // due to the currently playing player leaving if not f then begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then SendSlotStatus(Slots[i].Player, s); end else begin for i:= 0 to 5 do if Assigned(Slots[i].Player) then begin for j:= 0 to 5 do SendSlotStatus(Slots[i].Player, j); SendGameStatus(Slots[i].Player); end; end; finally Lock.Release; end; inherited; if PlayerCount = 0 then {$IFNDEF FPC} ExpireZones.PushItem(Self); {$ELSE} ExpireZones.Add(Self); {$ENDIF} end; procedure TPlayGame.SendGameStatus(APlayer: TPlayer); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $06; // m.Params.Add(AnsiChar(Ord(State))); // m.Params.Add(AnsiChar(Hi(Round)) + AnsiChar(Lo(Round))); SetLength(m.Data, 3); m.Data[0]:= Ord(State); m.Data[1]:= Hi(Round); m.Data[2]:= Lo(Round); // m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; procedure TPlayGame.SendSlotStatus(APlayer: TPlayer; ASlot: Integer); var m: TMessage; begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $07; // m.Params.Add(AnsiChar(j)); // m.Params.Add(AnsiChar(Slots[j].State)); // m.Params.Add(AnsiChar(Hi(Slots[j].Score)) + // AnsiChar(Lo(Slots[j].Score))); // // m.DataFromParams; SetLength(m.Data, 4); m.Data[0]:= ASlot; m.Data[1]:= Ord(Slots[ASlot].State); m.Data[2]:= Hi(Slots[ASlot].Score); m.Data[3]:= Lo(Slots[ASlot].Score); {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; { TPlayZone } procedure TPlayZone.Add(APlayer: TPlayer); begin inherited; end; function TPlayZone.AddGame(ADesc, APassword: AnsiString): TPlayGame; begin Result:= GameByName(ADesc); if not Assigned(Result) then begin Result:= TPlayGame.Create; Result.Desc:= ADesc; Result.Play:= Self; Result.Password:= APassword; FGames.Add(Result); end; end; constructor TPlayZone.Create; begin inherited; FGames:= TPlayGames.Create; end; destructor TPlayZone.Destroy; var i: Integer; begin with FGames.LockList do try for i:= Count - 1 downto 0 do begin Items[i].Play:= nil; Items[i].Free; end; finally FGames.UnlockList; end; FGames.Free; inherited; end; function TPlayZone.GameByName(ADesc: AnsiString): TPlayGame; var i: Integer; begin Result:= nil; with FGames.LockList do try for i:= 0 to Count - 1 do if CompareText(string(Items[i].Desc), string(ADesc)) = 0 then begin Result:= Items[i]; Exit; end; finally FGames.UnlockList; end; end; class function TPlayZone.Name: AnsiString; begin result:= 'play'; end; procedure TPlayZone.ProcessPlayerMessage(APlayer: TPlayer; AMessage: TMessage; var AHandled: Boolean); var g: TPlayGame; d: AnsiString; m: TMessage; ml: TMessageList; i: Integer; p: AnsiString; f: Boolean; s: Integer; begin if AMessage.Category = mcPlay then if AMessage.Method = 1 then begin AHandled:= True; AMessage.ExtractParams; if (AMessage.Params.Count > 0) and (AMessage.Params.Count < 3) then begin d:= Copy(AMessage.Params[0], Low(AnsiString), 8); g:= GameByName(AMessage.Params[0]); if AMessage.Params.Count = 2 then p:= AMessage.Params[1] else p:= ''; if not Assigned(g) then g:= AddGame(d, p); if CompareText(string(p), string(g.Password)) = 0 then begin g.Lock.Acquire; try if (g.State < gsPreparing) and (g.SlotCount < 6) then begin g.Add(APlayer); s:= -1; for i:= 0 to 5 do begin if (Assigned(g.Slots[i].Player)) or (g.Slots[i].State > psPlaying) then g.SendSlotStatus(APlayer, i); if g.Slots[i].Player = APlayer then s:= i; end; Assert(s > -1, 'Failure in handling join in play zone.'); for i:= 0 to 5 do if (Assigned(g.Slots[i].Player)) and (g.Slots[i].Player <> APlayer) then g.SendSlotStatus(g.Slots[i].Player, s); end else begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $00; m.Params.Add(LIT_ERR_PLAYGMST); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; finally g.Lock.Release; end; end else begin m:= TMessage.Create; m.Category:= mcPlay; m.Method:= $00; m.Params.Add(LIT_ERR_PLAYPWDR); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} end; end else APlayer.SendServerError(LIT_ERR_PLAYJINV); end else if AMessage.Method = 2 then begin AMessage.ExtractParams; g:= GameByName(AMessage.Params[0]); if Assigned(g) then begin g.Remove(APlayer); end else APlayer.SendServerError(LIT_ERR_PLAYPINV); AHandled:= True; end else if AMessage.Method = $03 then begin AHandled:= True; AMessage.ExtractParams; g:= nil; if AMessage.Params.Count > 0 then begin g:= GameByName(AMessage.Params[0]); if not Assigned(g) then begin APlayer.SendServerError(LIT_ERR_PLAYLINV); Exit; end; end; ml:= TMessageList.Create(APlayer); if AMessage.Params.Count > 0 then begin g.Lock.Acquire; try f:= False; for i:= 0 to 5 do if g.Slots[i].Player = APlayer then begin f:= True; Break; end; if f or (Length(g.Password) = 0) then for i:= 0 to 5 do if Assigned(g.Slots[i].Player) then ml.Data.Enqueue(g.Slots[i].Name + ' ' + AnsiChar(i + $30)); finally g.Lock.Release; end end else with FGames.LockList do try for i:= 0 to Count - 1 do if Length(Items[i].Password) = 0 then ml.Data.Enqueue(Items[i].Desc); finally FGames.UnlockList; end; m:= TMessage.Create; m.Category:= mcText; m.Method:= $01; m.Params.Add(ml.Name); m.Params.Add(AnsiString(ARR_LIT_NAM_CATEGORY[mcPlay])); if AMessage.Params.Count > 0 then m.Params.Add(g.Desc); m.DataFromParams; {$IFNDEF FPC} APlayer.Messages.PushItem(m); {$ELSE} APlayer.Messages.Add(m); {$ENDIF} ListMessages.Add(ml); end end; procedure TPlayZone.Remove(APlayer: TPlayer); begin APlayer.RemoveZoneByClass(TPlayGame); end; procedure TPlayZone.RemoveGame(ADesc: AnsiString); var g: TPlayGame; begin g:= GameByName(ADesc); if Assigned(g) then FGames.Remove(g); end; initialization Randomize; {$IFNDEF FPC} ExpireZones:= TExpireZones.Create(100); {$ElSE} ExpireZones:= TExpireZones.Create; {$ENDIF} {$IFNDEF FPC} ExpirePlayers:= TExpirePlayers.Create(512); {$ElSE} ExpirePlayers:= TExpirePlayers.Create; {$ENDIF} ListMessages:= TMessageLists.Create; {$IFNDEF FPC} ServerMsgs:= TConnectMessages.Create(512); {$ELSE} ServerMsgs:= TConnectMessages.Create; {$ENDIF} ServerDisp:= TServerDispatcher.Create(False); SystemZone:= TSystemZone.Create; LimboZone:= TLimboZone.Create; LobbyZone:= TLobbyZone.Create; PlayZone:= TPlayZone.Create; finalization {$IFNDEF FPC} while ExpirePlayers.QueueSize > 0 do ExpirePlayers.PopItem.Free; {$ELSE} with ExpirePlayers.LockList do try while Count > 0 do begin Items[0].Free; Delete(0); end; finally ExpirePlayers.UnlockList; end; {$ENDIF} {$IFNDEF FPC} while ExpireZones.QueueSize > 0 do ExpireZones.PopItem.Free; {$ELSE} with ExpireZones.LockList do try while Count > 0 do begin Items[0].Free; Delete(0); end; finally ExpireZones.UnlockList; end; {$ENDIF} {$IFNDEF FPC} while ServerMsgs.QueueSize > 0 do with ServerMsgs.PopItem do begin Msg.Free; Free; end; {$ELSE} with ServerMsgs.LockList do try while Count > 0 do begin Items[0].Msg.Free; Items[0].Free; Delete(0); end; finally ServerMsgs.UnlockList; end; {$ENDIF} ServerDisp.Terminate; ServerDisp.WaitFor; ServerDisp.Free; ServerMsgs.Free; DoDestroyListMessages; ExpireZones.Free; PlayZone.Free; LobbyZone.Free; LimboZone.Free; SystemZone.Free; // MessageLock.Free; end.
unit SettingsTestFieldsUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testutils, testregistry, LKSL_Settings_Fields; type { TSettingsTestFields } TSettingsTestFields= class(TTestCase) private FFields: TLKSettingsFields; protected procedure SetUp; override; procedure TearDown; override; published procedure TestFieldsCount; procedure TestFieldsClear; procedure TestFieldIntegerValue; procedure TestFieldStringValue; procedure TestFieldIntegerType; procedure TestFieldStringType; end; implementation procedure TSettingsTestFields.TestFieldsCount; var FieldInt: TLKSettingsFieldInteger; begin FieldInt:= TLKSettingsFieldInteger.Create(FFields); FFields.Add(FieldInt); AssertEquals('Number of fields in list.', 1, FFields.Count); end; procedure TSettingsTestFields.TestFieldsClear; var FieldInt: TLKSettingsFieldInteger; FieldStr: TLKSettingsFieldString; begin FieldInt:= TLKSettingsFieldInteger.Create(FFields); FFields.Add(FieldInt); FieldStr:= TLKSettingsFieldString.Create(FFields); FFields.Add(FieldStr); AssertEquals('Inserted fields in list.', 2, FFields.Count); FFields.Clear; AssertEquals('Cleared Number of fields in list.', 0, FFields.Count); end; procedure TSettingsTestFields.TestFieldIntegerValue; var FieldInt: TLKSettingsFieldInteger; begin FieldInt:= TLKSettingsFieldInteger.Create(FFields); FieldInt.Value:= 10; AssertEquals('Integer field value.', 10, FieldInt.Value); FieldInt.Free; end; procedure TSettingsTestFields.TestFieldStringValue; var FieldStr: TLKSettingsFieldString; begin FieldStr:= TLKSettingsFieldString.Create(FFields); FieldStr.Value:= 'Testing string value'; AssertEquals('String Field Value.', 'Testing string value', FieldStr.Value); FieldStr.Free; end; procedure TSettingsTestFields.TestFieldIntegerType; var FieldInt: TLKSettingsFieldInteger; begin FieldInt:= TLKSettingsFieldInteger.Create(FFields); AssertTrue('Integer field type.', sftInteger = FieldInt.FieldType); FieldInt.Free; end; procedure TSettingsTestFields.TestFieldStringType; var FieldStr: TLKSettingsFieldString; begin FieldStr:= TLKSettingsFieldString.Create(FFields); AssertTrue('String field type.', sftString = FieldStr.FieldType); FieldStr.Free; end; procedure TSettingsTestFields.SetUp; begin FFields:= TLKSettingsFields.Create(nil); end; procedure TSettingsTestFields.TearDown; begin FFields.Free; end; initialization RegisterTest(TSettingsTestFields); end.
{------------------------------------------------------------------------------- Сохранение видео/аудио потока на диск -------------------------------------------------------------------------------} unit MediaStream.Writer.Tsm; {$ALIGN ON} {$MINENUMSIZE 4} {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, SysUtils, Classes, SyncObjs, Graphics, Messages,Controls,MediaProcessing.Definitions,TsmFile; type TMediaStreamWriter_Tsm = class private FStream: TStream; FOwnStream : boolean; FFileName: string; FHeader : TTsmHeader; FIndexTable : array of TTsmIndexTableItem; FIndexTableLength : integer; procedure GrowIndexTable; procedure CompleteWriting; procedure UpdateHeader; procedure CheckOpened; procedure InternalWriteData(const aFormat: TMediaStreamDataHeader;aData: pointer; aDataSize: cardinal); public //Открыть файл для записи procedure Open(const aFileName: string); function Opened: boolean; //Ассоциировать себя с потоком procedure AssignToStream(aStream: TStream); procedure EnableVideo(aStreamType: TStreamType; aStreamSubType: DWORD; aWidth: DWORD; aHeight: DWORD; aBitCount: Word); procedure EnableAudio(aStreamType: TStreamType; aStreamSubType: DWORD; aChannels: Byte; aBitsPerSample: Word; aSamplesPerSec: DWORD); //Закрыть файл procedure Close; procedure WriteData(const aFormat: TMediaStreamDataHeader;aData: pointer; aDataSize: cardinal); procedure CheckDataCompartibility(const aFormat: TMediaStreamDataHeader;aData: pointer; aDataSize: cardinal); constructor Create; overload; constructor Create (const aFileName: string); overload; constructor Create (const aStream: TStream); overload; destructor Destroy; override; property Stream: TStream read FStream; function VideoFramesWrittenCount :int64; function AudioFramesWrittenCount :int64; end; implementation uses Math,Forms; function TMediaStreamWriter_Tsm.Opened: boolean; begin result:=FStream<>nil; end; procedure TMediaStreamWriter_Tsm.UpdateHeader; var aPos: int64; begin aPos:=FStream.Position; FStream.Seek(0,soFromBeginning); FStream.WriteBuffer(FHeader,sizeof(FHeader)); FStream.Seek(aPos,soFromBeginning); end; function TMediaStreamWriter_Tsm.VideoFramesWrittenCount: int64; begin result:=FHeader.VideoFrameCount; end; { TMediaStreamWriter_Tsm } constructor TMediaStreamWriter_Tsm.Create; begin inherited; end; constructor TMediaStreamWriter_Tsm.Create(const aFileName: string); begin Create; Open(aFileName); end; constructor TMediaStreamWriter_Tsm.Create(const aStream: TStream); begin Create; AssignToStream(aStream); end; destructor TMediaStreamWriter_Tsm.Destroy; begin Close; inherited; end; procedure TMediaStreamWriter_Tsm.EnableAudio(aStreamType: TStreamType; aStreamSubType: DWORD; aChannels: Byte; aBitsPerSample: Word; aSamplesPerSec: DWORD); begin if (FHeader.AudioStreamType=aStreamType) and (FHeader.AudioStreamSubType=aStreamSubType) and (FHeader.AudioChannels=aChannels) and (FHeader.AudioBitsPerSample=aBitsPerSample) and (FHeader.AudioSamplesPerSec=aSamplesPerSec) then exit; if (FHeader.AudioFrameCount<>0) then raise Exception.Create('Не допускается смена формата после начала записи'); FHeader.AudioStreamType:=aStreamType; FHeader.AudioStreamSubType:=aStreamSubType; FHeader.AudioChannels:=aChannels; FHeader.AudioBitsPerSample:=aBitsPerSample; FHeader.AudioSamplesPerSec:=aSamplesPerSec; end; procedure TMediaStreamWriter_Tsm.EnableVideo(aStreamType: TStreamType; aStreamSubType, aWidth, aHeight: DWORD; aBitCount: Word); begin if (FHeader.VideoStreamType=aStreamType) and (FHeader.VideoStreamSubType=aStreamSubType) and (FHeader.VideoWidth=aWidth) and (FHeader.VideoHeight=aHeight) and (FHeader.VideoBitCount=aBitCount) then exit; if (FHeader.VideoFrameCount<>0) then raise Exception.Create('Не допускается смена формата после начала записи'); FHeader.VideoStreamType:=aStreamType; FHeader.VideoStreamSubType:=aStreamSubType; FHeader.VideoWidth:=aWidth; FHeader.VideoHeight:=aHeight; FHeader.VideoBitCount:=aBitCount; end; procedure TMediaStreamWriter_Tsm.GrowIndexTable; begin if Length(FIndexTable)=FIndexTableLength then SetLength(FIndexTable,Length(FIndexTable)+25*60*20); //20 Минут Assert(Length(FIndexTable)>FIndexTableLength); end; procedure TMediaStreamWriter_Tsm.InternalWriteData(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal); var aTimeStamp: int64; aFrameHeader: TTsmFrameHeader; aExtension: TTsmFrameHeaderExtension; begin CheckDataCompartibility(aFormat,aData,aDataSize); GrowIndexTable; aTimeStamp:=aFormat.TimeStamp*aFormat.TimeKoeff; aFrameHeader.Marker:=0; aExtension.StreamType:=aFormat.biStreamType; aExtension.StreamSubType:=aFormat.biStreamSubType; aExtension.Channel:=aFormat.Channel; aExtension.TimestampHigh:=(aTimeStamp shr 32); aExtension.Tag:=aFormat.Tag; if aFormat.biMediaType=mtVideo then begin if (FHeader.VideoFrameCount>0) and (aTimeStamp<FHeader.VideoFirstTimeStamp) then raise Exception.CreateFmt('Нарушен порядок следования временных отсчетов Video. Первый отсчет в файле=%d; Переданный отсчет=%d',[FHeader.VideoFirstTimeStamp,aTimeStamp]); FIndexTable[FIndexTableLength].SetDataTypeAndKey(TsmDataTypeVideo,ffKeyFrame in aFormat.biFrameFlags); FIndexTable[FIndexTableLength].TimestampOffs:=aTimeStamp-FHeader.VideoFirstTimeStamp; FIndexTable[FIndexTableLength].StreamPosition:=FStream.Position; inc(FHeader.VideoFrameCount); end else if aFormat.biMediaType=mtAudio then begin if (FHeader.AudioFrameCount>0) and (aTimeStamp<FHeader.AudioFirstTimeStamp) then raise Exception.CreateFmt('Нарушен порядок следования временных отсчетов Audio. Первый отсчет в файле=%d; Переданный отсчет=%d',[FHeader.AudioFirstTimeStamp,aTimeStamp]); FIndexTable[FIndexTableLength].SetDataTypeAndKey(TsmDataTypeAudio,ffKeyFrame in aFormat.biFrameFlags); FIndexTable[FIndexTableLength].TimestampOffs:=aTimeStamp-FHeader.AudioFirstTimeStamp; FIndexTable[FIndexTableLength].StreamPosition:=FStream.Position; inc(FHeader.AudioFrameCount); end else if aFormat.biMediaType=mtSysData then begin //if (FHeader.AudioFrameCount>0) and (aTimeStamp<FHeader.AudioFirstTimeStamp) then // raise Exception.CreateFmt('Нарушен порядок следования временных отсчетов Audio. Первый отсчет в файле=%d; Переданный отсчет=%d',[FHeader.AudioFirstTimeStamp,aTimeStamp]); FIndexTable[FIndexTableLength].SetDataTypeAndKey(TsmDataTypeSysData,ffKeyFrame in aFormat.biFrameFlags); FIndexTable[FIndexTableLength].TimestampOffs:=aTimeStamp;//-FHeader.AudioFirstTimeStamp; FIndexTable[FIndexTableLength].StreamPosition:=FStream.Position; inc(FHeader.SysDataFrameCount); aFrameHeader.Marker:=aFrameHeader.Marker or $80; end else raise Exception.Create('Неизвестный тип медиа'); aFrameHeader.DataTypeAndKey:=FIndexTable[FIndexTableLength].DataTypeAndKey; aFrameHeader.TimestampOffs:=FIndexTable[FIndexTableLength].TimestampOffs; aFrameHeader.DataSize:=aDataSize; aFrameHeader.PrevFrameOffset:=0; aFrameHeader.IndexTablePos:=FIndexTableLength; if FIndexTableLength>0 then aFrameHeader.PrevFrameOffset:=FIndexTable[FIndexTableLength].StreamPosition-FIndexTable[FIndexTableLength-1].StreamPosition; inc(FIndexTableLength); FStream.WriteBuffer(aFrameHeader,sizeof(aFrameHeader)); if aFrameHeader.Marker and $80 <>0 then FStream.WriteBuffer(aExtension,sizeof(aExtension)); FStream.WriteBuffer(aData^,aDataSize); inc(FHeader.TotalFrameCount); end; procedure TMediaStreamWriter_Tsm.AssignToStream(aStream: TStream); begin Close; FStream:=aStream; FOwnStream:=false; //Заголовок FStream.WriteBuffer(FHeader,sizeof(FHeader)); end; procedure TMediaStreamWriter_Tsm.Close; begin if Opened then CompleteWriting; if FOwnStream then FreeAndNil(FStream) else FStream:=nil; FFileName:=''; SetLength(FIndexTable,0); FIndexTableLength:=0; FHeader.VideoFrameCount:=0; FHeader.AudioFrameCount:=0; FHeader.SysDataFrameCount:=0; ZeroMemory(@FHeader,sizeof(FHeader)); FHeader.Signature:=TsmSignature; FHeader.Version:=1; end; procedure TMediaStreamWriter_Tsm.Open(const aFileName: string); begin Close; FFileName:=aFileName; FStream:=TFileStream.Create(aFileName,fmCreate); FOwnStream:=true; //Заголовок FStream.WriteBuffer(FHeader,sizeof(FHeader)); end; procedure TMediaStreamWriter_Tsm.WriteData(const aFormat: TMediaStreamDataHeader;aData: pointer; aDataSize: cardinal); var aStreamType: TStreamType; aTimeStamp: int64; begin CheckOpened; aTimeStamp:=aFormat.TimeStamp*aFormat.TimeKoeff; if aFormat.biMediaType=mtVideo then begin Assert(aFormat.biStreamType<>0); aStreamType:=FHeader.VideoStreamType; EnableVideo(aFormat.biStreamType,aFormat.biStreamSubType,aFormat.VideoWidth,aFormat.VideoHeight,aFormat.VideoBitCount); //Первым должен быть опорный видео-кадр if (FHeader.VideoFrameCount>0) or (ffKeyFrame in aFormat.biFrameFlags) then begin FHeader.VideoLastTimeStamp:=aTimeStamp; //В случае аварийного заверешения записи эта информация поможет нам легче восстановить файл if (aStreamType=0) or (FHeader.VideoFrameCount=0) then begin Assert(FHeader.VideoStreamType<>0); if FHeader.VideoFrameCount=0 then FHeader.VideoFirstTimeStamp:=aTimeStamp; UpdateHeader; end; InternalWriteData(aFormat,aData,aDataSize); end; end else if aFormat.biMediaType=mtAudio then begin Assert(aFormat.biStreamType<>0); aStreamType:=FHeader.AudioStreamType; EnableAudio(aFormat.biStreamType,aFormat.biStreamSubType,aFormat.AudioChannels,aFormat.AudioBitsPerSample,aFormat.AudioSamplesPerSec); FHeader.AudioLastTimeStamp:=aTimeStamp; //Первым должен быть опорный кадр //if (FHeader.AudioFrameCount>0) or (ffKeyFrame in aFormat.biFrameFlags) then begin //В случае аварийного заверешения записи эта информация поможет нам легче восстановить файл if (aStreamType=0) or (FHeader.AudioFrameCount=0) then begin Assert(FHeader.AudioStreamType<>0); if FHeader.AudioFrameCount=0 then FHeader.AudioFirstTimeStamp:=aTimeStamp; UpdateHeader; end; InternalWriteData(aFormat,aData,aDataSize); end; end else if aFormat.biMediaType=mtSysData then begin InternalWriteData(aFormat,aData,aDataSize); end; end; procedure TMediaStreamWriter_Tsm.CompleteWriting; var aFrameHead : TTsmFrameHeader; aIndexTableSize : cardinal; aIndexTablePosition: int64; begin CheckOpened; //Записываем индексную таблицу aIndexTableSize:=FIndexTableLength*sizeof(TTsmIndexTableItem); ZeroMemory(@aFrameHead,sizeof(aFrameHead)); aFrameHead.Marker:=0; aFrameHead.DataSize:=aIndexTableSize; aFrameHead.SetDataTypeAndKey(TsmDataTypeIndexTable,false); aIndexTablePosition:=FStream.Position; //Заголовок FStream.WriteBuffer(aFrameHead,sizeof(aFrameHead)); //Данные FStream.WriteBuffer(FIndexTable[0],aIndexTableSize); //Корректируем заголовок FHeader.Valid:=true; FHeader.IndexTableStreamPosition:=aIndexTablePosition; FStream.Seek(0,soFromBeginning); //Обновляем StreamInfo UpdateHeader; end; function TMediaStreamWriter_Tsm.AudioFramesWrittenCount: int64; begin result:=FHeader.AudioFrameCount; end; procedure TMediaStreamWriter_Tsm.CheckDataCompartibility(const aFormat: TMediaStreamDataHeader; aData: pointer; aDataSize: cardinal); var aTimeStamp: int64; begin aTimeStamp:=aFormat.TimeStamp*aFormat.TimeKoeff; if (aFormat.biMediaType=mtVideo) and (FHeader.VideoFrameCount>0) then begin if aTimeStamp<FHeader.VideoFirstTimeStamp then raise Exception.CreateFmt('Нарушен порядок следования временных отсчетов Video. Первый отсчет в файле=%d; Переданный отсчет=%d',[FHeader.VideoFirstTimeStamp,aTimeStamp]); end else if (aFormat.biMediaType=mtAudio) and (FHeader.AudioFrameCount>0) then begin if aTimeStamp<FHeader.AudioFirstTimeStamp then raise Exception.CreateFmt('Нарушен порядок следования временных отсчетов Video. Первый отсчет в файле=%d; Переданный отсчет=%d',[FHeader.AudioFirstTimeStamp,aTimeStamp]); end end; procedure TMediaStreamWriter_Tsm.CheckOpened; begin if not Opened then raise Exception.Create('Записыватель еще не инициализирован'); end; end.
unit BaseEventsQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, System.Contnrs, System.Generics.Collections, DSWrap, HRTimer; type TQueryMonitor = class; TQueryBaseEvents = class(TQueryBase) procedure DefaultOnGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure HideNullGetText(Sender: TField; var Text: string; DisplayText: Boolean); private FAutoTransaction: Boolean; FAfterCommit: TNotifyEventsEx; FAfterCancelUpdates: TNotifyEventsEx; FBeforeApplyUpdates: TNotifyEventsEx; FAfterApplyUpdates: TNotifyEventsEx; FAfterCommitUpdates: TNotifyEventsEx; FClientCount: Integer; FDebug: Boolean; FHaveAnyNotCommitedChanges: Boolean; FHRTimer: THRTimer; FMaster: TQueryBaseEvents; FNeedLoad: Boolean; class var FMonitor: TQueryMonitor; const FDebugFileName: string = 'C:\Public\SQL.txt'; procedure DoAfterDelete(Sender: TObject); procedure DoAfterMasterScroll(Sender: TObject); procedure DoAfterOpen(Sender: TObject); procedure DoAfterPost(Sender: TObject); procedure DoBeforeApplyUpdates(Sender: TFDDataSet); procedure DoAfterApplyUpdates(Sender: TFDDataSet; AError: Integer); procedure DoBeforeMasterScroll(Sender: TObject); procedure DoBeforeOpenOrRefresh(Sender: TObject); procedure DoBeforePost(Sender: TObject); function GetActual: Boolean; function GetBeforeApplyUpdates: TNotifyEventsEx; function GetAfterApplyUpdates: TNotifyEventsEx; function GetAfterCommitUpdates: TNotifyEventsEx; procedure InitializeFields; procedure TryStartTransaction(Sender: TObject); procedure SetAutoTransaction(const Value: Boolean); procedure SetMaster(const Value: TQueryBaseEvents); { Private declarations } protected FAutoTransactionEventList: TObjectList; FDSWrap: TDSWrap; FMasterEventList: TObjectList; class var FFile: TextFile; function CreateDSWrap: TDSWrap; virtual; abstract; procedure DoAfterCommit(Sender: TObject); procedure DoAfterRefresh(Sender: TObject); procedure DoAfterRollback(Sender: TObject); function GetHaveAnyNotCommitedChanges: Boolean; override; procedure SaveDebugLog; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddClient; procedure ApplyUpdates; virtual; procedure CancelUpdates; virtual; procedure LoadFromMaster; overload; procedure LoadFromMaster(AIDParent: Integer; AForcibly: Boolean = False); overload; procedure MasterCascadeDelete; procedure RemoveClient; procedure TryCallAfterCommitUpdatesEvent; procedure TryLoad(AIDParent: Integer); procedure TryLoad2(AIDParent: Integer); procedure TryRefresh; property Actual: Boolean read GetActual; property AutoTransaction: Boolean read FAutoTransaction write SetAutoTransaction; property AfterCancelUpdates: TNotifyEventsEx read FAfterCancelUpdates; property BeforeApplyUpdates: TNotifyEventsEx read GetBeforeApplyUpdates; property AfterApplyUpdates: TNotifyEventsEx read GetAfterApplyUpdates; property AfterCommit: TNotifyEventsEx read FAfterCommit; property AfterCommitUpdates: TNotifyEventsEx read GetAfterCommitUpdates; property ClientCount: Integer read FClientCount; property Debug: Boolean read FDebug write FDebug; property HaveAnyNotCommitedChanges: Boolean read FHaveAnyNotCommitedChanges; property Master: TQueryBaseEvents read FMaster write SetMaster; class property Monitor: TQueryMonitor read FMonitor; property Wrap: TDSWrap read FDSWrap; { Public declarations } end; TQueryMonitor = class private FBeforeApplyUpdates: TNotifyEventsEx; FChangedQueries: TList<TQueryBaseEvents>; FEventList: TObjectList; FOnHaveAnyChanges: TNotifyEventsEx; FQueries: TList<TQueryBaseEvents>; procedure CheckChangedQueries; procedure DoChangedListNotify(Sender: TObject; const Item: TQueryBaseEvents; Action: TCollectionNotification); function GetConnection: TFDCustomConnection; function GetHaveAnyChanges: Boolean; function GetIsEmpty: Boolean; protected procedure DoAfterCommitOrRollback(Sender: TObject); procedure DoAfterDelete(Sender: TObject); procedure DoAfterEditOrInsert(Sender: TObject); procedure DoAfterCancelOrPost(Sender: TObject); property Queries: TList<TQueryBaseEvents> read FQueries; public constructor Create; destructor Destroy; override; procedure Add(AQuery: TQueryBaseEvents); procedure ApplyUpdates; procedure CancelUpdates; procedure Remove(AQuery: TQueryBaseEvents); procedure TryCommit; procedure TryRollback; property BeforeApplyUpdates: TNotifyEventsEx read FBeforeApplyUpdates; property Connection: TFDCustomConnection read GetConnection; property HaveAnyChanges: Boolean read GetHaveAnyChanges; property IsEmpty: Boolean read GetIsEmpty; property OnHaveAnyChanges: TNotifyEventsEx read FOnHaveAnyChanges; end; implementation {$R *.dfm} uses RepositoryDataModule, QueryGroupUnit2, System.Math; { TfrmDataModule } constructor TQueryBaseEvents.Create(AOwner: TComponent); begin inherited Create(AOwner); // FDebug := True; // Создаём обёртку вокруг себя FDSWrap := CreateDSWrap; FDSWrap.Obj := Self; TNotifyEventWrap.Create(FDSWrap.AfterDelete, DoAfterDelete, FDSWrap.EventList); TNotifyEventWrap.Create(FDSWrap.AfterPost, DoAfterPost, FDSWrap.EventList); // Будем засекать время выполнения запроса TNotifyEventWrap.Create(Wrap.BeforeOpen, DoBeforeOpenOrRefresh, Wrap.EventList); TNotifyEventWrap.Create(Wrap.BeforeRefresh, DoBeforeOpenOrRefresh, Wrap.EventList); TNotifyEventWrap.Create(Wrap.AfterRefresh, DoAfterRefresh, Wrap.EventList); // Все поля будем выравнивать по левому краю + клонировать курсор (если надо) TNotifyEventWrap.Create(Wrap.AfterOpen, DoAfterOpen, Wrap.EventList); // Во всех строковых полях будем удалять начальные и конечные пробелы TNotifyEventWrap.Create(Wrap.BeforePost, DoBeforePost, Wrap.EventList); // Создаём события FAfterCommit := TNotifyEventsEx.Create(Self); FAfterCancelUpdates := TNotifyEventsEx.Create(Self); // По умолчанию транзакции сами начинаются и заканчиваются FAutoTransaction := True; // Создаём список своих подписчиков на события FAutoTransactionEventList := TObjectList.Create; FMasterEventList := TObjectList.Create; FHRTimer := THRTimer.Create(False); if FMonitor = nil then begin FMonitor := TQueryMonitor.Create; if FDebug then begin AssignFile(FFile, FDebugFileName); Rewrite(FFile); end; end; // Добавляем себя в список всех запросов FMonitor.Add(Self); end; destructor TQueryBaseEvents.Destroy; begin FreeAndNil(FHRTimer); FreeAndNil(FAfterCommit); FreeAndNil(FAfterCancelUpdates); Assert(FMonitor <> nil); // Удаляем себя из списка всех запросов FMonitor.Remove(Self); // Если монитор больше не нужен if FMonitor.IsEmpty then begin FreeAndNil(FMonitor); if Debug then CloseFile(FFile); end; FreeAndNil(FMasterEventList); // отписываемся от всех событий Мастера FreeAndNil(FAutoTransactionEventList); inherited; end; procedure TQueryBaseEvents.AddClient; begin Assert(FClientCount >= 0); Inc(FClientCount); if FClientCount > 1 then Exit; // если мастер изменился, нам пора обновиться if FNeedLoad then begin LoadFromMaster; Wrap.NeedRefresh := False; // Обновлять больше не нужно end else if Wrap.NeedRefresh then Wrap.RefreshQuery else if Master <> nil then LoadFromMaster else Wrap.TryOpen; end; procedure TQueryBaseEvents.ApplyUpdates; begin Wrap.TryPost; if FDQuery.CachedUpdates then begin // Если все изменения прошли без ошибок if FDQuery.ApplyUpdates() = 0 then FDQuery.CommitUpdates; // Извещаем всех что CommitUpdates произошёл! if FAfterCommitUpdates <> nil then AfterCommitUpdates.CallEventHandlers(Self); end; // Тут какой-то глюк и до переоткрытия кол-во изменений не 0 // Assert(FDQuery.ChangeCount = 0); end; procedure TQueryBaseEvents.CancelUpdates; begin // отменяем все сделанные изменения на стороне клиента Wrap.TryCancel; if FDQuery.CachedUpdates then begin FDQuery.CancelUpdates; // Дополнительно сообщаем о том, что изменения отменены FAfterCancelUpdates.CallEventHandlers(Self); end end; procedure TQueryBaseEvents.DefaultOnGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin Text := VarToStr(Sender.Value); end; procedure TQueryBaseEvents.DoAfterCommit(Sender: TObject); begin if FHaveAnyNotCommitedChanges then begin // Помечаем что у нас нет не закоммитенных изменений FHaveAnyNotCommitedChanges := False; // Извещаем всех что наши изменения закоммичены FAfterCommit.CallEventHandlers(Self); end; end; procedure TQueryBaseEvents.DoAfterDelete(Sender: TObject); begin // Если транзакция ещё не завершилась if FDQuery.Connection.InTransaction then FHaveAnyNotCommitedChanges := True; end; procedure TQueryBaseEvents.DoAfterMasterScroll(Sender: TObject); // var // S: String; begin // S := Name; // if S.StartsWith('QueryCategoryParameters2') then // beep; TryLoad(IfThen(FMaster.FDQuery.RecordCount > 0, FMaster.Wrap.PK.AsInteger, -1)); end; procedure TQueryBaseEvents.DoAfterOpen(Sender: TObject); var i: Integer; begin SaveDebugLog; // Костыль с некоторыми типами полей InitializeFields; // делаем выравнивание всех полей по левому краю for i := 0 to FDQuery.FieldCount - 1 do FDQuery.Fields[i].Alignment := taLeftJustify; end; procedure TQueryBaseEvents.DoAfterPost(Sender: TObject); begin // Если транзакция ещё не завершилась if FDQuery.Connection.InTransaction then FHaveAnyNotCommitedChanges := True; end; procedure TQueryBaseEvents.DoAfterRefresh(Sender: TObject); begin SaveDebugLog; end; procedure TQueryBaseEvents.DoAfterRollback(Sender: TObject); begin // Помечаем что у нас нет не закоммитенных изменений FHaveAnyNotCommitedChanges := False; end; procedure TQueryBaseEvents.DoBeforeApplyUpdates(Sender: TFDDataSet); begin Assert(FBeforeApplyUpdates <> nil); FBeforeApplyUpdates.CallEventHandlers(Self); end; procedure TQueryBaseEvents.DoAfterApplyUpdates(Sender: TFDDataSet; AError: Integer); begin Assert(FAfterApplyUpdates <> nil); FAfterApplyUpdates.CallEventHandlers(Self); end; procedure TQueryBaseEvents.DoBeforeMasterScroll(Sender: TObject); begin // Перед тем, как мастер переместится на новую запись, // нужно сохранить изменения в текущей if FDQuery.Active then Wrap.TryPost; end; procedure TQueryBaseEvents.DoBeforeOpenOrRefresh(Sender: TObject); begin FHRTimer.StartTimer; end; procedure TQueryBaseEvents.DoBeforePost(Sender: TObject); var i: Integer; S: string; begin // Убираем начальные и конечные пробелы в строковых полях for i := 0 to FDQuery.FieldCount - 1 do begin if (FDQuery.Fields[i] is TStringField) and (not FDQuery.Fields[i].ReadOnly and not FDQuery.Fields[i].IsNull) then begin S := FDQuery.Fields[i].AsString.Trim; if FDQuery.Fields[i].AsString <> S then FDQuery.Fields[i].AsString := S; end; end; end; function TQueryBaseEvents.GetActual: Boolean; begin Result := FDQuery.Active and not Wrap.NeedRefresh; end; function TQueryBaseEvents.GetBeforeApplyUpdates: TNotifyEventsEx; begin if FBeforeApplyUpdates = nil then begin Assert(not Assigned(FDQuery.BeforeApplyUpdates)); FBeforeApplyUpdates := TNotifyEventsEx.Create(Self); FDQuery.BeforeApplyUpdates := DoBeforeApplyUpdates; end; Result := FBeforeApplyUpdates; end; function TQueryBaseEvents.GetAfterApplyUpdates: TNotifyEventsEx; begin if FAfterApplyUpdates = nil then begin Assert(not Assigned(FDQuery.AfterApplyUpdates)); FAfterApplyUpdates := TNotifyEventsEx.Create(Self); FDQuery.AfterApplyUpdates := DoAfterApplyUpdates; end; Result := FAfterApplyUpdates; end; function TQueryBaseEvents.GetAfterCommitUpdates: TNotifyEventsEx; begin if FAfterCommitUpdates = nil then begin FAfterCommitUpdates := TNotifyEventsEx.Create(Self); end; Result := FAfterCommitUpdates; end; procedure TQueryBaseEvents.TryStartTransaction(Sender: TObject); begin // начинаем транзакцию, если она ещё не началась if (not AutoTransaction) and (not FDQuery.Connection.InTransaction) then FDQuery.Connection.StartTransaction; end; function TQueryBaseEvents.GetHaveAnyNotCommitedChanges: Boolean; begin Result := FHaveAnyNotCommitedChanges; end; procedure TQueryBaseEvents.HideNullGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin if VarIsNull(Sender.Value) or (Sender.Value = 0) then Text := '' else Text := Sender.Value; end; procedure TQueryBaseEvents.InitializeFields; var i: Integer; begin for i := 0 to FDQuery.Fields.Count - 1 do begin // TWideMemoField - событие OnGetText if FDQuery.Fields[i] is TWideMemoField then FDQuery.Fields[i].OnGetText := DefaultOnGetText; if FDQuery.Fields[i] is TFDAutoIncField then FDQuery.Fields[i].ProviderFlags := [pfInWhere, pfInKey]; end; end; procedure TQueryBaseEvents.LoadFromMaster(AIDParent: Integer; AForcibly: Boolean = False); begin Assert(DetailParameterName <> ''); // Если есть необходимость в загрузке данных if (not FDQuery.Active) or (FDQuery.Params.ParamByName(DetailParameterName) .AsInteger <> AIDParent) or AForcibly then begin FDQuery.Params.ParamByName(DetailParameterName).AsInteger := AIDParent; Wrap.RefreshQuery; end; end; procedure TQueryBaseEvents.LoadFromMaster; var AIDParent: Integer; begin FNeedLoad := False; Assert(FMaster <> nil); AIDParent := IfThen(FMaster.FDQuery.RecordCount > 0, FMaster.Wrap.PK.AsInteger, -1); LoadFromMaster(AIDParent); end; procedure TQueryBaseEvents.MasterCascadeDelete; var V: Variant; begin Assert(FMaster <> nil); Assert(FMaster.FDQuery.RecordCount > 0); V := FMaster.Wrap.PK.Value; Wrap.CascadeDelete(V, DetailParameterName); FMaster.Wrap.LocateByPK(V, True); end; procedure TQueryBaseEvents.RemoveClient; begin Assert(FClientCount > 0); Dec(FClientCount); end; procedure TQueryBaseEvents.SaveDebugLog; var i: Integer; t: Double; begin if not FDebug then Exit; t := FHRTimer.ReadTimer; Writeln(FFile, Format('Time = %f (%s)', [t, Label1.Caption])); // Записываем SQL запрос в файл for i := 0 to FDQuery.SQL.Count - 1 do Writeln(FFile, FDQuery.SQL[i]); if FDQuery.ParamCount > 0 then begin Writeln(FFile, ''); for i := 0 to FDQuery.Params.Count - 1 do begin Writeln(FFile, Format(':%s = %s', [FDQuery.Params[i].Name, FDQuery.Params[i].AsString])); end; end; Writeln(FFile, ''); Writeln(FFile, ''); Flush(FFile); end; procedure TQueryBaseEvents.SetAutoTransaction(const Value: Boolean); begin if FAutoTransaction <> Value then begin FAutoTransaction := Value; // Если не включён режим автотранзакций if not FAutoTransaction then begin // Обработка не-автоматической транзакции TNotifyEventWrap.Create(DMRepository.AfterCommit, DoAfterCommit, FAutoTransactionEventList); TNotifyEventWrap.Create(DMRepository.AfterRollback, DoAfterRollback, FAutoTransactionEventList); TNotifyEventWrap.Create(Wrap.BeforeInsert, TryStartTransaction, FAutoTransactionEventList); TNotifyEventWrap.Create(Wrap.BeforeDelete, TryStartTransaction, FAutoTransactionEventList); TNotifyEventWrap.Create(Wrap.BeforeEdit, TryStartTransaction, FAutoTransactionEventList); end else begin FAutoTransactionEventList.Clear; end; end; end; procedure TQueryBaseEvents.SetMaster(const Value: TQueryBaseEvents); begin if FMaster <> Value then begin // Отписываемся от всех событий старого мастера FMasterEventList.Clear; FMaster := Value; if FMaster <> nil then begin // Подписываемся на события нового мастера TNotifyEventWrap.Create(FMaster.Wrap.BeforeScroll, DoBeforeMasterScroll, FMasterEventList); TNotifyEventWrap.Create(FMaster.Wrap.AfterScrollM, DoAfterMasterScroll, FMasterEventList); end; end; end; procedure TQueryBaseEvents.TryCallAfterCommitUpdatesEvent; begin if FAfterCommitUpdates <> nil then FAfterCommitUpdates.CallEventHandlers(Self); end; procedure TQueryBaseEvents.TryLoad(AIDParent: Integer); var // AIDParent: Integer; AParamValueChange: Boolean; begin Assert(DetailParameterName <> ''); // Assert(FMaster <> nil); // AIDParent := IfThen(FMaster.FDQuery.RecordCount > 0, // FMaster.Wrap.PK.AsInteger, -1); // Если значение параметра изменилось AParamValueChange := FDQuery.Params.ParamByName(DetailParameterName).AsInteger <> AIDParent; // Если наш запрос пока ещё никто не использует if FClientCount = 0 then begin FNeedLoad := True; Exit; end; // Если наш запрос кто-то использует // но параметр НЕ изменился и запрос уже открыт if (not AParamValueChange) and FDQuery.Active then begin Exit; end; if AParamValueChange then FDQuery.Params.ParamByName(DetailParameterName).AsInteger := AIDParent; // Обновляем или открываем заново запрос Wrap.RefreshQuery; end; procedure TQueryBaseEvents.TryLoad2(AIDParent: Integer); var // AIDParent: Integer; AParamValueChange: Boolean; begin Assert(DetailParameterName <> ''); // Если значение параметра изменилось AParamValueChange := FDQuery.Params.ParamByName(DetailParameterName).AsInteger <> AIDParent; // Если наш запрос кто-то использует // но параметр НЕ изменился и запрос уже открыт if (not AParamValueChange) and FDQuery.Active then begin Exit; end; if AParamValueChange then FDQuery.Params.ParamByName(DetailParameterName).AsInteger := AIDParent; // Обновляем или открываем заново запрос Wrap.RefreshQuery; end; procedure TQueryBaseEvents.TryRefresh; begin (* if not Lock then Wrap.RefreshQuery else Wrap.NeedRefresh := True; *) if FClientCount > 0 then Wrap.RefreshQuery else Wrap.NeedRefresh := True; end; constructor TQueryMonitor.Create; begin inherited; FQueries := TList<TQueryBaseEvents>.Create; FChangedQueries := TList<TQueryBaseEvents>.Create; FChangedQueries.OnNotify := DoChangedListNotify; FEventList := TObjectList.Create(True); TNotifyEventWrap.Create(DMRepository.AfterCommit, DoAfterCommitOrRollback, FEventList); TNotifyEventWrap.Create(DMRepository.AfterRollback, DoAfterCommitOrRollback, FEventList); FBeforeApplyUpdates := TNotifyEventsEx.Create(Self); FOnHaveAnyChanges := TNotifyEventsEx.Create(Self); end; destructor TQueryMonitor.Destroy; begin FreeAndNil(FBeforeApplyUpdates); FreeAndNil(FOnHaveAnyChanges); FreeAndNil(FEventList); FreeAndNil(FQueries); FreeAndNil(FChangedQueries); inherited; end; procedure TQueryMonitor.Add(AQuery: TQueryBaseEvents); var i: Integer; begin Assert(AQuery <> nil); i := FQueries.IndexOf(AQuery); Assert(i = -1); FQueries.Add(AQuery); TNotifyEventWrap.Create(AQuery.FDSWrap.AfterEdit, DoAfterEditOrInsert, FEventList); TNotifyEventWrap.Create(AQuery.FDSWrap.AfterInsert, DoAfterEditOrInsert, FEventList); TNotifyEventWrap.Create(AQuery.FDSWrap.AfterDelete, DoAfterDelete, FEventList); TNotifyEventWrap.Create(AQuery.FDSWrap.AfterCancel, DoAfterCancelOrPost, FEventList); TNotifyEventWrap.Create(AQuery.FDSWrap.AfterPost, DoAfterCancelOrPost, FEventList); TNotifyEventWrap.Create(AQuery.AfterCancelUpdates, DoAfterCancelOrPost, FEventList); TNotifyEventWrap.Create(AQuery.AfterCommitUpdates, DoAfterCancelOrPost, FEventList); end; procedure TQueryMonitor.DoAfterCommitOrRollback(Sender: TObject); var i: Integer; begin for i := FChangedQueries.Count - 1 downto 0 do begin if not FChangedQueries[i].HaveAnyChanges then FChangedQueries.Delete(i); end; end; procedure TQueryMonitor.DoAfterDelete(Sender: TObject); var i: Integer; Q: TQueryBaseEvents; begin Q := (Sender as TDSWrap).Obj as TQueryBaseEvents; // Если нет несохранённных изменений if not Q.HaveAnyChanges then begin i := FChangedQueries.IndexOf(Q); if i >= 0 then FChangedQueries.Delete(i); end else begin i := FChangedQueries.IndexOf(Q); // Если этого запроса ещё нет в списке изменённых if i = -1 then FChangedQueries.Add(Q); end; end; procedure TQueryMonitor.DoAfterEditOrInsert(Sender: TObject); var i: Integer; Q: TQueryBaseEvents; begin Q := (Sender as TDSWrap).Obj as TQueryBaseEvents; if not Q.HaveAnyChanges then Exit; i := FChangedQueries.IndexOf(Q); // Если этого запроса ещё нет в списке изменённых if i = -1 then FChangedQueries.Add(Q); end; procedure TQueryMonitor.DoAfterCancelOrPost(Sender: TObject); var i: Integer; Q: TQueryBaseEvents; begin Q := nil; if Sender is TQueryBaseEvents then Q := Sender as TQueryBaseEvents else if Sender is TDSWrap then Q := (Sender as TDSWrap).Obj as TQueryBaseEvents; Assert(Q <> nil); i := FChangedQueries.IndexOf(Q); // Если изменения в этом запросе не требуют сохранения if i < 0 then Exit; // Если нет несохранённых изменений if not Q.HaveAnyChanges then FChangedQueries.Delete(i); end; function TQueryMonitor.GetHaveAnyChanges: Boolean; begin Result := FChangedQueries.Count > 0; end; procedure TQueryMonitor.ApplyUpdates; var ACount: Integer; AQueryGroup: TQueryGroup2; Q: TQueryBaseEvents; begin if not HaveAnyChanges then Exit; // Дополнительно проверяем, что сохранение необходимо!!! CheckChangedQueries; if not HaveAnyChanges then Exit; ACount := FChangedQueries.Count; FBeforeApplyUpdates.CallEventHandlers(Self); while (FChangedQueries.Count > 0) do begin Q := FChangedQueries[0]; if (Q.Owner <> nil) and (Q.Owner is TQueryGroup2) then begin AQueryGroup := Q.Owner as TQueryGroup2; // Просим группу сохранить свои изменения AQueryGroup.ApplyUpdates; end else begin // Если запрос сам по себе Q.ApplyUpdates; end; CheckChangedQueries; // Если количество запросов нуждающихся в сохранении не уменьшилось if FChangedQueries.Count = ACount then break; end; TryCommit; end; procedure TQueryMonitor.CancelUpdates; var ACount: Integer; AQueryGroup: TQueryGroup2; k: Integer; Q: TQueryBaseEvents; begin if not HaveAnyChanges then Exit; ACount := FChangedQueries.Count; k := 0; while (FChangedQueries.Count > 0) and (k < ACount) do begin Q := FChangedQueries[0]; if (Q.Owner <> nil) and (Q.Owner is TQueryGroup2) then begin AQueryGroup := Q.Owner as TQueryGroup2; // Просим группу Отменить свои изменения AQueryGroup.CancelUpdates; Inc(k); end else begin // Если запрос сам по себе Q.CancelUpdates; end; Continue; end; TryRollback; end; procedure TQueryMonitor.CheckChangedQueries; var i: Integer; Q: TQueryBaseEvents; begin for i := FChangedQueries.Count - 1 downto 0 do begin Q := FChangedQueries[i]; // Если нет несохранённых изменений if not Q.HaveAnyChanges then FChangedQueries.Delete(i); end; end; procedure TQueryMonitor.DoChangedListNotify(Sender: TObject; const Item: TQueryBaseEvents; Action: TCollectionNotification); var ACount: Integer; begin ACount := (Sender as TList<TQueryBaseEvents>).Count; if ((Action = cnAdded) and (ACount = 1)) or ((Action = cnRemoved) and (ACount = 0)) then begin FOnHaveAnyChanges.CallEventHandlers(Self); end; end; function TQueryMonitor.GetConnection: TFDCustomConnection; begin Result := nil; if FQueries.Count = 0 then Exit; Result := FQueries.Last.FDQuery.Connection; end; function TQueryMonitor.GetIsEmpty: Boolean; begin Result := FQueries.Count = 0; end; procedure TQueryMonitor.Remove(AQuery: TQueryBaseEvents); var i: Integer; begin Assert(AQuery <> nil); // Мы не должны разрушать запрос, который имеет несохранённые данные i := FChangedQueries.IndexOf(AQuery); // if i >= 0 then // beep; Assert(i = -1); i := FQueries.IndexOf(AQuery); Assert(i >= 0); FQueries.Delete(i); end; procedure TQueryMonitor.TryCommit; begin // Если есть незавершённая транзакция if Connection.InTransaction then Connection.Commit; end; procedure TQueryMonitor.TryRollback; begin // Если есть незавершённая транзакция if Connection.InTransaction then Connection.Rollback; // Отменяем транзакцию end; end.
(***************************************************************************** * Pascal Solution to "Rot13 Encryption" from the * * * * Seventh Annual UCF ACM UPE High School Programming Tournament * * May 15, 1993 * * * *****************************************************************************) program thirteen; var f: text; c: char; begin assign( f, 'thirteen.in' ); reset( f ); while not eof( f ) do begin while not eoln( f ) do begin read( f, c ); if ( upcase( c ) in ['A'..'M'] ) then begin write( chr( ord( c ) + 13 ) ); end else if ( upcase( c ) in ['N'..'Z'] ) then begin write( chr( ord( c ) - 13 ) ); end else begin write( c ); end; end; readln( f ); writeln; end; close( f ); end.
Unit CustomDirOutline; // This is a small enhancement of the sample TDirectoryOutline // Changes are: // 1) Leaf/open/close bitmaps are used as inherited from TOutline // instead of being specially loaded. THerefore they can be changed // 2) Fix to Click method to make root directory selectable // 3) Added Reload method // 4) Does not change or use current directory // 5) Has ChangeToParent, AtRoot, and ChangeToRoot methods Interface Uses SysUtils, Classes, Graphics, StdCtrls, Forms, Dialogs, CustomOutline, Outline; type TCustomDirOutline=Class(TCustomOutline) Protected FDirectory:String; FDrive:Char; FOnChange:TNotifyEvent; FLookAhead: boolean; Procedure SetDrive(NewDrive:Char); Procedure SetDirectory(Const NewDir:String); Procedure FillLevel(Node:TOutlineNode); Procedure CheckForSomeDirs(Node:TOutlineNode); Procedure BuildTree;Virtual; Procedure WalkTree(Const Dir:String); Procedure SetupShow;Override; Procedure BuildOneLevel(ParentLevel:Longint);Virtual; Procedure Change;Virtual; Public Procedure Expand(Index: Longint);Override; Procedure SetupComponent;Override; Destructor Destroy;Override; Procedure Click;Override; Procedure Reload; Public Property Drive:Char read FDrive write SetDrive; // Note unlike original TDirOutline, setting this property // does *not* allow relative paths. Property Directory:String read FDirectory write SetDirectory; // Returns true if already at a root dir Function AtRoot: boolean; // Returns true if could be done Function ChangeToParent: boolean; Function Parent: string; Procedure ChangeToRoot; Property Lines; Property OnChange:TNotifyEvent read FOnChange write FOnChange; published // If this property is false, all dirs will have a + symbol // until they are expanded // If true, the control will look into each dir and see if there // are any subdirs to correct show or hide the + property LookAhead: boolean read FLookAhead write FLookAhead; End; Exports TCustomDirOutline, 'User', 'CustomDirOutline.bmp'; Implementation // Returns true if already at a root dir Function TCustomDirOutline.AtRoot: boolean; Var TestString: string; Begin TestString:= Directory; System.Delete( TestString, 1, 2 ); // remove x: off the start Result:= ( TestString='' ) or ( TestString='\' ); End; Function TCustomDirOutline.Parent: string; Var i: longint; Begin Result:= ''; if AtRoot then exit; Result:= Directory; if Result[ length( Result ) ]='\' then System.Delete( Result, length( Result ), 1 ); for i:= length( Result ) downto 2 do begin if Result[ i ]='\' then begin Result:= copy( Result, 1, i ); exit; end; end; End; // Returns true if could be done Function TCustomDirOutline.ChangeToParent: boolean; Begin Result:= false; if AtRoot then exit; Directory:= Parent; Result:= true; End; Procedure TCustomDirOutline.ChangeToRoot; Begin Directory:= copy( Directory, 1, 3 ); End; Procedure TCustomDirOutline.Change; Begin If FOnChange<>Nil Then FOnChange(Self); End; // Looks at the path for the given node and adds one directory // if there is one. Procedure TCustomDirOutline.CheckForSomeDirs(Node:TOutlineNode); Var Root:ShortString; SearchRec: TSearchRec; Status:Integer; Begin Node.Clear; Root:=Node.FullPath; If Root[Length(Root)] In ['\','/'] Then dec(Root[0]); Status:=FindFirst(Root+'\*.*',faDirectory,SearchRec); While Status=0 Do Begin If SearchRec.Attr And faDirectory = faDirectory Then Begin If ((SearchRec.Name<>'.')And(SearchRec.Name<>'..')) Then //no .. and . Begin // Found a directory // All we care about is adding one node if needed AddChild(Node.Index,SearchRec.Name); FindClose( SearchRec ); exit; End; End; Status:=FindNext(SearchRec); End; end; Procedure TCustomDirOutline.FillLevel(Node:TOutlineNode); Var TempIndex:Longint; Root:ShortString; SearchRec: TSearchRec; Status:Integer; s,s1:String; Begin // We always start from scratch. So it's up to date. Node.Clear; Root:=Node.FullPath; If Root[Length(Root)] In ['\','/'] Then dec(Root[0]); Status:=FindFirst(Root+'\*.*',faDirectory,SearchRec); While Status=0 Do Begin If SearchRec.Attr And faDirectory = faDirectory Then Begin If ((SearchRec.Name<>'.')And(SearchRec.Name<>'..')) Then //no .. and . Begin If Node.HasItems Then //must sort Begin TempIndex:=Node.GetFirstChild; s:=SearchRec.Name; UpcaseStr(s); If TempIndex<>-1 Then Begin s1:=Items[TempIndex].Text; UpcaseStr(s1); End; While (TempIndex<>-1)And(s1<s) Do Begin TempIndex:=Node.GetNextChild(TempIndex); If TempIndex<>-1 Then Begin s1:=Items[TempIndex].Text; UpcaseStr(s1); End; End; If TempIndex<>-1 Then Insert(TempIndex, SearchRec.Name) Else Add(Node.GetLastChild, SearchRec.Name); End Else AddChild(Node.Index,SearchRec.Name); End; End; Status:=FindNext(SearchRec); End; end; Procedure TCustomDirOutline.BuildOneLevel(ParentLevel:Longint); Var Index:LongInt; RootNode:TOutlineNode; FList:TList; t:longint; Begin FillLevel(Items[ParentLevel]); RootNode := Items[ParentLevel]; FList.Create; Index:=RootNode.GetFirstChild; While Index<>-1 Do Begin FList.Add(Items[Index]); Index:=RootNode.GetNextChild(Index); End; // Depending on look ahead, either look for any directories at the // next level to correctly set the +, or // go and put dummy entries so the + will always show up For t:=0 To FList.Count-1 Do if FLookAhead then CheckForSomeDirs(TOutlineNode(FList[t])) else AddChild( TOutlineNode( FList[t] ).Index, 'dummy'); FList.Destroy; End; Procedure TCustomDirOutline.SetupComponent; Begin Inherited SetupComponent; BorderStyle:= bsNone; PlusMinusSize.CX:= 14; PlusMinusSize.CY:= 14; ShowPlusMinus:= False; FLookAhead:= false; Name:='DirectoryOutline'; End; Destructor TCustomDirOutline.Destroy; Begin Inherited Destroy; End; Procedure TCustomDirOutline.Click; Begin inherited Click; Try If SelectedItem=-1 Then Beep(1200,400); if SelectedItem=1 then // Selecting root dir... FullPath will not be quite enough... Directory:=FDrive+':\' else Directory :=Items[SelectedItem].FullPath; Except End; End; Procedure TCustomDirOutline.SetDrive(NewDrive:Char); Begin FDrive:=Upcase(NewDrive); FDirectory:=FDrive+':\'; If Not (csLoading In ComponentState) Then BuildTree; End; Procedure TCustomDirOutline.SetDirectory(Const NewDir:String); Var TempPath: ShortString; Node:TOutlineNode; t:LongInt; Function FindNode(Node:TOutlineNode):TOutlineNode; Var s:String; t:LongInt; Node1:TOutlineNode; Begin s:=Node.FullPath; UpcaseStr(s); If s=TempPath Then Begin result:=Node; exit; End; For t:=0 To Node.ItemCount-1 Do Begin Node1:=Node.Items[t]; Node1:=FindNode(Node1); If Node1<>Nil Then Begin Result:=Node1; exit; End; End; Result:=Nil; End; Begin If (NewDir='') Then exit; If NewDir[ Length( NewDir ) ] In ['\','/'] Then Dec( NewDir[0]); TempPath := NewDir; FDirectory:=TempPath; If FDirectory[1]<>Drive Then Drive:=FDirectory[1] Else Begin WalkTree(TempPath); Change; End; TempPath:=FDirectory; UpcaseStr(TempPath); For t:=0 To ItemCount-1 Do Begin Node:=Items[t]; Node:=FindNode(Node); If Node<>Nil Then Break; End; If Node<>Nil Then If SelectedNode<>Node Then SetAndShowSelectedItem( Node.Index ); End; Procedure TCustomDirOutline.SetupShow; Var CurDir:String; Begin Inherited SetupShow; If FDrive=#0 Then //test if unassigned Begin {$I-} GetDir(0, CurDir); {$I+} If IoResult<>0 Then exit; FDrive := Upcase(CurDir[1]); FDirectory := CurDir; End; BuildTree; End; Procedure TCustomDirOutline.BuildTree; Var RootIndex: Longint; Begin Clear; If FDrive=#0 Then exit; RootIndex:= Add( 0, Drive+':' ); WalkTree( FDirectory ); Change; End; Procedure TCustomDirOutline.WalkTree(Const Dir:String); Var b:LongInt; CurPath,NextDir,s:ShortString; TempItem,TempIndex: Longint; begin TempItem := 1; { start at root } CurPath := Dir; b:=Pos(':',CurPath); If b>0 then CurPath:=Copy(CurPath,b+1,255); If CurPath<>'' Then If CurPath[1]='\' Then System.Delete(CurPath,1,1); NextDir := CurPath; Repeat b:=Pos('\',CurPath); If b=0 Then b:=Pos('/',CurPath); If b > 0 then Begin NextDir:=Copy(CurPath,1,b-1); CurPath:=Copy(CurPath,b+1,255); End Else Begin NextDir:=CurPath; CurPath:=''; End; // Expands this dir, forcing it's subdirs to be read Items[TempItem].Expanded:=True; TempIndex:=Items[TempItem].GetFirstChild; UpcaseStr(NextDir); If CurPath='' Then TempIndex:=-1 Else While TempIndex<>-1 Do Begin s:=Items[TempIndex].Text; UpcaseStr(s); If s=NextDir Then Break; TempIndex:=Items[TempItem].GetNextChild(TempIndex); End; If TempIndex<>-1 Then TempItem:=TempIndex Else CurPath:=''; //break Until CurPath=''; End; Procedure TCustomDirOutline.Expand(Index:Longint); Begin BuildOneLevel(Index); Inherited Expand(Index); End; Procedure TCustomDirOutline.Reload; Var OldDir: string; Begin OldDir:= Directory; BuildTree; Directory:= OldDir; End; initialization end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} unit ScktCnst; interface const //Do not localize KEY_SOCKETSERVER = '\SOFTWARE\Borland\Socket Server'; KEY_IE = 'SOFTWARE\Microsoft\Internet Explorer'; csSettings = 'Settings'; ckPort = 'Port'; ckThreadCacheSize = 'ThreadCacheSize'; ckInterceptGUID = 'InterceptGUID'; ckShowHost = 'ShowHost'; ckTimeout = 'Timeout'; ckRegistered = 'RegisteredOnly'; SServiceName = 'SocketServer'; SApplicationName = 'Borland Socket Server'; resourcestring SServiceOnly = 'The Socket Server can only be run as a service on NT 3.51 and prior'; SErrClose = 'Cannot exit when there are active connections. Kill connections?'; SErrChangeSettings = 'Cannot change settings when there are active connections. Kill connections?'; SQueryDisconnect = 'Disconnecting clients can cause application errors. Continue?'; SOpenError = 'Error opening port %d with error: %s'; SHostUnknown = '(Unknown)'; SNotShown = '(Not Shown)'; SNoWinSock2 = 'WinSock 2 must be installed to use the socket connection'; SStatusline = '%d current connections'; SAlreadyRunning = 'The Socket Server is already running'; SNotUntilRestart = 'This change will not take affect until the Socket Server is restarted'; implementation end.
unit Fonetiza.Consts; interface const PREPOSICOES: TArray<string> = ['DEL', 'DA', 'DE', 'DI', 'DO', 'DU', 'DAS', 'DOS', 'DEU', 'DER', 'E', 'LA', 'LE', 'LES', 'LOS', 'VAN', 'VON', 'EL']; TITULOS: TArray<string> = ['BEL', 'CEL', 'ENG', 'MAJ', 'PROF', 'MIN', 'TEN', 'CAP', 'DR', 'DRA', 'GAL', 'GEN', 'MED', 'PE', 'SARG', 'SGT', 'VVA', 'SR', 'SRA', 'MSC', 'CB', 'SD', 'SEN', 'BACHAREL', 'CORONEL', 'ENGENHEIRO', 'PROFESSOR', 'PROFESSORA', 'MINISTRO', 'TENENTE', 'DOUTOR', 'DOUTORA', 'GENERAL', 'MEDICO', 'PADRE', 'SARGENTO', 'CABO', 'SOLDADO', 'DEP', 'PASTOR', 'PASTORA', 'MESTRE', 'OFICIAL', 'PRESIDENTE', 'VEREADOR']; LETRAS: TArray<TArray<string>> = [['AGA', 'H'], ['BE', 'B'], ['CA', 'K'], ['CE', 'C'], ['DABLIU', 'W'], ['EFE', 'F'], ['ELE', 'L'], ['EME', 'M'], ['ENE', 'N'], ['ERRE', 'R'], ['ESSE', 'S'], ['GE', 'G'], ['IPSILOM', 'Y'], ['IPSILON', 'Y'], ['JOTA', 'J'], ['PE', 'P'], ['QUE', 'Q'], ['TE', 'T'], ['VE', 'V'], ['XIS', 'X'], ['ZE', 'Z']]; NUMEROS: TArray<TArray<string>> = [['CATORZE', '0014'], ['CEM', '0100'], ['CENTO', '0100'], ['CINCO', '0005'], ['CINCOENTA', '0050'], ['CINQUENTA', '0050'], ['DEZ', '0010'], ['DEZENOVE', '0019'], ['DEZESSEIS', '0016'], ['DEZESSETE', '0017'], ['DEZOITO', '0018'], ['DOIS', '0002'], ['DOZE', '0012'], ['DUZENTOS', '0200'], ['HUM', '0001'], ['NOVE', '0009'], ['NOVECENTOS', '0900'], ['NOVENTA', '0090'], ['OITENTA', '0080'], ['OITO', '0008'], ['OITOCENTOS', '0800'], ['ONZE', '0011'], ['QUARENTA', '0040'], ['QUATORZE', '0014'], ['QUATRO', '0004'], ['QUATROCENTOS', '0400'], ['QUINHENTOS', '0500'], ['QUINZE', '0015'], ['SEICENTOS', '0600'], ['SEIS', '0006'], ['SEISCENTOS', '0600'], ['SEISENTOS', '0600'], ['SESSENTA', '0060'], ['SETE', '0007'], ['SETECENTOS', '0700'], ['SETENTA', '0070'], ['TREIS', '0003'], ['TRES', '0003'], ['TRESENTOS', '0300'], ['TREZ', '0003'], ['TREZE', '0013'], ['TREZENTOS', '0300'], ['TRINTA', '0030'], ['UM', '0001'], ['VINTE', '0020'], ['ZERO', '0000'], ['I', '0001'], ['II', '0002'], ['III', '0003'], ['IV', '0004'], ['IX', '0009'], ['V', '0005'], ['VI', '0006'], ['VII', '0007'], ['VIII', '0008'], ['X', '0010'], ['XI', '0011'], ['XII', '0012'], ['XIII', '0013'], ['XIV', '0014'], ['XIX', '0019'], ['XV', '0015'], ['XVI', '0016'], ['XVII', '0017'], ['XVIII', '0018'], ['XX', '0020'], ['XXI', '0021'], ['XXII', '0022'], ['XXIII', '0023'], ['XXIV', '0024'], ['XXIX', '0029'], ['XXV', '0025'], ['XXVI', '0026'], ['XXVII', '0027'], ['XXVIII', '0028'], ['XXX', '0030'], ['XXXI', '0031']]; NOMES: TArray<TArray<string>> = [['ABRA', 'ABRAU'], ['ADRIANI', 'ADRIANA'], ['AIAKI', 'AIAXI'], ['ANI', 'AGINI'], ['AXILI', 'AKILI'], ['BAPITISTA', 'BATISTA'], ['BRIKUPIFI', 'BRIKUFI'], ['BRITAUPITI', 'BRITAUFI'], ['BRITAUTI', 'BRITAUFI'], ['BRITIKUFI', 'BRIKUFI'], ['BRITIKUPIFI', 'BRIKUFI'], ['DABADIA', 'BADIA'], ['DABUITI', 'BUITI'], ['DAGRANGIA', 'GRANGIA'], ['DAKANPURA', 'KANPURA'], ['DALA', 'LA'], ['DAMARIU', 'MARIU'], ['DANUVA', 'NUVA'], ['DARI', 'RI'], ['DARUI', 'RUI'], ['DATIRA', 'TIRA'], ['DAVIDI', 'DAVI'], ['DIBARBA', 'BARBA'], ['DIBASTIANI', 'BASTIANI'], ['DIBIAZI', 'BIAZI'], ['DIBILA', 'BILA'], ['DIBITIU', 'BITIU'], ['DIBUNA', 'BUNA'], ['DIBURTULI', 'BURTULI'], ['DIFRIN', 'FRIN'], ['DIFRITA', 'FRITA'], ['DIGASPIRI', 'GASPIRI'], ['DIGRIGURIU', 'GRIGURIU'], ['DIKARLI', 'KARLI'], ['DIKU', 'KU'], ['DILUKA', 'LUKA'], ['DILURDI', 'LURDI'], ['DIMARIA', 'MARIA'], ['DIMARIU', 'MARIU'], ['DIMARKI', 'MARKI'], ['DIMARKU', 'MARKU'], ['DIMARTINI', 'MARTINI'], ['DIMILU', 'MILU'], ['DIMIRANDA', 'MIRANDA'], ['DIMURA', 'MURA'], ['DINARDI', 'NARDI'], ['DINUNI', 'NUNI'], ['DIPAIVA', 'PAIVA'], ['DIPARI', 'PARI'], ['DIPIRI', 'PIRI'], ['DIRIN', 'RIN'], ['DIRIU', 'RIU'], ['DIRUSI', 'RUSI'], ['DISIZARI', 'SIZARI'], ['DISTIFANI', 'ISTIFANI'], ['DITUFU', 'TUFU'], ['DITUNI', 'TUNI'], ['DUVALI', 'UALI'], ['FABIANI', 'FABIANA'], ['GABRILI', 'GABRILA'], ['GIAKIKI', 'GIAKI'], ['GIAKUBI', 'GIAKU'], ['GIUAXIN', 'GIUAKIN'], ['GUAKU', 'GUASU'], ['ILIANI', 'ILIANA'], ['INISI', 'NS'], ['ISXAIFIR', 'XIFIR'], ['ISXIFIR', 'XIFIR'], ['ISXINATU', 'ISKINATU'], ['KRISTIANI', 'KRISTIANA'], ['KRUGIR', 'KRIGIR'], ['KRUIGIR', 'KRIGIR'], ['KUR', 'KURTI'], ['KUXIRANI', 'KUKRANI'], ['LUSIANI', 'LUSIANA'], ['MAGIDALINA', 'MADALINA'], ['MUILIR', 'MILIR'], ['MULIR', 'MILIR'], ['NIVITUN', 'NIUTUN'], ['PASTIR', 'PASTIUR'], ['RAXIU', 'RAKIU'], ['RUZANI', 'RUZANA'], ['TAXINARDI', 'TAKINARDI'], ['TATIANI', 'TATIANA'], ['TIKIRA', 'TIXIRA'], ['UI', 'UAI'], ['UXINTUN', 'UAXINTUN'], ['XIMITI', 'XIMIDITI'], ['XINAIDIR', 'XINIDIR'], ['XIRISTIA', 'KRISTIA'], ['XIRISTIANA', 'KRISTIANA'], ['XIRISTIANI', 'KRISTIANA'], ['XIRISTINA', 'KRISTINA'], ['XIRISTINI', 'KRISTINI'], ['XIRUIDIR', 'XIRUDIR']]; SINONIMOS: TArray<TArray<string>> = [['ABATIDURU', 'AVI'], ['ANBULATURIU', 'USPITAU'], ['ARKIDIUSIZI', 'IGRIGIA'], ['ARMADUR', 'FUNIRARIA'], ['AVIARIU', 'AVI'], ['AVIKULA', 'AVI'], ['BATALIAU', 'MILITAR'], ['BIRKARIU', 'KRIKI'], ['BRIGADA', 'MILITAR'], ['BUTIKI', 'MUDA'], ['DIUSIZI', 'IGRIGIA'], ['DIZINSITIZADUR', 'DIDITIZAKAU'], ['FAKUDADI', 'UNIVERSIDADI'], ['FIANBRIRIA', 'AKUGI'], ['FIRTILIZANTI', 'ADUBU'], ['FUTUKUPIA', 'KUPIA'], ['GIARDINAGIN', 'FLURIKUTURA'], ['GINASTIKA', 'AKADIMIA'], ['GINAZIU', 'ISKULA'], ['GRANGIA', 'AVI'], ['IDITURA', 'LIVRARIA'], ['INFURMATIKA', 'KUNPUTADUR'], ['INGARAFADUR', 'BIBIDA'], ['INKURPURADUR', 'KUNSTRUKAU'], ['ISPRISU', 'TRANSPURTADUR'], ['ISTASIUNAMINTU', 'GARAGI'], ['ISTITIKA', 'AKADIMIA'], ['IZIRSITU', 'MILITAR'], ['KAFI', 'LANXUNITI'], ['KANTINA', 'RISTAURANTI'], ['KARGA', 'TRANSPURTADUR'], ['KARNI', 'AKUGI'], ['KLINIKA', 'USPITAU'], ['KUARTIU', 'MILITAR'], ['KULIGIU', 'ISKULA'], ['KUNFIKAU', 'MUDA'], ['KURSU', 'ISKULA'], ['KURTINA', 'DIKURAKAU'], ['LANXIRIA', 'LANXUNITI'], ['LUTIAMINTU', 'KUNSTRUKAU'], ['MAGAZINI', 'MUDA'], ['MARSINARIA', 'MUVIU'], ['MATIRNAU', 'KRIKI'], ['MITALURGIKA', 'AKU'], ['MITAU', 'AKU'], ['MUTIU', 'UTIU'], ['PAPILARIA', 'LIVRARIA'], ['PARUKIA', 'IGRIGIA'], ['PIZARIA', 'RISTAURANTI'], ['PULISIA', 'MILITAR'], ['PULISIAU', 'MILITAR'], ['RIFRIGIRANTI', 'BIBIDA'], ['RIGIMINTU', 'MILITAR'], ['RILUGIUARIA', 'GIUALIRIA'], ['SANTUARIU', 'IGRIGIA'], ['SIRIALISTA', 'SIRIAI'], ['SIRVIGIARIA', 'BIBIDA'], ['SUPLITIVU', 'ISKULA'], ['TAPIKARIA', 'DIKURAKAU'], ['TAPITI', 'DIKURAKAU'], ['TIPUGRAFIA', 'GRAFIKA'], ['UIAKAU', 'UNIBU'], ['UINIU', 'BIBIDA'], ['UISTUARIU', 'MUDA'], ['XAPA', 'AKU'], ['XIRUKUPIA', 'KUPIA'], ['PAU', 'PADARIA'], ['XURASKARIA', 'RISTAURANTI']]; implementation end.
unit SearchStat; interface uses SysUtils, Variants, Classes, MSHTML, ActiveX, WinInet, Forms, Controls, Windows, Messages, Graphics, Dialogs, StdCtrls, InetThread; const Yandex = 1; Google = 2; YahooLink = 3; Yahoo = 4; Bing = 5; Rambler = 6; Alexa = 7; YaLinksPattern = '*Inlinks (*'; YaPagesPattern = '*Pages (*'; EngineURLs : array [1..7]of string = ('http://yandex.ru/yandsearch?text=&&site=%s', 'http://www.google.ru/search?q=site:%s&&hl=ru&&lr=&&num=10', 'http://siteexplorer.search.yahoo.com/search?p=%s&&bwm=i', 'http://siteexplorer.search.yahoo.com/search?p=%s', 'http://www.bing.com/search?q=site:%s&&filt=all', 'http://nova.rambler.ru/srch?query=&&and=1&&dlang=0&&mimex=0&&st_date=&&end_date=&&news=0&&limitcontext=0&&exclude=&&filter=%s', 'http://www.alexa.com/siteinfo/%s'); type TCharsets = (tchNone, tchUtf8, tchWin1251); type TCharSet = set of Char; type TOptions = class(TPersistent) private FYandex : boolean; FGoogle : boolean; FYahoo : boolean; FBing : boolean; FRambler : boolean; FYahooLinks : boolean; FAlexaRang : boolean; published property Yandex: Boolean read FYandex write FYandex; property Google: Boolean read FGoogle write FGoogle; property Yahoo: Boolean read FYahoo write FYahoo; property Bing: Boolean read FBing write FBing; property Rambler: Boolean read FRambler write FRambler; property YahooLinks: Boolean read FYahooLinks write FYahooLinks; property AlexaRang: Boolean read FAlexaRang write FAlexaRang; end; type TSingleStat = record EngineConst:byte; Name: string; Operation: string; Value: int64; end; TSingleAcceptEvent = procedure(const EngineConst: byte; Value: int64) of object; TAllAcceptEvent = procedure of object; TStopThreadsEvent = procedure of object; TActivateEvent = procedure (const ActiveThreads: integer)of object; TErrorThreadEvent = procedure (const ErrThreadNum, AllErrThreads:integer; Error: string)of object; TSingleAcceptEventEx = procedure (const Statistic: TSingleStat)of object; type TSearchStats = class(TComponent) private FURL: string; FYandexPages : int64; FGooglePages : int64; FYahooLinks : int64; FYahooPages : int64; FBingPages : int64; FRamblerPages : int64; FAlexaRank : int64; FActive : boolean; FOptions : TOptions; FThreads : byte; FActiveThreads: byte; FAcceptThreads: byte; FErrorThreads : byte; FonSingleAcceptThread : TSingleAcceptEvent; FonAllAcceptThreads : TAllAcceptEvent; FonStopThreads : TStopThreadsEvent; FonActivate : TActivateEvent; FonErrorThread : TErrorThreadEvent; FonSingleAcceptEx : TSingleAcceptEventEx; FPageStreams : array [1..7]of TMemoryStream; FInetThreads : array [1..7]of TInetThread; procedure onActivateThread; procedure onAcceptThread(const EngineConst: byte); procedure onErrorThread(ErrorStr: string; ErrThread:integer); procedure SetURL(cURL: string); procedure SetThread(EngineConst: byte); function PageCharset(PageHTML: string): TCharsets; function DecodeStream(Stream: TMemoryStream; Charset: TCharsets): IHTMLDocument2; function ifThreadsStop: boolean; function YandexParser:int64; function GoogleParser:int64; function YahooLinksParser: int64; function YahooPagesParser: int64; function BingParser: int64; function RamblerParser: int64; function AlexaRangRUS : int64; public Constructor Create(AOwner:TComponent);override; destructor Destroy;override; procedure Deactivate(State: boolean); procedure Activate; procedure Stop; published property Options: TOptions read FOptions write FOptions; property URL: string read FURL write SetURL; property Active: boolean read FActive write Deactivate; property OnAcceptSingleThread:TSingleAcceptEvent read FonSingleAcceptThread write FonSingleAcceptThread; property OnAllAcceptThreads:TAllAcceptEvent read FonAllAcceptThreads write FonAllAcceptThreads; property OnStopThreads:TStopThreadsEvent read FonStopThreads write FonStopThreads; property OnActivate: TActivateEvent read FonActivate write FonActivate; property OnError: TErrorThreadEvent read FonErrorThread write FonErrorThread; property OnAcceptSingleThreadEx: TSingleAcceptEventEx read FonSingleAcceptEx write FonSingleAcceptEx; end; procedure Register; function StripNonConforming(const S: string; const ValidChars: TCharSet): string; Procedure IsolateText( Const S: String; Tag1, Tag2: String; list:TStrings ); function MatchStrings(source, pattern: string): Boolean; implementation procedure Register; begin RegisterComponents('WebDelphi.ru',[TSearchStats]); end; { TSearchStats } function StripNonConforming(const S: string; const ValidChars: TCharSet): string; var DestI: Integer; SourceI: Integer; begin SetLength(Result, Length(S)); DestI := 0; for SourceI := 1 to Length(S) do if S[SourceI] in ValidChars then begin Inc(DestI); Result[DestI] := S[SourceI] end; SetLength(Result, DestI) end; function TSearchStats.DecodeStream(Stream: TMemoryStream; Charset: TCharsets): IHTMLDocument2; var Cache: TStringList; V: OleVariant; begin if Assigned(Stream) then begin Cache:=TStringList.Create; Stream.Position:=0; Cache.LoadFromStream(Stream); V:=VarArrayCreate([0, 0], varVariant); case Charset of tchUtf8: V[0] := Utf8ToAnsi(Cache.Text); tchWin1251: V[0] := Cache.Text; tchNone:begin Charset:=PageCharset(Cache.Text); if Charset = tchUtf8 then V[0] := Utf8ToAnsi(Cache.Text) else V[0] := Cache.Text; end end; Result := coHTMLDocument.Create as IHTMLDocument2; Result.Write(PSafeArray(TVarData(V).VArray)); end else begin raise Exception.Create('Поток пуст!'); Exit; end; end; function TSearchStats.PageCharset(PageHTML: string): TCharsets; var V: OleVariant; Doc: IHTMLDocument2; Meta: IHTMLElementCollection; Element: IHTMLElement; i: integer; cont: string; begin try Doc:=coHTMLDocument.Create as IHTMLDocument2; V:=VarArrayCreate([0, 0], varVariant); V[0]:=PageHTML; Doc.Write(PSafeArray(TVarData(V).VArray)); Meta := Doc.all.tags('meta') as IHTMLElementCollection; cont := ''; for i := 0 to Meta.length - 1 do begin Element := Meta.item(i, 0) as IHTMLElement; if pos('content-type', LowerCase(Element.outerHTML)) > 0 then begin cont := Element.getAttribute('content', 0); if pos('charset', cont) > 0 then break else cont := ''; end; end; if length(cont) > 0 then begin if pos('utf-8', LowerCase(cont)) > 0 then Result := tchUtf8 else Result := tchWin1251 end else Result := tchNone; Doc := nil; except raise Exception.Create ('PageCharset - Ошибка определения кодировки страницы'); end; end; function TSearchStats.RamblerParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Element: IHTMLElement; Tags: IHTMLElementCollection; i:integer; str,attr: string; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Rambler]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Rambler],Charset); Tags:=Doc.all.tags('span')as IHTMLElementCollection; str:=''; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; try if (Element.className='info')then str:=Element.innerText; except end; end; if length(str)>0 then begin if pos(':',str)>0 then begin Delete(str, 1,pos(':',str)+1); Result:=StrToInt(str) end else Result:=-1; end else Result:=-1; end; procedure TSearchStats.Activate; begin FThreads:=0; if not FActive then begin FActive:=true; end else Exit; if Options.FYandex then SetThread(Yandex); if Options.FGoogle then SetThread(Google); if Options.FYahoo then SetThread(Yahoo); if Options.FBing then SetThread(Bing); if Options.FRambler then SetThread(Rambler); if Options.FYahooLinks then SetThread(YahooLink); if Options.FAlexaRang then SetThread(Alexa); if FActiveThreads=0 then FActive:=false; if Assigned(FonActivate) then OnActivate(FActiveThreads); end; function TSearchStats.AlexaRangRUS: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Element: IHTMLElement; Tags: IHTMLElementCollection; i:integer; str,attr: string; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Alexa]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Alexa],Charset); Tags:=Doc.all.tags('div')as IHTMLElementCollection; str:=''; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; try if (Element.className='data')then begin attr:=Element.innerHTML; if pos('ru.png', attr)>0 then str:=Element.innerText; end; except end; end; if length(str)>0 then begin str:=StripNonConforming(str,['0'..'9']); Result:=StrToInt(str) end else Result:=-1; end; function TSearchStats.BingParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Element: IHTMLElement; Tags: IHTMLElementCollection; i:integer; str,attr: string; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Bing]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Bing],Charset); Tags:=Doc.all.tags('span')as IHTMLElementCollection; str:=''; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; try if (Element.className='sb_count')then str:=Element.innerText; except end; end; if length(str)>0 then begin if pos('из',str)>0 then begin Delete(str, 1,pos('из',str)+2); Result:=StrToInt(StripNonConforming(str,['0'..'9'])); end else Result:=-1; end else Result:=-1; end; constructor TSearchStats.Create(AOwner: TComponent); begin inherited; FOptions:=TOptions.Create; end; procedure TSearchStats.Deactivate(State: boolean); var i:integer; begin if State then begin Activate; Exit; end; if FActiveThreads=0 then Exit; for i:=1 to 7 do begin if Assigned(FInetThreads[i]) then begin TerminateThread(FInetThreads[i].Handle,0); FreeAndNil(FPageStreams[i]); end; end; FThreads:=0; FActiveThreads:=0; FAcceptThreads:=0; FErrorThreads:=0; end; destructor TSearchStats.Destroy; begin inherited; end; function TSearchStats.GoogleParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Tags: IHTMLElementCollection; Element: IHTMLElement; i:integer; Str: String; List:TStringList; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Google]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Google],Charset); Tags:=Doc.all.tags('p')as IHTMLElementCollection; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; str:=Element.innerText; if (pos('Результаты',str)>0)and(pos('из приблизительно',str)>0) and (pos(FURL,str)>0) then break; end; if length(str)>0 then begin List:=TStringList.Create; IsolateText(Str, 'приблизительно', FURL, list); Result:=StrToInt(StripNonConforming(list.Text,['0'..'9'])) end else Result:=-1; end; function TSearchStats.ifThreadsStop: boolean; begin Result:=(FAcceptThreads=7)or(FErrorThreads=7)or(FAcceptThreads+FErrorThreads=FThreads); end; Procedure IsolateText( Const S: String; Tag1, Tag2: String; list:TStrings ); Var pScan, pEnd, pTag1, pTag2: PChar; foundText: String; searchtext: String; Begin searchtext := Uppercase(S); Tag1:= Uppercase( Tag1 ); Tag2:= Uppercase( Tag2 ); pTag1:= PChar(Tag1); pTag2:= PChar(Tag2); pScan:= PChar(searchtext); Repeat pScan:= StrPos( pScan, pTag1 ); If pScan <> Nil Then Begin Inc(pScan, Length( Tag1 )); pEnd := StrPos( pScan, pTag2 ); If pEnd <> Nil Then Begin SetString( foundText,Pchar(S) + (pScan- PChar(searchtext) ),pEnd - pScan ); list.Add( foundText ); pScan := pEnd + Length(tag2); End Else pScan := Nil; End; Until pScan = Nil; End; procedure TSearchStats.onAcceptThread(const EngineConst: byte); var Single: TSingleStat; begin Dec(FActiveThreads); Inc(FAcceptThreads); case EngineConst of 1:begin FYandexPages:=YandexParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FYandexPages); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Yandex'; Single.Operation:='Подсчёт страниц в индеке'; Single.Value:=FYandexPages; OnAcceptSingleThreadEx(Single); end; end; 2:begin FGooglePages:=GoogleParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FGooglePages); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Google'; Single.Operation:='Подсчёт страниц в индеке'; Single.Value:=FGooglePages; OnAcceptSingleThreadEx(Single); end; end; 3:begin FYahooLinks:=YahooLinksParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FYahooLinks); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Yahoo'; Single.Operation:='Подсчёт внешних ссылок на страницы сайта'; Single.Value:=FYahooLinks; OnAcceptSingleThreadEx(Single); end; end; 4:begin FYahooPages:=YahooPagesParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FYahooPages); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Yahoo'; Single.Operation:='Подсчёт страниц в индексе'; Single.Value:=FYahooPages; OnAcceptSingleThreadEx(Single); end; end; 5:begin FBingPages:=BingParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FBingPages); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Bing'; Single.Operation:='Подсчёт страниц в индексе'; Single.Value:=FBingPages; OnAcceptSingleThreadEx(Single); end; end; 6:begin FRamblerPages:=RamblerParser; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FRamblerPages); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Rambler'; Single.Operation:='Подсчёт страниц в индексе'; Single.Value:=FRamblerPages; OnAcceptSingleThreadEx(Single); end; end; 7:begin FAlexaRank:=AlexaRangRUS; if Assigned(FonSingleAcceptThread) then OnAcceptSingleThread(EngineConst, FAlexaRank); if Assigned(FonSingleAcceptEx) then begin Single.EngineConst:=EngineConst; Single.Name:='Alexa'; Single.Operation:='Текущее положение в рейтинге'; Single.Value:=FAlexaRank; OnAcceptSingleThreadEx(Single); end; end; end; if ifThreadsStop then if Assigned(FonAllAcceptThreads) then begin OnAllAcceptThreads; FActive:=false; FThreads:=0; FActiveThreads:=0; FAcceptThreads:=0; FErrorThreads:=0; end; end; procedure TSearchStats.onActivateThread; begin Inc(FActiveThreads); end; procedure TSearchStats.onErrorThread(ErrorStr: string; ErrThread:integer); begin Dec(FActiveThreads); Inc(FErrorThreads); if Assigned(FonErrorThread) then OnError(ErrThread,FErrorThreads,ErrorStr); if ifThreadsStop then if Assigned(FonAllAcceptThreads) then begin OnAllAcceptThreads; FActive:=false; FThreads:=0; FActiveThreads:=0; FAcceptThreads:=0; FErrorThreads:=0; end; end; procedure TSearchStats.SetThread(EngineConst: byte); var URLstr:string; begin try URLstr:=Format(EngineURLs[EngineConst],[FURL]); except MessageBox(0,'Ошибка в URL. Сбор статистики прерван',PChar('Ошибка потока '+IntToStr(EngineConst)),MB_OK+MB_ICONERROR); Exit; end; if Assigned(FPageStreams[EngineConst]) then FreeAndNil(FPageStreams[EngineConst]); FPageStreams[EngineConst]:=TMemoryStream.Create; FInetThreads[EngineConst]:=TInetThread.Create(true, URLstr, Pointer(FPageStreams[EngineConst]),EngineConst); FInetThreads[EngineConst].OnAcceptedEvent:=onAcceptThread; FInetThreads[EngineConst].OnError:=onErrorThread; FInetThreads[EngineConst].Resume; FInetThreads[EngineConst].FreeOnTerminate:=true; Inc(FActiveThreads); Inc(FThreads); end; procedure TSearchStats.SetURL(cURL: string); var aURLC: TURLComponents; lencurl: Cardinal; aURL: string; begin if pos('http://', cURL) = 0 then cURL := 'http://' + cURL; FillChar(aURLC, SizeOf(TURLComponents), 0); with aURLC do begin lpszScheme := nil; dwSchemeLength := INTERNET_MAX_SCHEME_LENGTH; lpszHostName := nil; dwHostNameLength := INTERNET_MAX_HOST_NAME_LENGTH; lpszUserName := nil; dwUserNameLength := INTERNET_MAX_USER_NAME_LENGTH; lpszPassword := nil; dwPasswordLength := INTERNET_MAX_PASSWORD_LENGTH; lpszUrlPath := nil; dwUrlPathLength := INTERNET_MAX_PATH_LENGTH; lpszExtraInfo := nil; dwExtraInfoLength := INTERNET_MAX_PATH_LENGTH; dwStructSize := SizeOf(aURLC); end; lencurl := INTERNET_MAX_URL_LENGTH; SetLength(aURL, lencurl); InternetCanonicalizeUrl(PChar(cURL), PChar(aURL), lencurl, ICU_BROWSER_MODE); if InternetCrackUrl(PChar(aURL), length(aURL), 0, aURLC) then begin FURL := aURLC.lpszHostName; Delete(FURL, pos(aURLC.lpszUrlPath, aURLC.lpszHostName), length (aURLC.lpszUrlPath)); end else raise Exception.Create('SetDomain - Ошибка WinInet #' + IntToStr (GetLastError)); end; procedure TSearchStats.Stop; var i: Integer; begin for i:=1 to 7 do begin if Assigned(FInetThreads[i]) then begin TerminateThread(FInetThreads[i].Handle,0); FreeAndNil(FPageStreams[i]); end; end; FActive:=false; if Assigned(FonStopThreads) then OnStopThreads; FThreads:=0; FActiveThreads:=0; FAcceptThreads:=0; FErrorThreads:=0; end; function TSearchStats.YahooLinksParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Element: IHTMLElement; Tags: IHTMLElementCollection; i:integer; str: string; StringList: TStringList; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[YahooLink]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[YahooLink],Charset); StringList:=TStringList.Create; Tags:=Doc.all.tags('span')as IHTMLElementCollection; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; str:=Element.innerText; if MatchStrings(str, YaLinksPattern) then break; end; IsolateText(Str, '(',')', StringList); Result:=StrToInt(StripNonConforming(StringList.Strings[0],['0'..'9'])); end; function TSearchStats.YahooPagesParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Element: IHTMLElement; Tags: IHTMLElementCollection; i:integer; str: string; StringList: TStringList; begin cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Yahoo]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Yahoo],Charset); StringList:=TStringList.Create; Tags:=Doc.all.tags('span')as IHTMLElementCollection; for i:=0 to Tags.length-1 do begin Element:=Tags.item(i, 0) as IHTMLElement; str:=Element.innerText; if MatchStrings(str, YaPagesPattern) then break; end; IsolateText(Str, '(',')', StringList); Result:=StrToInt(StripNonConforming(StringList.Strings[0],['0'..'9'])); end; function MatchStrings(source, pattern: string): Boolean; var pSource: array[0..255] of Char; pPattern: array[0..255] of Char; function MatchPattern(element, pattern: PChar): Boolean; function IsPatternWild(pattern: PChar): Boolean; var t: Integer; begin Result := StrScan(pattern, '*') <> nil; if not Result then Result := StrScan(pattern, '?') <> nil; end; begin if 0 = StrComp(pattern, '*') then Result := True else if (element^ = Chr(0)) and (pattern^ <> Chr(0)) then Result := False else if element^ = Chr(0) then Result := True else begin case pattern^ of '*': if MatchPattern(element, @pattern[1]) then Result := True else Result := MatchPattern(@element[1], pattern); '?': Result := MatchPattern(@element[1], @pattern[1]); else if element^ = pattern^ then Result := MatchPattern(@element[1], @pattern[1]) else Result := False; end; end; end; begin StrPCopy(pSource, source); StrPCopy(pPattern, pattern); Result := MatchPattern(pSource, pPattern); end; function TSearchStats.YandexParser: int64; var Charset: TCharsets; Doc: IHTMLDocument2; Cache: TStringList; Title: string; k:integer; begin k:=1; cache:=TStringList.Create; Cache.LoadFromStream(FPageStreams[Yandex]); Charset:=PageCharset(Cache.Text); Doc:=coHTMLDocument.Create as IHTMLDocument2; Doc:=DecodeStream(FPageStreams[Yandex],Charset); Title:=Doc.title; if Length(Title)=0 then Result:=-1 else begin if pos('тыс',title)>0 then k:=1000 else if pos('млн',title)>0 then k:=1000000 else if pos('млрд',title)>0 then k:=1000000000; end; try Title:=StripNonConforming(Title, ['0'..'9']); Result:=StrToInt(Title)*k; except Result:=-1; end; end; end.
{*******************************************************} { } { Delphi DataSnap Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Datasnap.DSHTTP; interface uses System.JSON, System.Classes, System.SysUtils, Data.DBXCommon, Data.DBXTransport, Data.DbxDatasnap, Datasnap.DSHTTPCommon, Datasnap.DSAuth, Datasnap.DSTransport, Datasnap.DSCommonServer, Datasnap.DSServer, Datasnap.DSService, Datasnap.DSSession, System.Generics.Collections, Web.WebFileDispatcher, IPPeerAPI; type /// <summary>Serves a response to a DataSnap/cache request for supported /// request types (GET and DELETE).</summary> TDSHTTPCacheContextService = class(TDSRequestFilterManager) private FSession: TDSSession; FLocalConnection: Boolean; /// <summary> Parses the request for the desired Cache item ID, command index and parameter index. /// Any of these can be -1 instead of an actual value, as long as the ones after it are also -1. /// </summary> function ParseRequst(Request: string; out CacheId, CommandIndex, ParameterIndex: Integer): Boolean; procedure InvalidRequest(Response: TDSHTTPResponse; Request: string); /// <summary> Returns the Cache Item IDs as held by the cache </summary> procedure GetCacheContents(out Value: TJSONValue); /// <summary> Returns the number of commands held by the item. (Usually 1) /// </summary> procedure GetCacheItemContents(const CacheId: Integer; out Value: TJSONValue); /// <summary> Returns the number of parameters held by the command /// </summary> procedure GetCommandContents(const CacheId: Integer; const CommandIndex: Integer; out Value: TJSONValue); /// <summary> Returns the parameter value as either JSON or TStream, depending on the request /// </summary> procedure GetParameterValue(const RequestInfo: TDSHTTPRequest; const CacheId: Integer; const CommandIndex: Integer; const ParameterIndex: Integer; out Response: TJSONValue; out ResponseStream: TStream; out IsError: Boolean); /// <summary> Returns the parameter index for the given command. </summary> function GetOriginalParamIndex(const Command: TDBXCommand; const Parameter: TDBXParameter): Integer; /// <summary> Returns true if Streams should be returned as JSON, false to return them as content stream /// </summary> function StreamsAsJSON(const RequestInfo: TDSHTTPRequest): Boolean; function ByteContent(JsonValue: TJSONValue): TArray<Byte>; public constructor Create(Session: TDSSession; LocalConnection: Boolean); reintroduce; virtual; /// <summary> Uses the given Request string to deterine which part of the cache the client is interested in, /// and populates the result accordingly. /// </summary> procedure ProcessGETRequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: string); /// <summary> Uses the given Request string to deterine which part of the cache the client wants to delete, /// and populates the result accordingly after performing the deletion. /// </summary> procedure ProcessDELETERequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: string); end; /// <summary>Represents the DataSnap-specific REST server.</summary> TDSRESTServer = class public type TParsingRequestEvent = TDSServiceResponseHandler.TParsingRequestEvent; TParseRequestEvent = TDSServiceResponseHandler.TParseRequestEvent; private /// <summary> Time in miliseconds a session will remain valid. </summary> /// <remarks> After this time passes, the session is marked as expired and eventually removed. /// If 0 is specified, the session never expires. /// </remarks> FSessionTimeout: Integer; /// <summary> Name of a DSServer in the current process </summary> FDSServerName: string; FDSHTTPAuthenticationManager: TDSCustomAuthenticationManager; FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory; FIPImplementationID: string; FRESTContext: string; FDSContext: string; FSessionLifetime: TDSSessionLifetime; FTrace: TDSHTTPServiceTraceEvent; FParseRequestEvent: TParseRequestEvent; FParsingRequestEvent: TParsingRequestEvent; FResultEvent: TDSRESTResultEvent; FDSServer: TDSCustomServer; function GetRestContext: string; function GetDsContext: string; procedure SetRestContext(const ctx: string); procedure SetDsContext(const ctx: string); /// <summary> Tries to consume the prefix out of the context. Returns what /// is left of it, nil if the prefix is not found. /// <param name="prefix">prefix string, not null or empty</param> /// <param name="context">current context, never null or empty</param> /// <param name="unused">unused part of the context</param> /// <return>true if the context has the prefix</return> /// </summary> function Consume(const Prefix: string; const Context: string; out Unused: string): Boolean; function ByteContent(DataStream: TStream): TArray<Byte>; overload; function ByteContent(JsonValue: TJSONValue): TArray<Byte>; overload; property RESTContext: string read GetRestContext write SetRESTContext; property DSContext: string read GetDSContext write SetDSContext; procedure SetAuthenticationManager(AuthenticationManager: TDSCustomAuthenticationManager); virtual; function IsClosingSession(const Request: string): Boolean; function IsOpeningClientChannel(const Request: string): Boolean; function IsClosingClientChannel(const Request: string): Boolean; procedure UpdateSessionTunnelHook(const Request: string; Session: TDSSession; RequestInfo: TDSHTTPRequest); virtual; procedure CloseRESTSession(Session: TDSSession; ResponseInfo: TDSHTTPResponse); procedure CheckClientChannelMethod(const Request: string); function CreateRESTService(const AuthUserName, AuthPassword: string): TDSRESTService; virtual; strict protected procedure SetDSServerName(AName: string); virtual; function ConsumeOtherContext(const AContext: string; out APrefix: string; out AUnused: string): Boolean; virtual; procedure DoDSOtherCommand( const AContext: TDSHTTPContext; const ARequestInfo: TDSHTTPRequest; const AResponseInfo: TDSHTTPResponse; const APrefix: string; const ARequest: string; ALocalConnection: Boolean); virtual; procedure DoDSRESTCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: string); procedure DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse); procedure DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string); virtual; protected function Decode(Data: string): string; virtual; abstract; public constructor Create; overload; constructor Create(const AIPImplementationID: string); overload; constructor Create(const ADSServer: TDSCustomServer); overload; constructor Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string); overload; virtual; destructor Destroy; override; procedure CreateProtocolHandlerFactory(ATransport: TDSServerTransport); virtual; procedure ClearProtocolHandlerFactory; virtual; property DSServer: TDSCustomServer read FDSServer write FDSServer; property DSServerName: string read FDSServerName write SetDSServerName; property DSAuthenticationManager: TDSCustomAuthenticationManager read FDSHTTPAuthenticationManager write SetAuthenticationManager; property SessionTimeout: Integer read FSessionTimeout write FSessiontimeout; property SessionLifetime: TDSSessionLifetime read FSessionLifetime write FSessionLifetime; property IPImplementationID: string read FIPImplementationID; /// <summary>Event to call when a REST call is having its result built, to be returned.</summary> property ResultEvent: TDSRESTResultEvent read FResultEvent write FResultEvent; property OnParsingRequest: TParsingRequestEvent read FParsingRequestEvent write FParsingRequestEvent; property OnParseRequest: TParseRequestEvent read FParseRequestEvent write FParseRequestEvent; end; /// <summary>HTTP server that provides DataSnap-specific implementations for /// different command types, and supports both REST and HTTP.</summary> TDSHTTPServer = class(TDSRESTServer) strict private /// <summary> DS host name. Only used if DSServerName is not specified </summary> FDSHostname: string; /// <summary> DS host port number. Only used if DSServerName is not specified </summary> FDSPort: Integer; /// <summary> Filter reference </summary> FFilters: TTransportFilterCollection; /// <summary>true if the user credentials are passed through remote DS instance</summary> FCredentialsPassThrough: Boolean; /// <summary>DS user credentials, they work in tandem with the pass through</summary> FDSAuthUser: string; FDSAuthPassword: string; FCacheContext: string; // /// <summary> Time in miliseconds a session will remain valid. </summary> // /// <remarks> After this time passes, the session is marked as expired and eventually removed. // /// If 0 is specified, the session never expires. // /// </remarks> // FSessionTimeout: Integer; FSessionEvent: TDSSessionEvent; private FTunnelService: TDSTunnelService; procedure SetDSHostname(AHostname: string); procedure SetDSPort(APort: Integer); procedure SetFilters(AFilterCollection: TTransportFilterCollection); procedure SetAuthenticationManager(AuthenticationManager: TDSCustomAuthenticationManager); override; function GetTunnelService: TDSTunnelService; procedure CloseAllTunnelSessions; function CreateRESTService(const AuthUserName, AuthPassword: string): TDSRESTService; override; function GetCacheContext: string; procedure SetCacheContext(const ctx: string); function GetClientChannelInfo(Request: string; out ChannelName, ClientChannelId, ClientCallbackID, SecurityToken: string): Boolean; procedure UpdateSessionTunnelHook(const Request: string; Session: TDSSession; RequestInfo: TDSHTTPRequest); override; procedure CloseSessionTunnels(Session: TDSSession); strict protected procedure SetDSServerName(AName: string); override; procedure DoTunnelCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse); function ConsumeOtherContext(const AContext: string; out APrefix: string; out AUnused: string): Boolean; override; procedure DoDSOtherCommand( const AContext: TDSHTTPContext; const ARequestInfo: TDSHTTPRequest; const AResponseInfo: TDSHTTPResponse; const APrefix: string; const ARequest: string; ALocalConnection: Boolean); override; procedure DoDSCacheCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: string; LocalConnection: Boolean); public constructor Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string); overload; override; destructor Destroy; override; procedure CreateProtocolHandlerFactory(ATransport: TDSServerTransport); override; procedure ClearProtocolHandlerFactory; override; property CacheContext: string read GetCacheContext write SetCacheContext; property TunnelService: TDSTunnelService read GetTunnelService; property DSHostname: string read FDSHostname write SetDSHostname; property DSPort: Integer read FDSPort write SetDSPort; property Filters: TTransportFilterCollection read FFilters write SetFilters; property CredentialsPassThrough: Boolean read FCredentialsPassThrough write FCredentialsPassThrough; property DSAuthUser: string read FDSAuthUSer write FDSAuthUser; property DSAuthPassword: string read FDSAuthPassword write FDSAuthPassword; end; /// <summary>Default implementation of a response handler that returns JSON /// for all data types, except for the case where the user specifies that he /// wants a TStream to be returned in the response stream when the TStream is /// the only output/response parameter of the method being invoked.</summary> TDSDefaultResponseHandler = class(TDSJsonResponseHandler) private FStoreHandler: Boolean; protected function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; override; procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); override; public constructor Create(AllowBinaryStream: Boolean; DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean = True); destructor Destroy; override; procedure Close; override; end; /// <summary>Implements the REST architecture for the REST service provider of /// a DataSnap server.</summary> TCustomDSRESTServerTransport = class(TDSServerTransport) public type TParsingRequestEvent = procedure(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings; var AHandled: Boolean) of object; TParseRequestEvent = procedure(Sender: TObject; const ARequest: string; const ASegments: TStrings; var ADSMethodName: string; const AParamValues: TStrings) of object; strict protected FRESTServer: TDSRESTServer; strict private { Private declarations } FSessionLifetime: TDSSessionLifetime; FSessionTimeout: Integer; FDSContext: string; FDSRestContext: string; FAuthenticationManager: TDSCustomAuthenticationManager; FTrace: TDSHTTPServiceTraceEvent; FResultEvent: TDSRESTResultEvent; FParsingRequestEvent: TParsingRequestEvent; FParseRequestEvent: TParseRequestEvent; private function GetRESTServer: TDSRESTServer; procedure UpdateDSServerName; function IsDSContextStored: Boolean; function IsRESTContextStored: Boolean; procedure ReadTrace(Reader: TReader); procedure ReadFormatResult(Reader: TReader); procedure ReadProperty(Reader: TReader; const ANewProperty: string); protected procedure Loaded; override; procedure RequiresServer; function CreateRESTServer: TDSRESTServer; virtual; abstract; procedure InitializeRESTServer; virtual; { Protected declarations } procedure SetRESTContext(const Ctx: string ); procedure SetDSContext(const Ctx: string); procedure SetTraceEvent(Event: TDSHTTPServiceTraceEvent); procedure SetParseRequestEvent(Event: TParseRequestEvent); function GetParseRequestEvent: TParseRequestEvent; procedure SetParsingRequestEvent(Event: TParsingRequestEvent); function GetParsingRequestEvent: TParsingRequestEvent; procedure SetServer(const AServer: TDSCustomServer); override; procedure SetAuthenticationManager(const AuthenticationManager: TDSCustomAuthenticationManager); procedure SetResultEvent(const RestEvent: TDSRESTResultEvent); procedure SetIPImplementationID(const AIPImplementationID: string); override; function GetRESTContext: string; function GetDSContext: string; function GetTraceEvent: TDSHTTPServiceTraceEvent; function GetAuthenticationManager: TDSCustomAuthenticationManager; function GetResultEvent: TDSRESTResultEvent; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetSessionTimeout: Integer; virtual; procedure SetSessionTimeout(const Milliseconds: Integer); virtual; function GetIPImplementationID: string; override; // Backward compatability procedure DefineProperties(Filer: TFiler); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; property RESTServer: TDSRESTServer read GetRESTServer; [Stored('IsDSContextStored'), nodefault] property DSContext: string read GetDSContext write SetDSContext stored IsDSContextStored nodefault; /// <summary> REST URL context like in http://my.site.com/datasnap/rest/... /// In the example above rest denotes that the request is a REST request /// and is processed by REST service /// </summary> [Stored('IsRESTContextStored'), nodefault] property RESTContext: string read GetRESTContext write SetRESTContext stored IsRESTContextStored nodefault; property AuthenticationManager: TDSCustomAuthenticationManager read GetAuthenticationManager write SetAuthenticationManager; /// <summary> Time in miliseconds a session will remain valid. </summary> /// <remarks> After this time passes, the session is marked as expired and eventually removed. /// If 0 is specified, the session never expires. /// </remarks> [Default(1200000)] property SessionTimeout: Integer read GetSessionTimeout write SetSessionTimeout default 1200000; property SessionLifetime: TDSSessionLifetime read FSessionLifetime write FSessionLifetime default TDSSessionLifetime.TimeOut; /// <summary> User trace code might go here /// </summary> property OnHTTPTrace: TDSHTTPServiceTraceEvent read GetTraceEvent write SetTraceEvent; property Trace: TDSHTTPServiceTraceEvent read GetTraceEvent write SetTraceEvent; // Old name /// <summary>Event to call when a REST call is having its result built.</summary> /// <remarks>The result can be modified by this event, changing its format or content.</remarks> property OnFormatResult: TDSRESTResultEvent read GetResultEvent write SetResultEvent; property FormatResult: TDSRESTResultEvent read GetResultEvent write SetResultEvent; // Old name property OnParseRequest: TParseRequestEvent read GetParseRequestEvent write SetParseRequestEvent; property OnParsingRequest: TParsingRequestEvent read GetParsingRequestEvent write SetParsingRequestEvent; end; /// <summary>Represents the HTTP service provider of a DataSnap server, /// providing lightweight HTTP services for DataSnap, and implementing /// protocols such as REST.</summary> TCustomDSHTTPServerTransport = class(TCustomDSRESTServerTransport) strict protected FHttpServer: TDSHTTPServer; strict private { Private declarations } FCredentialsPassthrough: Boolean; FDSAuthPassword: string; FDSAuthUser: string; FDSPort: Integer; FDSHostName: string; FDSCacheContext: string; function IsCacheContextStored: Boolean; private function GetHttpServer: TDSHTTPServer; function IsDSHostnameStored: Boolean; procedure SetCacheContext(const Ctx: string); function GetCacheContext: string; protected function CreateHttpServer: TDSHTTPServer; virtual; abstract; function CreateRESTServer: TDSRESTServer; override; procedure InitializeRESTServer; override; procedure InitializeHttpServer; virtual; { Protected declarations } procedure SetDSHostname(Host: string ); procedure SetDSPort(Port: Integer); function GetDSHostname: string; function GetDSPort: Integer; procedure SetFilters(const Value: TTransportFilterCollection); override; procedure ServerCloseAllTunnelSessions; procedure SetCredentialsPassThrough(const AFlag: Boolean); virtual; procedure SetDSAuthUser(const UserName: string); virtual; procedure SetDSAuthPassword(const UserPassword: string); virtual; function GetCredentialsPassThrough: Boolean; function GetDSAuthUser: string; virtual; function GetDSAuthPassword: string; virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; property HttpServer: TDSHTTPServer read GetHttpServer; /// <summary> Cache URL context, like in http://my.site.com/datasnap/cache/... /// </summary> [Stored('IsCacheContextStored'), nodefault] property CacheContext: string read GetCacheContext write SetCacheContext stored IsCacheContextStored nodefault; /// <summary> Datasnap Server machine name. Only used when DSServer is not set </summary> [Stored('IsDSHostnameStored'), nodefault] property DSHostname: string read GetDSHostname write SetDSHostname stored IsDSHostnameStored nodefault; /// <summary> Datasnap Server port number. Only used when DSServer is not set </summary> [Default(211)] property DSPort: Integer read GetDSPort write SetDSPort default 211; /// <summary> true if the user credentials are authenticated at the endpoint </summary> [Default(False)] property CredentialsPassThrough: Boolean read GetCredentialsPassThrough write SetCredentialsPassThrough default False; property DSAuthUser: string read GetDSAuthUser write SetDSAuthUser; property DSAuthPassword: string read GetDSAuthPassword write SetDSAuthPassword; end; /// <summary>Implements the REST architecture for the REST service provider of /// a DataSnap server.</summary> TDSRESTServerTransport = class(TCustomDSRESTServerTransport) published property DSContext; property RESTContext; property Server; property AuthenticationManager; property SessionTimeout; property SessionLifetime; property OnParseRequest; property OnParsingRequest; property OnHTTPTrace; property OnFormatResult; end; /// <summary>Lightweight HTTP service provider for DataSnap servers that /// implements internet protocols such as REST or HTTP.</summary> TDSHTTPServerTransport = class(TCustomDSHTTPServerTransport) published property DSContext; property RESTContext; property CacheContext; property Server; property DSHostname; property DSPort; property Filters; property AuthenticationManager; property CredentialsPassThrough; property DSAuthUser; property DSAuthPassword; property SessionTimeout; property OnHTTPTrace; property OnFormatResult; end; /// <summary>Response handler for the case when complex data types are stored /// on the server in a cache and the URL (Uniform Resource Identifier) to the /// object in the cache is passed back to the user instead of the value of the /// cached object.</summary> TDSCacheResponseHandler = class(TDSJsonResponseHandler) protected FResultHandler: TDSCacheResultCommandHandler; FCacheId: Integer; function GetCacheObject: TDSCacheResultCommandHandler; function HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; override; procedure PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); override; function GetComplexParams(Command: TDBXCommand; out Index: Integer; AddIfNotFound: Boolean = True): TDSCommandComplexParams; procedure ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); override; public constructor Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean = True); destructor Destroy; override; procedure Close; override; end; /// <summary>Represents the factory class for creating an appropriate instance /// of TDSServiceResponseHandler.</summary> TDSResponseHandlerFactory = class public /// <summary> Returns a new instance of the appropriate TDSServiceResponseHandler implementation, /// based on the provided information. /// </summary> class function CreateResponseHandler(DSService: TDSService; RequestInfo: TDSHTTPRequest; CommandType: TDSHTTPCommandType = TDSHTTPCommandType.hcUnknown; HTTPServer: TDSHTTPServer = nil): TDSServiceResponseHandler; overload; /// <summary> Returns a new instance of the appropriate TDSServiceResponseHandler implementation, /// based on the provided information. /// </summary> class function CreateResponseHandler(DSService: TDSService; RequestInfo: TDSHTTPRequest; CommandType: TDSHTTPCommandType; HTTPServer: TDSRESTServer): TDSServiceResponseHandler; overload; end; TDSHTTPServiceComponent = class; TDSCustomCertFiles = class; TDSHTTPService = class(TCustomDSHTTPServerTransport) private FComponentList: TList<TComponent>; FCertFiles: TDSCustomCertFiles; FDefaultPort: Integer; FActive: Boolean; procedure RemoveComponent(const AComponent: TDSHTTPServiceComponent); procedure AddComponent(const AComponent: TDSHTTPServiceComponent); procedure SetCertFiles(const AValue: TDSCustomCertFiles); protected function CreateHttpServer: TDSHTTPServer; override; procedure InitializeHttpServer; override; procedure HTTPOtherContext( AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetHttpPort: Word; virtual; function GetServerSoftware: string; virtual; procedure SetIPImplementationID(const Value: string); override; function IsActive: Boolean; virtual; procedure SetActive(Status: Boolean); virtual; procedure SetHttpPort(const Port: Word); virtual; ///<summary> /// Called by the server when it is starting. ///</summary> procedure Start; override; ///<summary> /// Called by the server when it is stoping. ///</summary> procedure Stop; override; published { Published declarations } /// <summary> HTTP port </summary> [Default(_IPPORT_HTTP)] property HttpPort: Word read GetHttpPort write SetHttpPort default _IPPORT_HTTP; /// <summary> REST URL context like in http://my.site.com/datasnap/rest/... /// In the example above rest denotes that the request is a REST request /// and is processed by REST service /// </summary> /// <summary> True to start the service, false to stop it /// </summary> [Default(False)] property Active: Boolean read IsActive write SetActive default False; /// <summary> Server software, read only /// </summary> property ServerSoftware: string read GetServerSoftware; /// <summary> X.509 certificates and keys</summary> property CertFiles: TDSCustomCertFiles read FCertFiles write SetCertFiles; property IPImplementationID; property DSContext; property RESTContext; property CacheContext; property OnHTTPTrace; property OnFormatResult; property Server; property DSHostname; property DSPort; property Filters; property AuthenticationManager; property CredentialsPassThrough; property DSAuthUser; property DSAuthPassword; property SessionTimeout; end; {$IFNDEF NEXTGEN} TGetPEMFilePasskey = procedure(ASender: TObject; var APasskey: AnsiString) of object; {$ENDIF} TGetPEMFileSBPasskey = procedure(ASender: TObject; APasskey: TStringBuilder) of object; /// <summary>Provides information about X.509 certificates and private keys</summary> /// <remarks>Associate with a TDSHTTPService component to enable server side SSL</remarks> TDSCustomCertFiles = class(TComponent) private FCertFile: string; FKeyFile: string; FRootCertFile: string; {$IFNDEF NEXTGEN} FGetPEMFilePasskey: TGetPEMFilePasskey; {$ENDIF} FGetPEMFileSBPasskey: TGetPEMFileSBPasskey; function GetCertFile: string; function GetKeyFile: string; function GetRootCertFile: string; procedure SetCertFile(const Value: string); procedure SetRootCertFile(const Value: string); procedure SetKeyFile(const Value: string); {$IFNDEF NEXTGEN} procedure SetOnGetPEMFilePasskey(const Value: TGetPEMFilePasskey); function GetOnGetPEMFilePasskey: TGetPEMFilePasskey; {$ENDIF} procedure SetOnGetPEMFileSBPasskey(const Value: TGetPEMFileSBPasskey); function GetOnGetPEMFileSBPasskey: TGetPEMFileSBPasskey; published /// <summary>Provides the HTTP server implementation object with X.509 information</summary> /// <param name="AServer">HTTP server implementation object</param> procedure SetServerProperties(AServer: TObject); virtual; public /// <summary>File of the X.509 root certificate</summary> property RootCertFile: string read GetRootCertFile write SetRootCertFile; /// <summary>File of the X.509 certificate</summary> property CertFile: string read GetCertFile write SetCertFile; /// <summary>File of the X.509 private key</summary> property KeyFile: string read GetKeyFile write SetKeyFile; {$IFNDEF NEXTGEN} /// <summary>Event handler to provide the string used to encrypt the private key in KeyFile</summary> property OnGetPEMFilePasskey: TGetPEMFilePasskey read GetOnGetPEMFilePasskey write SetOnGetPEMFilePasskey; {$ENDIF} /// <summary>Event handler to provide the string used to encrypt the private key in KeyFile</summary> property OnGetPEMFileSBPasskey: TGetPEMFileSBPasskey read GetOnGetPEMFileSBPasskey write SetOnGetPEMFileSBPasskey; end; /// <summary>Provides information about X.509 certificates and private /// keys.</summary> TDSCertFiles = class(TDSCustomCertFiles) published property RootCertFile; property CertFile; property KeyFile; {$IFNDEF NEXTGEN} property OnGetPEMFilePasskey; {$ENDIF} property OnGetPEMFileSBPasskey; end; TDSHTTPServiceComponent = class(TComponent) private FService: TDSHTTPService; procedure SetService(const AValue: TDSHTTPService); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public procedure DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean); virtual; abstract; public published property Service: TDSHTTPService read FService write SetService; end; TDispatchFileEvent = procedure (Sender: TObject; const AFileName: string; AContext: TDSHTTPContext; Request: TDSHTTPRequest; Response: TDSHTTPResponse; var Handled: Boolean) of object; TDSCustomHTTPServiceFileDispatcher = class(TDSHTTPServiceComponent) private FFileDispatcherProperties: TWebFileDispatcherProperties; FBeforeDispatch: TDispatchFileEvent; FAfterDispatch: TDispatchFileEvent; procedure SetWebFileExtensions(const Value: TWebFileExtensions); function GetWebFileExtensions: TWebFileExtensions; procedure SetWebDirectories(const Value: TWebDirectories); function GetWebDirectories: TWebDirectories; function GetRootDirectory: string; procedure SetRootDirectory(const Value: string); function IsRootDirectoryStored: Boolean; public constructor Create(AOwner: TComponent); override; procedure DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean); override; protected procedure DoBeforeDispatch(Sender: TObject; const AFileName: string; AContext: TDSHTTPContext; Request: TDSHTTPRequest; Response: TDSHTTPResponse; var Handled: Boolean); virtual; property BeforeDispatch: TDispatchFileEvent read FBeforeDispatch write FBeforeDispatch; property AfterDispatch: TDispatchFileEvent read FAfterDispatch write FAfterDispatch; property WebFileExtensions: TWebFileExtensions read GetWebFileExtensions write SetWebFileExtensions; property WebDirectories: TWebDirectories read GetWebDirectories write SetWebDirectories; [Stored('IsRootDirectoryStored'), nodefault] property RootDirectory: string read GetRootDirectory write SetRootDirectory stored IsRootDirectoryStored nodefault; end; TDSHTTPServiceFileDispatcher = class(TDSCustomHTTPServiceFileDispatcher) published property BeforeDispatch; property AfterDispatch; property WebFileExtensions; property WebDirectories; property RootDirectory; end; TDSHTTPRequestIndy = class; TDSHTTPResponseIndy = class; /// <summary>Represents the Indy implementation of the DataSnap HTTP /// context.</summary> TDSHTTPContextIndy = class(TDSHTTPContext) private FContext: IIPContext; FRequest: TDSHTTPRequestIndy; FResponse: TDSHTTPResponseIndy; public constructor Create(const AContext: IIPContext; const ARequestInfo: IIPHTTPRequestInfo; const AResponseInfo: IIPHTTPResponseInfo); destructor Destroy; override; function Connected: Boolean; override; /// <summary>Indy Context. Provided so that event handlers can get to Indy specific properties. /// </summary> property Context: IIPContext read FContext; end; /// <summary>A Indy implementation of DataSnap HTTP Request /// </summary> TDSHTTPRequestIndy = class(TDSHTTPRequest) strict private FRequestInfo: IIPHTTPRequestInfo; FDocument: string; protected function GetCommand: string; override; function GetCommandType: TDSHTTPCommandType; override; function GetDocument: string; override; function GetParams: TStrings; override; function GetPostStream: TStream; override; function GetAuthUserName: string; override; function GetAuthPassword: string; override; function GetURI: string; override; function GetPragma: string; override; function GetAccept: string; override; function GetRemoteIP: string; override; function GetUserAgent: string; override; function GetProtocolVersion: string; override; public constructor Create(ARequestInfo: IIPHTTPRequestInfo); /// <summary>Indy RequestInfo. Provided so that event handlers can get to Indy specific properties. /// </summary> property RequestInfo: IIPHTTPRequestInfo read FRequestInfo; end; /// <summary>Indy implementation of DataSnap HTTP Response /// </summary> TDSHTTPResponseIndy = class(TDSHTTPResponse) strict private FResponseInfo: IIPHTTPResponseInfo; strict protected function GetContentStream: TStream; override; function GetResponseNo: Integer; override; function GetResponseText: string; override; procedure SetContentStream(const Value: TStream); override; procedure SetResponseNo(const Value: Integer); override; procedure SetResponseText(const Value: string); override; function GetContentText: string; override; procedure SetContentText(const Value: string); override; function GetContentLength: Int64; override; procedure SetContentLength(const Value: Int64); override; function GetCloseConnection: Boolean; override; procedure SetCloseConnection(const Value: Boolean); override; function GetPragma: string; override; procedure SetPragma(const Value: string); override; function GetContentType: string; override; procedure SetContentType(const Value: string); override; function GetFreeContentStream: Boolean; override; procedure SetFreeContentStream(const Value: Boolean); override; public constructor Create(AResponseInfo: IIPHTTPResponseInfo); procedure SetHeaderAuthentication(const Value: string; const Realm: string); override; /// <summary>Indy ResponseInfo. Provided so that event handlers can get to Indy specific properties. /// </summary> property ResponseInfo: IIPHTTPResponseInfo read FResponseInfo; end; /// <summary>Singleton that manages http applications.</summary> TDSHTTPApplication = class public const // Context object names sSessionObject = 'session'; private class var FInstance: TDSHTTPApplication; private /// <summary> Loads the session with the given session ID and sets it into the thread. </summary> /// <remarks> Pass in an empty string to create a new session </remarks> /// <returns> True if successful, false if passed an expired or invalid session ID </returns> function LoadRESTSession(const SessionId, UserName: string; SessionTimeout: Integer; ASessionLifetime: TDSSessionLifetime; const TunnelService: TDSTunnelService; const AuthManager: TDSCustomAuthenticationManager; const ARequestInfo: TDSHTTPRequest; out IsNewSession: Boolean): Boolean; function GetHTTPDispatch: TDSHTTPDispatch; procedure SetSessionRequestInfo(const ASession: TDSSession; const ARequest: TDSHTTPRequest); function GetDispatching: Boolean; public /// <summary> Checks the request for a Session ID and returns it if one is found. </summary> /// <remarks> Checks the Pragama header and optionally the query parameter of the url. /// If checking both places, the URL parameter takes priority if both locations have values specified. /// </remarks> /// <returns> The found session ID or empty string if none found. </returns> function GetRequestSessionId(const ARequestInfo: TDSHTTPRequest; const CheckURLParams: Boolean = True): string; procedure StartDispatch(const AContext: TDSHTTPContext; const ARequest: TDSHTTPRequest; const AResponse: TDSHTTPResponse); procedure EndDispatch; property Dispatching: Boolean read GetDispatching; property HTTPDispatch: TDSHTTPDispatch read GetHTTPDispatch; class property Instance: TDSHTTPApplication read FInstance; end; implementation uses {$IFNDEF POSIX} Winapi.ActiveX, System.Win.ComObj, {$ENDIF} System.StrUtils, Data.DBXClientResStrs, Data.DBXCommonIndy, Data.DBXJSONCommon, Data.DBXPlatform, System.TypInfo, Datasnap.DSServerResStrs; const DATASNAP_CONTEXT = 'datasnap'; TUNNEL_CONTEXT = 'tunnel'; TUNNEL_INFO_LIST = 'tunnelinfolist'; SESSION_EXPIRED = 'Session has expired'; // do not localize SESSION_EXPIRED_MSG = 'The specified session has expired due to inactivity or was an invalid Session ID'; //do not localize CANNOT_PROCESS_PARAM = 'Query parameter %0:s (%1:s) is not accepted as a valid converter. The converter type might not be registered yet hence the request is rejected'; //do not localize QUERY_PARAM_CONFLICT = 'Query parameters are conflicting. This is usually due to references on the same output parameter'; //do not localize NO_SERVER_DATA = 'Server stopped sending data. The connection was terminated or connection timeout.'; //do not localize PROTOCOL_COMMAND_NOT_SUPPORTED = 'Command %s in request is not supported. Accepted commands are: GET, POST and PUT'; //do not localize INVALID_DATASNAP_CONTEXT = 'Expected datasnap context in request %s'; //do not localize INVALID_REQUEST = 'Invalid request format. (%s)'; //do not localize type TDSHTTPOtherContextEvent = procedure( AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean) of object; TDSHTTPServerIndy = class(TDSHTTPServer) strict private FHTTPOtherContext: TDSHTTPOtherContextEvent; private FServer: IIPHTTPServer; FDefaultPort: Word; FServerSoftware: string; FIPImplementationID: string; FPeerProcs: IIPPeerProcs; function PeerProcs: IIPPeerProcs; function GetActive: Boolean; function GetDefaultPort: Word; procedure SetActive(const Value: Boolean); procedure SetDefaultPort(const Value: Word); procedure DoIndyCommand(AContext: IIPContext; ARequestInfo: IIPHTTPRequestInfo; AResponseInfo: IIPHTTPResponseInfo); function GetServerSoftware: string; procedure SetServerSoftware(const Value: string); property HTTPOtherContext: TDSHTTPOtherContextEvent read FHTTPOtherContext write FHTTPOtherContext; protected function Decode(Data: string): string; override; procedure DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string); override; procedure InitializeServer; virtual; public constructor Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string = ''); override; destructor Destroy; override; property Server: IIPHTTPServer read FServer; property DefaultPort: Word read GetDefaultPort write SetDefaultPort; property Active: Boolean read GetActive write SetActive; property ServerSoftware: string read GetServerSoftware write SetServerSoftware; end; TDSHTTPSServerIndy = class(TDSHTTPServerIndy) private FCertFile: string; FKeyFile: string; FRootCertFile: string; {$IFNDEF NEXTGEN} FOnGetPEMFilePasskey: TGetPEMFilePasskey; {$ENDIF} FOnGetPEMFileSBPasskey: TGetPEMFileSBPasskey; procedure ServerOnConnect(AContext: IIPContext); function GetCertFile: string; function GetKeyFile: string; function GetRootCertFile: string; procedure SetCertFile(const Value: string); procedure SetKeyFile(const Value: string); procedure SetRootCertFile(const Value: string); function GetSSLOptions: IIPSSLOptions; procedure OnGetPassword(APasskey: TStringBuilder); protected procedure DoGetPEMFilePasskey(ASender: TObject; APasskey: TStringBuilder); virtual; procedure InitializeServer; override; property SSLOptions: IIPSSLOptions read GetSSLOptions; public destructor Destroy; override; {$IFNDEF NEXTGEN} property OnGetPEMFilePasskey: TGetPEMFilePasskey read FOnGetPEMFilePasskey write FOnGetPEMFilePasskey; {$ENDIF} property OnGetPEMFileSBPasskey: TGetPEMFileSBPasskey read FOnGetPEMFileSBPasskey write FOnGetPEMFileSBPasskey; property RootCertFile: string read GetRootCertFile write SetRootCertFile; property CertFile: string read GetCertFile write SetCertFile; property KeyFile: string read GetKeyFile write SetKeyFile; end; { TDSHTTPServerIndy } constructor TDSHTTPServerIndy.Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string = ''); begin inherited Create(ADSServer, AIPImplementationID); FIPImplementationID := AIPImplementationID; FServerSoftware := 'DatasnapHTTPService/2011'; end; procedure TDSHTTPServerIndy.InitializeServer; begin if FServer <> nil then begin FServer.UseNagle := False; FServer.KeepAlive := True; FServer.ServerSoftware := FServerSoftware; FServer.DefaultPort := FDefaultPort; FServer.OnCommandGet := Self.DoIndyCommand; FServer.OnCommandOther := Self.DoIndyCommand; end; end; function TDSHTTPServerIndy.PeerProcs: IIPPeerProcs; begin if FPeerProcs = nil then FPeerProcs := IPProcs(FIPImplementationID); Result := FPeerProcs; end; function TDSHTTPServerIndy.Decode(Data: string): string; begin if Data.IndexOf('%') >= 0 then // Optimization Result := PeerProcs.URLDecode(Data) else Result := Data; end; destructor TDSHTTPServerIndy.Destroy; begin inherited; if FServer <> nil then begin FServer.Active := False; FServer := nil; end; end; procedure TDSHTTPServerIndy.DoIndyCommand(AContext: IIPContext; ARequestInfo: IIPHTTPRequestInfo; AResponseInfo: IIPHTTPResponseInfo); var LContext: TDSHTTPContextIndy; begin LContext := TDSHTTPContextIndy.Create(AContext, ARequestInfo, AResponseInfo); try DoCommand(LContext, LContext.FRequest, LContext.FResponse); finally LContext.Free; end; end; procedure TDSHTTPServerIndy.DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string); var LHandled: Boolean; begin LHandled := False; if Assigned(FHTTPOtherContext) then begin FHTTPOtherContext(AContext, ARequestInfo, AResponseInfo, ARequest, LHandled); end; if not LHandled then inherited; end; function TDSHTTPServerIndy.GetActive: Boolean; begin if FServer <> nil then Result := FServer.Active else Result := False; end; function TDSHTTPServerIndy.GetDefaultPort: Word; begin if FServer <> nil then Result := FServer.DefaultPort else Result := FDefaultPort; end; function TDSHTTPServerIndy.GetServerSoftware: string; begin if FServer <> nil then Result := FServer.ServerSoftware else Result := FServerSoftware; end; procedure TDSHTTPServerIndy.SetActive(const Value: Boolean); begin if Value and (FServer = nil) then begin FServer := PeerFactory.CreatePeer(FIPImplementationID, IIPHTTPServer, nil) as IIPHTTPServer; InitializeServer; end; if FServer <> nil then FServer.Active := Value; end; procedure TDSHTTPServerIndy.SetDefaultPort(const Value: Word); begin if FServer <> nil then FServer.DefaultPort := Value else FDefaultPort := Value; end; procedure TDSHTTPServerIndy.SetServerSoftware(const Value: string); begin if FServer <> nil then FServer.ServerSoftware := Value else FServerSoftware := Value; end; { TDSHTTPService } constructor TDSHTTPService.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultPort := _IPPORT_HTTP; FComponentList := TList<TComponent>.Create; // Does not own objects end; procedure TDSHTTPService.RemoveComponent(const AComponent: TDSHTTPServiceComponent); begin if (AComponent <> nil) and (FComponentList <> nil) then FComponentList.Remove(AComponent); end; procedure TDSHTTPService.AddComponent(const AComponent: TDSHTTPServiceComponent); begin if FComponentList.IndexOf(AComponent) = -1 then FComponentList.Add(AComponent); end; function TDSHTTPService.CreateHttpServer: TDSHTTPServer; var LHTTPServer: TDSHTTPServerIndy; begin if Assigned(FCertFiles) then LHTTPServer := TDSHTTPSServerIndy.Create(Self.Server, IPImplementationID) else LHTTPServer := TDSHTTPServerIndy.Create(Self.Server, IPImplementationID); Result := LHTTPServer; LHTTPServer.HTTPOtherContext := HTTPOtherContext; end; procedure TDSHTTPService.HTTPOtherContext( AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean); var I: Integer; LComponent: TComponent; begin for I := 0 to FComponentList.Count - 1 do begin LComponent := FComponentList[I]; if LComponent is TDSHTTPServiceComponent then begin TDSHTTPServiceComponent(LComponent).DoCommand(AContext, ARequestInfo, AResponseInfo, ARequest, AHandled); if AHandled then break; end; end; end; destructor TDSHTTPService.Destroy; begin TDSSessionManager.Instance.TerminateAllSessions(self); ServerCloseAllTunnelSessions; FreeAndNil(FComponentList); inherited; end; function TDSHTTPService.GetHttpPort: Word; begin if Assigned(FHttpServer) then Result := TDSHTTPServerIndy(FHttpServer).DefaultPort else Result := FDefaultPort; end; procedure TDSHTTPService.SetHttpPort(const Port: Word); begin FDefaultPort := Port; if Assigned(FHttpServer) then TDSHTTPServerIndy(FHttpServer).DefaultPort := Port; end; procedure TDSHTTPService.InitializeHttpServer; begin inherited; if FCertFiles <> nil then FCertFiles.SetServerProperties(FHttpServer); TDSHTTPServerIndy(FHttpServer).DefaultPort := FDefaultPort; TDSHTTPServerIndy(FHttpServer).Active := FActive; end; function TDSHTTPService.IsActive: Boolean; begin if Assigned(FHttpServer) then Result := TDSHTTPServerIndy(FHttpServer).Active else Result := FActive; end; procedure TDSHTTPService.SetActive(Status: Boolean); begin if not Status then ServerCloseAllTunnelSessions; FActive := Status; if Assigned(FHttpServer) then TDSHTTPServerIndy(FHttpServer).Active := Status else if not (csLoading in ComponentState) then // Create FHttpServer if FActive then RequiresServer; end; procedure TDSHTTPService.SetCertFiles(const AValue: TDSCustomCertFiles); begin if (AValue <> FCertFiles) then begin if Assigned(FCertFiles) then RemoveFreeNotification(FCertFiles); FCertFiles := AValue; if Assigned(FCertFiles) then FreeNotification(FCertFiles); end; end; procedure TDSHTTPService.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FCertFiles) then FCertFiles := nil; end; function TDSHTTPService.GetServerSoftware: string; begin if not (csLoading in ComponentState) then RequiresServer; if FHttpServer <> nil then Result := TDSHTTPServerIndy(FHttpServer).ServerSoftware else Result := ''; end; procedure TDSHTTPService.SetIPImplementationID(const Value: string); begin if IsActive then raise TDSServiceException.Create(sCannotChangeIPImplID); inherited SetIPImplementationID(Value); end; procedure TDSHTTPService.Stop; begin TDSSessionManager.Instance.TerminateAllSessions(self); SetActive(False); inherited; end; procedure TDSHTTPService.Start; begin inherited; RequiresServer; if Assigned(FHttpServer) then begin if FCertFiles <> nil then FCertFiles.SetServerProperties(FHttpServer); TDSHTTPServerIndy(FHttpServer).Active := True; end; end; { TDSHTTPResponseIndy } constructor TDSHTTPResponseIndy.Create(AResponseInfo: IIPHTTPResponseInfo); begin FResponseInfo := AResponseInfo; end; procedure TDSHTTPResponseIndy.SetHeaderAuthentication(const Value: string; const Realm: string); begin FResponseInfo.AuthRealm := Realm; FResponseInfo.WWWAuthenticate.Add('Basic realm="' + Realm + '", charset="UTF-8"'); end; function TDSHTTPResponseIndy.GetCloseConnection: Boolean; begin Result := FResponseInfo.CloseConnection; end; function TDSHTTPResponseIndy.GetContentLength: Int64; begin Result := FResponseInfo.ContentLength; end; function TDSHTTPResponseIndy.GetContentStream: TStream; begin Result := FResponseInfo.ContentStream; end; function TDSHTTPResponseIndy.GetContentText: string; begin Result := FResponseInfo.ContentText; end; function TDSHTTPResponseIndy.GetContentType: string; begin Result := FResponseInfo.ContentType; end; function TDSHTTPResponseIndy.GetFreeContentStream: Boolean; begin Result := FResponseInfo.FreeContentStream; end; function TDSHTTPResponseIndy.GetPragma: string; begin Result := FResponseInfo.Pragma; end; function TDSHTTPResponseIndy.GetResponseNo: Integer; begin Result := FResponseInfo.ResponseNo; end; function TDSHTTPResponseIndy.GetResponseText: string; begin Result := FResponseInfo.ResponseText; end; procedure TDSHTTPResponseIndy.SetCloseConnection(const Value: Boolean); begin FResponseInfo.CloseConnection := Value; end; procedure TDSHTTPResponseIndy.SetContentLength(const Value: Int64); begin FResponseInfo.ContentLength := Value; end; procedure TDSHTTPResponseIndy.SetContentStream(const Value: TStream); begin FResponseInfo.ContentStream := Value; end; procedure TDSHTTPResponseIndy.SetContentText(const Value: string); begin FResponseInfo.ContentText := Value; end; procedure TDSHTTPResponseIndy.SetContentType(const Value: string); begin FResponseInfo.ContentType := Value; end; procedure TDSHTTPResponseIndy.SetFreeContentStream(const Value: Boolean); begin FResponseInfo.FreeContentStream := Value; end; procedure TDSHTTPResponseIndy.SetPragma(const Value: string); begin inherited; FResponseInfo.Pragma := Value; end; procedure TDSHTTPResponseIndy.SetResponseNo(const Value: Integer); begin FResponseInfo.ResponseNo := Value; end; procedure TDSHTTPResponseIndy.SetResponseText(const Value: string); begin FResponseInfo.ResponseText := Value; end; { TDSHTTPRequestIndy } constructor TDSHTTPRequestIndy.Create(ARequestInfo: IIPHTTPRequestInfo); begin FRequestInfo := ARequestInfo; end; function TDSHTTPRequestIndy.GetAccept: string; begin Result := FRequestInfo.Accept; end; function TDSHTTPRequestIndy.GetAuthPassword: string; begin Result := FRequestInfo.AuthPassword; end; function TDSHTTPRequestIndy.GetAuthUserName: string; begin Result := FRequestInfo.AuthUserName; end; function TDSHTTPRequestIndy.GetCommand: string; begin Result := FRequestInfo.Command; end; function TDSHTTPRequestIndy.GetCommandType: TDSHTTPCommandType; begin case FRequestInfo.CommandType of THTTPCommandTypePeer.hcUnknown: Result := TDSHTTPCommandType.hcUnknown; THTTPCommandTypePeer.hcGET: Result := TDSHTTPCommandType.hcGET; THTTPCommandTypePeer.hcPOST: Result := TDSHTTPCommandType.hcPOST; THTTPCommandTypePeer.hcDELETE: Result := TDSHTTPCommandType.hcDELETE; THTTPCommandTypePeer.hcPUT: Result := TDSHTTPCommandType.hcPUT; THTTPCommandTypePeer.hcTRACE, THTTPCommandTypePeer.hcHEAD, THTTPCommandTypePeer.hcOPTION: Result := TDSHTTPCommandType.hcOther; else //Result := TDSHTTPCommandType.hcUnknown; raise TDSServiceException.Create(sUnknownCommandType); end; end; function TDSHTTPRequestIndy.GetDocument: string; var {$IFDEF NEXTGEN} RawStr: array of byte; {$ELSE} RawStr: RawByteString; {$ENDIF} Count, I: Integer; CharCode: SmallInt; begin // RAID 272624: Indy doesn't properly decodes the encoded URLs; this will be fixed in // Indy 11 we are told. If so, this code can be replaced with // // Result := LRequestInfo.Document // if FDocument = EmptyStr then begin Count := FRequestInfo.Document.Length; {$IFDEF NEXTGEN} SetLength(RawStr, Count); {$ELSE} RawStr := ''; {$ENDIF} for I := 0 to Count - 1 do begin CharCode := Ord(FRequestInfo.Document.Chars[I]); if CharCode > 255 then begin FDocument := FRequestInfo.Document; Exit(FDocument) end; {$IFDEF NEXTGEN} RawStr[I] := Byte(CharCode); {$ELSE} RawStr := RawStr + AnsiChar(CharCode); {$ENDIF} end; FDocument := UTF8ToString(RawStr) end; Exit(FDocument); end; function TDSHTTPRequestIndy.GetParams: TStrings; begin Result := FRequestInfo.Params; end; function TDSHTTPRequestIndy.GetPostStream: TStream; begin Result := FRequestInfo.PostStream; end; function TDSHTTPRequestIndy.GetPragma: string; begin Result := FRequestInfo.Pragma; end; function TDSHTTPRequestIndy.GetRemoteIP: string; begin Result := FRequestInfo.RemoteIP; end; function TDSHTTPRequestIndy.GetURI: string; begin Result := FRequestInfo.URI; end; function TDSHTTPRequestIndy.GetUserAgent: string; begin Result := FRequestInfo.UserAgent; end; function TDSHTTPRequestIndy.GetProtocolVersion: string; begin Result := FRequestInfo.Version; end; { TDSHTTPContextIndy } function TDSHTTPContextIndy.Connected: Boolean; begin Result := FContext.Connection.Connected; end; constructor TDSHTTPContextIndy.Create(const AContext: IIPContext; const ARequestInfo: IIPHTTPRequestInfo; const AResponseInfo: IIPHTTPResponseInfo); begin inherited Create; FContext := AContext; FRequest := TDSHTTPRequestIndy.Create(ARequestInfo); FResponse := TDSHTTPResponseIndy.Create(AResponseInfo); end; destructor TDSHTTPContextIndy.Destroy; begin FRequest.Free; FResponse.Free; inherited; end; { TDSHTTPServiceComponent } procedure TDSHTTPServiceComponent.SetService(const AValue: TDSHTTPService); begin if (AValue <> Service) then begin if Assigned(Service) then RemoveFreeNotification(Service); if Assigned(AValue) then FreeNotification(AValue); end; if FService <> nil then FService.RemoveComponent(self); if AValue <> nil then AValue.AddComponent(self); self.FService := AValue; end; procedure TDSHTTPServiceComponent.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FService) then FService := nil; end; type TIndyDispatchFileRequest = class(TDispatchFileRequest) private FContext: TDSHTTPContextIndy; FRequestInfo: TDSHTTPRequestIndy; FResponseInfo: TDSHTTPResponseIndy; FComponent: TDSCustomHTTPServiceFileDispatcher; protected function IsGetRequest: Boolean; override; function IsHeadRequest: Boolean; override; procedure SetErrorCode(AStatusCode: Integer); override; function GetIfModifiedSince: TDateTime; override; procedure SetContentStream(AStream: TStream); override; procedure SetContentLength(ALength: Integer); override; procedure SetContentType(const AValue: string); override; procedure SetLastModified(AValue: TDateTime); override; function GetExceptionClass: TClass; override; procedure DoBeforeDispatch(const AFileName: string; var AHandled: Boolean); override; procedure DoAfterDispatch(const AFileName: string; var AHandled: Boolean); override; function GetRequestPathInfo: string; override; function GetResponseSent: Boolean; override; public constructor Create(AComponent: TDSCustomHTTPServiceFileDispatcher; AContext: TDSHTTPContextIndy; ARequestInfo: TDSHTTPRequestIndy; AResponseInfo: TDSHTTPResponseIndy); end; { TIndyDispatchFileRequest } constructor TIndyDispatchFileRequest.Create(AComponent: TDSCustomHTTPServiceFileDispatcher; AContext: TDSHTTPContextIndy; ARequestInfo: TDSHTTPRequestIndy; AResponseInfo: TDSHTTPResponseIndy); begin inherited Create(AComponent.FFileDispatcherProperties); FComponent := AComponent; FContext := AContext; FRequestInfo := ARequestInfo; FResponseInfo := AResponseInfo; end; function TIndyDispatchFileRequest.IsGetRequest: Boolean; begin Result := FRequestInfo.RequestInfo.CommandType = THTTPCommandTypePeer.hcGET; end; function TIndyDispatchFileRequest.IsHeadRequest: Boolean; begin Result := FRequestInfo.RequestInfo.CommandType = THTTPCommandTypePeer.hcHEAD; end; procedure TIndyDispatchFileRequest.SetErrorCode(AStatusCode: Integer); begin FResponseInfo.ResponseInfo.ResponseNo := AStatusCode; end; function TIndyDispatchFileRequest.GetIfModifiedSince: TDateTime; begin Result := IPProcs(FRequestInfo.RequestInfo.GetIPImplementationID).GMTToLocalDateTime(FRequestInfo.RequestInfo.RawHeaders.Values['If-Modified-Since']); {do not localize} end; procedure TIndyDispatchFileRequest.SetContentStream(AStream: TStream); begin FResponseInfo.ResponseInfo.ContentStream := AStream; end; procedure TIndyDispatchFileRequest.SetContentLength(ALength: Integer); begin FResponseInfo.ResponseInfo.ContentLength := ALength; end; procedure TIndyDispatchFileRequest.SetContentType(const AValue: string); begin FResponseInfo.ResponseInfo.ContentType := AValue; end; procedure TIndyDispatchFileRequest.SetLastModified(AValue: TDateTime); begin TDSHTTPRequestIndy(FRequestInfo).RequestInfo.LastModified := AValue; end; function TIndyDispatchFileRequest.GetExceptionClass: TClass; begin Result := Exception; end; procedure TIndyDispatchFileRequest.DoBeforeDispatch(const AFileName: string; var AHandled: Boolean); begin FComponent.DoBeforeDispatch(FComponent, AFileName, FContext, FRequestInfo, FResponseInfo, AHandled); end; procedure TIndyDispatchFileRequest.DoAfterDispatch(const AFileName: string; var AHandled: Boolean); begin if Assigned(FComponent.FAfterDispatch) then FComponent.FAfterDispatch(FComponent, AFileName, FContext, FRequestInfo, FResponseInfo, AHandled); if (not FResponseInfo.ResponseInfo.HeaderHasBeenWritten) and (FResponseInfo.ResponseInfo.ContentText = '') then begin // Force write of error message FResponseInfo.ResponseInfo.WriteHeader; FResponseInfo.ResponseInfo.WriteContent; end; end; { TIndyDispatchFileRequest } function TIndyDispatchFileRequest.GetRequestPathInfo: string; begin Result := FRequestInfo.Document; end; function TIndyDispatchFileRequest.GetResponseSent: Boolean; begin Result := False; end; { TDSCustomHTTPServiceFileDispatcher } constructor TDSCustomHTTPServiceFileDispatcher.Create(AOwner: TComponent); begin inherited; FFileDispatcherProperties := TWebFileDispatcherProperties.Create(Self); end; procedure TDSCustomHTTPServiceFileDispatcher.DoBeforeDispatch(Sender: TObject; const AFileName: string; AContext: TDSHTTPContext; Request: TDSHTTPRequest; Response: TDSHTTPResponse; var Handled: Boolean); begin if Assigned(FBeforeDispatch) then FBeforeDispatch(Sender, AFileName, AContext, Request, Response, Handled); end; procedure TDSCustomHTTPServiceFileDispatcher.DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string; var AHandled: Boolean); var LDispatcher: TIndyDispatchFileRequest; begin AHandled := False; if AContext is TDSHTTPContextIndy then begin LDispatcher := TIndyDispatchFileRequest.Create(Self, TDSHTTPContextIndy(AContext), TDSHTTPRequestIndy(ARequestInfo), TDSHTTPResponseIndy(AResponseInfo)); try AHandled := LDispatcher.DispatchFileRequest; finally LDispatcher.Free; end; end; end; function TDSCustomHTTPServiceFileDispatcher.GetWebDirectories: TWebDirectories; begin Result := FFileDispatcherProperties.WebDirectories; end; function TDSCustomHTTPServiceFileDispatcher.GetRootDirectory: string; begin Result := FFileDispatcherProperties.RootDirectory; end; function TDSCustomHTTPServiceFileDispatcher.GetWebFileExtensions: TWebFileExtensions; begin Result := FFileDispatcherProperties.WebFileExtensions; end; procedure TDSCustomHTTPServiceFileDispatcher.SetWebDirectories( const Value: TWebDirectories); begin FFileDispatcherProperties.WebDirectories := Value; end; procedure TDSCustomHTTPServiceFileDispatcher.SetRootDirectory(const Value: string); begin FFileDispatcherProperties.RootDirectory := Value; end; function TDSCustomHTTPServiceFileDispatcher.IsRootDirectoryStored: Boolean; begin Result := not SameText(GetRootDirectory, '.'); end; procedure TDSCustomHTTPServiceFileDispatcher.SetWebFileExtensions( const Value: TWebFileExtensions); begin FFileDispatcherProperties.WebFileExtensions := Value; end; { TDSCertFiles } function TDSCustomCertFiles.GetCertFile: string; begin Result := FCertFile; end; function TDSCustomCertFiles.GetKeyFile: string; begin Result := FKeyFile; end; {$IFNDEF NEXTGEN} procedure TDSCustomCertFiles.SetOnGetPEMFilePasskey( const Value: TGetPEMFilePasskey); begin FGetPEMFilePasskey := Value; end; {$ENDIF} procedure TDSCustomCertFiles.SetOnGetPEMFileSBPasskey( const Value: TGetPEMFileSBPasskey); begin FGetPEMFileSBPasskey := Value; end; function TDSCustomCertFiles.GetRootCertFile: string; begin Result := FRootCertFile; end; procedure TDSCustomCertFiles.SetCertFile(const Value: string); begin FCertFile := Value; end; procedure TDSCustomCertFiles.SetKeyFile(const Value: string); begin FKeyFile := Value; end; {$IFNDEF NEXTGEN} function TDSCustomCertFiles.GetOnGetPEMFilePasskey: TGetPEMFilePasskey; begin Result := FGetPEMFilePassKey; end; {$ENDIF} function TDSCustomCertFiles.GetOnGetPEMFileSBPasskey: TGetPEMFileSBPasskey; begin Result := FGetPEMFileSBPassKey; end; procedure TDSCustomCertFiles.SetRootCertFile(const Value: string); begin FRootCertFile := Value; end; procedure TDSCustomCertFiles.SetServerProperties(AServer: TObject); var LServer: TDSHTTPSServerIndy; begin if AServer is TDSHTTPSServerIndy then begin LServer := TDSHTTPSServerIndy(AServer); LServer.CertFile := CertFile; LServer.KeyFile := KeyFile; LServer.RootCertFile := RootCertFile; LServer.OnGetPEMFileSBPasskey := OnGetPEMFileSBPasskey; {$IFNDEF NEXTGEN} LServer.OnGetPEMFilePasskey := OnGetPEMFilePasskey; {$ENDIF} end else begin raise TDSServiceException.Create(Format(SUnknownServerType, [AServer.ClassName])); end; end; { TDSHTTPSServerIndy } destructor TDSHTTPSServerIndy.Destroy; begin inherited; end; (* << Client>>> Create a VCL Application and drop a TIdTCPClient and a TIdSSLIOHandlerSocketOpenSSL on the form. Set the TIdTCPClient's Host to localhost, Port to 16000 and IOHandler to the SSL IOHandler. Next, alter the SSL options so that Method is set to sslvSSLv3 and Mode is set to sslmClient. Next create OnCreate/OnDestroy event handlers for the form and in that put Client.Connect/Client.Disconnect respectively. Compile. << Server>> Create a VCL Application and drop a TIdCMDTcpServer and a TIdServerIOHandlerSSLOpenSSL on the form. Set the TIdCMDTCPServer's Bindings to 127.0.0.1:16000 and IOHandler to the SSL IOHandler. Next alter the SSL options so that Method is set to sslvSSLv3 and Mode is set to sslmServer. Set CertFile to server.cert, KeyFile to server.key and RootCertFile to ca.cert. Next, create event handlers for the form OnCreate/OnDestroy to Server.Active := True/Server.Active := False respectively. Compile. *) function TDSHTTPSServerIndy.GetSSLOptions: IIPSSLOptions; var Handler: IIPServerIOHandlerSSLOpenSSL; begin if Server <> nil then begin if not Supports(Server.IOHandler, IIPServerIOHandlerSSLOpenSSL, Handler) then raise TDSServiceException.Create(sUnsupportedServerIOHandler); Result := Handler.SSLOptions; end; end; function TDSHTTPSServerIndy.GetCertFile: string; begin if SSLOptions <> nil then Result := SSLOptions.CertFile else Result := FCertFile; end; function TDSHTTPSServerIndy.GetKeyFile: string; begin if SSLOptions <> nil then Result := SSLOptions.KeyFile else Result := FKeyFile; end; function TDSHTTPSServerIndy.GetRootCertFile: string; begin if SSLOptions <> nil then Result := SSLOptions.RootCertFile else Result := FRootCertFile; end; procedure TDSHTTPSServerIndy.InitializeServer; var LIOHandler: IIPServerIOHandlerSSLOpenSSL; begin inherited; if Server <> nil then begin LIOHandler := PeerFactory.CreatePeer(IPImplementationID, IIPServerIOHandlerSSLOpenSSL, Server.GetObject as TComponent) as IIPServerIOHandlerSSLOpenSSL; //TIdServerIOHandlerSSLOpenSSL.Create(Server); LIOHandler.SSLOptions.Method := TIPSSLVersionPeer.sslvTLSv1; LIOHandler.SSLOptions.Mode := TIPSSLModePeer.sslmServer; LIOHandler.SSLOptions.CertFile := FCertFile; LIOHandler.SSLOptions.RootCertFile := FRootCertFile; LIOHandler.SSLOptions.KeyFile := FKeyFile; LIOHandler.OnGetPassword := OnGetPassword; Server.IOHandler := LIOHandler; Assert(not Assigned(Server.OnConnect)); Server.OnConnect := ServerOnConnect; end; end; procedure TDSHTTPSServerIndy.OnGetPassword(APasskey: TStringBuilder); begin DoGetPEMFilePasskey(Self, APasskey); end; procedure TDSHTTPSServerIndy.DoGetPEMFilePasskey(ASender : TObject; APasskey: TStringBuilder); {$IFNDEF NEXTGEN} var LPass: AnsiString; {$ENDIF} begin if Assigned(FOnGetPEMFileSBPasskey) then FOnGetPEMFileSBPasskey(ASender, APasskey) {$IFNDEF NEXTGEN} else if Assigned(FOnGetPEMFilePasskey) then begin LPass := AnsiString(APasskey.ToString); FOnGetPEMFilePasskey(ASender, LPass); APasskey.Clear; APasskey.Append(LPass); end; {$ENDIF} end; procedure TDSHTTPSServerIndy.ServerOnConnect(AContext: IIPContext); var Handler: IIPSSLIOHandlerSocketBase; begin // Passthrough = False to enable SSL. Indy supports SSL on a per connection basis. // For DataSnap, SSL is always enabled for an HTTPS connection if not Supports(AContext.Connection.IOHandler, IIPSSLIOHandlerSocketBase, Handler) then raise TDSServiceException.Create(sUnsupportedServerIOHandler); Handler.PassThrough := False; end; procedure TDSHTTPSServerIndy.SetCertFile(const Value: string); begin if SSLOptions <> nil then SSLOptions.CertFile := Value else FCertFile := Value; end; procedure TDSHTTPSServerIndy.SetKeyFile(const Value: string); begin if SSLOptions <> nil then SSLOptions.KeyFile := Value else FKeyFile := Value; end; procedure TDSHTTPSServerIndy.SetRootCertFile(const Value: string); begin if SSLOptions <> nil then SSLOptions.RootCertFile := Value else FRootCertFile := Value; end; {TDSHTTPServer} constructor TDSRESTServer.Create; begin Create(nil, ''); end; constructor TDSRESTServer.Create(const AIPImplementationID: string); begin Create(nil, AIPImplementationID); end; constructor TDSRESTServer.Create(const ADSServer: TDSCustomServer); begin Create(ADSServer, ''); end; constructor TDSRESTServer.Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string); begin inherited Create; FDSServer := ADSServer; FIPImplementationID := AIPImplementationID; // Default values defined elsewhere // FRESTContext := REST_CONTEXT; // FCacheContext := CACHE_CONTEXT; // FDSContext := DATASNAP_CONTEXT; // FDSHostname := 'localhost'; // FDSPort := 211; // FCredentialsPassThrough := false; // FSessionTimeout := 1200000; // FDSAuthUser := EmptyStr; // FDSAuthPassword := EmptyStr; FResultEvent := nil; FProtocolHandlerFactory := nil; end; constructor TDSHTTPServer.Create(const ADSServer: TDSCustomServer; const AIPImplementationID: string); begin inherited; FTunnelService := TDSTunnelService.Create(FDSHostname, FDSPort, FFilters, FProtocolHandlerFactory); //Listen for a session closing event and close the session's tunnel, if one exists FSessionEvent := procedure(Sender: TObject; const EventType: TDSSessionEventType; const Session: TDSSession) begin case EventType of SessionClose: CloseSessionTunnels(Session); end; end; TDSSessionManager.Instance.AddSessionEvent(FSessionEvent); end; destructor TDSRESTServer.Destroy; begin FreeAndNil(FProtocolHandlerFactory); inherited; end; destructor TDSHTTPServer.Destroy; begin if Assigned(FSessionEvent) then begin if TDSSessionManager.Instance <> nil then TDSSessionManager.Instance.RemoveSessionEvent(FSessionEvent); FSessionEvent := nil; end; FreeAndNil(FTunnelService); inherited; end; procedure TDSRESTServer.CreateProtocolHandlerFactory(ATransport: TDSServerTransport); begin FreeAndNil(FProtocolHandlerFactory); FProtocolHandlerFactory := TDSJSONProtocolHandlerFactory.Create(ATransport); //TunnelService.ProtocolHandlerFactory := FProtocolHandlerFactory; end; procedure TDSHTTPServer.CreateProtocolHandlerFactory(ATransport: TDSServerTransport); begin inherited; TunnelService.ProtocolHandlerFactory := FProtocolHandlerFactory; end; procedure TDSRESTServer.ClearProtocolHandlerFactory; begin FreeAndNil(FProtocolHandlerFactory); end; procedure TDSHTTPServer.ClearProtocolHandlerFactory; begin inherited; TunnelService.ProtocolHandlerFactory := nil; end; function TDSHTTPServer.GetTunnelService: TDSTunnelService; begin if FTunnelService = nil then FTunnelService := TDSTunnelService.Create(FDSHostname, FDSPort, FFilters, FProtocolHandlerFactory); Result := FTunnelService; end; procedure TDSHTTPServer.CloseAllTunnelSessions; begin if FTunnelService <> nil then FTunnelService.TerminateAllSessions; end; procedure TDSRESTServer.CloseRESTSession(Session: TDSSession; ResponseInfo: TDSHTTPResponse); begin Assert(ResponseInfo <> nil); if (Session <> nil) then begin try TDSSessionManager.Instance.CloseSession(Session.SessionName); ResponseInfo.ResponseNo := 200; ResponseInfo.ResponseText := '{"result":[true]}'; except end; end else begin ResponseInfo.ResponseNo := 400; ResponseInfo.ResponseText := SESSION_EXPIRED_MSG; end; end; function TDSHTTPServer.GetCacheContext: string; begin Result := FCacheContext + '/'; end; function TDSRESTServer.IsClosingSession(const Request: string): Boolean; begin Result := AnsiStartsText('/CloseSession/', Request); end; const sDSAdmin = '/DSAdmin/'; function TDSRESTServer.IsClosingClientChannel(const Request: string): Boolean; begin Result := AnsiStartsText(sDSAdmin + 'CloseClientChannel/', Request) or AnsiStartsText(sDSAdmin + '%22CloseClientChannel%22/', Request); end; function TDSRESTServer.IsOpeningClientChannel(const Request: string): Boolean; begin Result := AnsiStartsText(sDSAdmin + 'ConsumeClientChannel/', Request) or AnsiStartsText(sDSAdmin + '%22ConsumeClientChannel%22/', Request); end; procedure TDSRESTServer.CheckClientChannelMethod(const Request: string); begin if AnsiStartsText(sDSAdmin, Request) then if IsOpeningClientChannel(Request) or IsClosingClientChannel(Request) then raise TDSServiceException.CreateFmt(sChannelMethodsNotSupported, [ClassName]); end; function TDSHTTPServer.GetClientChannelInfo(Request: string; out ChannelName, ClientChannelId, ClientCallbackID, SecurityToken: string): Boolean; var OpeningClientChannel: Boolean; Tokens: TStringList; begin Result := False; OpeningClientChannel := IsOpeningClientChannel(Request); if OpeningClientChannel or IsClosingClientChannel(Request) then begin Tokens := TStringList.Create; Tokens.Delimiter := '/'; Tokens.DelimitedText := Request; try if (OpeningClientChannel and (Tokens.Count > 7)) or (Tokens.Count > 5) then begin ChannelName := Tokens[3]; ClientChannelId := Tokens[4]; if OpeningClientChannel then begin ClientCallbackID := Tokens[5]; SecurityToken := Tokens[7]; end else SecurityToken := Tokens[5]; Result := ClientChannelId <> EmptyStr; end; finally FreeAndNil(Tokens); end; end; end; function TDSRESTServer.GetDsContext: string; begin Result := FDSContext + '/'; end; function TDSRESTServer.GetRestContext: string; begin Result := FRESTContext + '/'; end; procedure TDSRESTServer.SetAuthenticationManager( AuthenticationManager: TDSCustomAuthenticationManager); begin FDSHTTPAuthenticationManager := AuthenticationManager; end; procedure TDSHTTPServer.SetAuthenticationManager( AuthenticationManager: TDSCustomAuthenticationManager); begin inherited; if FTunnelService <> nil then FTunnelService.DSAuthenticationManager := AuthenticationManager; end; procedure TDSHTTPServer.SetCacheContext(const ctx: string); begin if (ctx <> EmptyStr) and (ctx.Chars[ctx.Length - 1] = '/') then FCacheContext := ctx.Substring(0, ctx.Length - 1) else FCacheContext := ctx; end; procedure TDSRESTServer.SetDsContext(const ctx: string); begin if (ctx <> EmptyStr) and (ctx.Chars[ctx.Length - 1] = '/') then FDSContext := ctx.Substring(0, ctx.Length - 1) else FDSContext := ctx; end; procedure TDSHTTPServer.SetDSHostname(AHostname: string); begin FDSHostname := AHostname; TunnelService.DSHostname := AHostname; end; procedure TDSHTTPServer.SetDSPort(APort: Integer); begin FDSPort := Aport; TunnelService.DSPort := APort; end; procedure TDSRESTServer.SetDSServerName(AName: string); begin FDSServerName := AName; end; procedure TDSHTTPServer.SetDSServerName(AName: string); begin inherited; TunnelService.HasLocalServer := AName <> EmptyStr; end; procedure TDSHTTPServer.SetFilters(AFilterCollection: TTransportFilterCollection); begin FFilters := AFilterCollection; TunnelService.Filters := AFilterCollection; end; procedure TDSRESTServer.SetRestContext(const ctx: string); begin if (ctx <> EmptyStr) and (ctx.Chars[ctx.Length - 1] = '/') then FRESTContext := ctx.Substring(0, ctx.Length - 1) else FRESTContext := ctx; end; procedure TDSHTTPServer.CloseSessionTunnels(Session: TDSSession); var RESTService: TDSRESTService; CloseTunnelRequest: string; RespHandler: TDSServiceResponseHandler; Obj: TObject; InfoList: TList<TDSSessionTunnelInfo>; Info: TDSSessionTunnelInfo; I: Integer; begin InfoList := nil; if Session.HasObject(TUNNEL_INFO_LIST) then begin Obj := Session.GetObject(TUNNEL_INFO_LIST); if Obj Is TList<TDSSessionTunnelInfo> then InfoList := TList<TDSSessionTunnelInfo>(Obj); end; if (Session <> nil) and (InfoList <> nil) then begin for I := 0 to (InfoList.Count - 1) do begin Info := InfoList.Items[I]; CloseTunnelRequest := Format('/DSAdmin/CloseClientChannel/%s/%s/', [Info.ClientChannelId, Info.SecurityToken]); RESTService := CreateRESTService(Info.AuthUser, Info.AuthPassword); RespHandler := TDSResponseHandlerFactory.CreateResponseHandler(RESTService, nil, TDSHTTPCommandType.hcGET); try try RESTService.ProcessGETRequest(CloseTunnelRequest, nil, nil, RespHandler); except end; finally FreeAndNil(RespHandler); end; end; end; end; procedure TDSRESTServer.UpdateSessionTunnelHook(const Request: string; Session: TDSSession; RequestInfo: TDSHTTPRequest); begin CheckClientChannelMethod(Request); end; procedure TDSHTTPServer.UpdateSessionTunnelHook(const Request: string; Session: TDSSession; RequestInfo: TDSHTTPRequest); var SessionChannelName: string; SessionClientChannelId: string; SessionSecurityToken: string; SessionClientCallbackID: string; Obj: TObject; Info: TDSSessionTunnelInfo; InfoList: TList<TDSSessionTunnelInfo>; I: Integer; begin Assert(Session <> nil); Assert(RequestInfo <> nil); if IsOpeningClientChannel(Request) then begin if GetClientChannelInfo(Request, SessionChannelName, SessionClientChannelId, SessionClientCallbackID, SessionSecurityToken) then begin if SessionClientCallbackID <> '' then begin Info.ChannelName := SessionChannelName; Info.ClientChannelId := SessionClientChannelId; Info.SecurityToken := SessionSecurityToken; Info.AuthUser := RequestInfo.AuthUserName; Info.AuthPassword := RequestInfo.AuthPassword; if not Session.HasObject(TUNNEL_INFO_LIST) then Session.PutObject(TUNNEL_INFO_LIST, TList<TDSSessionTunnelInfo>.Create); Obj := Session.GetObject(TUNNEL_INFO_LIST) ; if (Obj Is TList<TDSSessionTunnelInfo>) then TList<TDSSessionTunnelInfo>(Obj).Add(Info); end; end; end else if IsClosingClientChannel(Request) then begin if GetClientChannelInfo(Request, SessionChannelName, SessionClientChannelId, SessionClientCallbackID, SessionSecurityToken) then begin Obj := Session.GetObject(TUNNEL_INFO_LIST); //SessionClientChannelId if Obj Is TList<TDSSessionTunnelInfo> then begin InfoList := TList<TDSSessionTunnelInfo>(Obj); for I := 0 to (InfoList.Count - 1) do begin Info := InfoList.Items[I]; if (SessionClientChannelId = Info.ClientChannelId) and (SessionSecurityToken = Info.SecurityToken) then begin InfoList.Delete(I); Exit; end; end; end; end; end; end; function TDSRESTServer.ByteContent(DataStream: TStream): TArray<Byte>; var Buffer: TArray<Byte>; begin if not Assigned(DataStream) then exit(nil); SetLength(Buffer, DataStream.Size); // the content may have been read DataStream.Position := 0; if DataStream.Size > 0 then DataStream.Read(Buffer[0], DataStream.Size); Result := Buffer; end; function TDSRESTServer.ByteContent(JsonValue: TJSONValue): TArray<Byte>; var Buffer: TArray<Byte>; begin SetLength(Buffer, JsonValue.EstimatedByteSize); SetLength(Buffer, JsonValue.ToBytes(Buffer, 0)); Result := Buffer; end; function TDSHTTPApplication.GetRequestSessionId(const ARequestInfo: TDSHTTPRequest; const CheckURLParams: Boolean): string; var SessionID: string; PragmaStr: string; PragmaList: TStringList; begin //empty string will be returned for session ID unless found in Pragma header SessionID := ''; if CheckURLParams then begin SessionID := ARequestInfo.Params.Values['SESSIONID']; if SessionID = '' then SessionID := ARequestInfo.Params.Values['sid']; end; //if no session ID is given in the URL, then try to load it from the Pragma header field if SessionID = '' then begin PragmaStr := ARequestInfo.Pragma; if PragmaStr <> '' then begin PragmaList := TStringList.Create; PragmaList.CommaText := PragmaStr; //Pragma is a comma-separaged list of keys with optional value pairings. //session id is stored as a key/value pair with "dssession" as the key SessionID := PragmaList.Values['dssession']; FreeAndNil(PragmaList); end; end; Result := SessionID; end; function TDSHTTPApplication.LoadRESTSession(const SessionId: string; const UserName: string; SessionTimeout: Integer; ASessionLifetime: TDSSessionLifetime; const TunnelService: TDSTunnelService; const AuthManager: TDSCustomAuthenticationManager; const ARequestInfo: TDSHTTPRequest; out IsNewSession: Boolean): Boolean; var Session: TDSSession; LDispatch: TDSHTTPDispatch; begin TDSSessionManager.ClearThreadSession; //if session id wasn't specified then create a new session if SessionID = '' then begin IsNewSession := True; Session := TDSSessionManager.Instance.CreateSession<TDSRESTSession>(function: TDSSession begin Result := TDSRESTSession.Create(AuthManager); Result.ObjectCreator := TunnelService; //populate session data while creating, so session event fires with data already populated SetSessionRequestInfo(Result, ARequestInfo); end, UserName, ASessionLifetime); Assert(ASessionLifetime = Session.SessionLifetime); Session.LifeDuration := SessionTimeout; case Session.SessionLifetime of TDSSessionLifetime.TimeOut: begin if SessionTimeout > 0 then begin Session.ScheduleInactiveTerminationEvent; end; end; TDSSessionLifetime.Request: begin LDispatch := TDSHTTPApplication.Instance.GetHTTPDispatch; Assert(LDispatch <> nil); if LDispatch <> nil then // Free when done with request LDispatch.OwnedObjects.Add(Session); end; end; end else begin IsNewSession := False; //check if the Session ID is valid by trying to get it's matching session from the manager Session := TDSSessionManager.Instance.Session[SessionID]; //if the session ID wasn't valid, return false showing session retrieval failed if (Session = nil) or (not Session.IsValid) then begin exit(False); end else Session.MarkActivity; //session is being used again, so mark as active end; if Session <> nil then TDSSessionManager.SetAsThreadSession(Session); exit(True); end; procedure TDSHTTPServer.DoDSCacheCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: string; LocalConnection: Boolean); var CmdType: TDSHTTPCommandType; SessionID: string; Session: TDSSession; IsNewSession: Boolean; SessionFailure: Boolean; CacheService: TDSHTTPCacheContextService; Len: Integer; ParamName: string; begin CacheService := nil; CmdType := ARequestInfo.CommandType; SessionID := TDSHTTPApplication.Instance.GetRequestSessionId(aRequestInfo, True); //Try to load the session with the given session ID into the current thread SessionFailure := not TDSHTTPApplication.Instance.LoadRESTSession(SessionID, ARequestInfo.AuthUserName, FSessionTimeout, FSessionLifetime, nil (*FTunnelService*), FDSHTTPAuthenticationManager, ARequestInfo, IsNewSession); Session := TDSSessionManager.GetThreadSession; //free any stream which was stored from a previous execution if Session <> nil then begin Session.LastResultStream.Free; Session.LastResultStream := nil; end; try if (Session = nil) or SessionFailure then begin AResponseInfo.ResponseNo := 403; //Forbidden AResponseInfo.ResponseText := SESSION_EXPIRED; AResponseInfo.ContentText := '{"SessionExpired":"' + SSessionExpiredMsg + '"}'; end else begin CacheService := TDSHTTPCacheContextService.Create(Session, LocalConnection); Len := 0; while (Len < ARequestInfo.Params.Count) do begin try ParamName := ARequestInfo.Params.Names[Len]; CacheService.ProcessQueryParameter(ParamName, ARequestInfo.Params.Values[ParamName]); finally Inc(Len); end; end; // dispatch to the appropriate service case CmdType of TDSHTTPCommandType.hcGET: CacheService.ProcessGETRequest(ARequestInfo, AResponseInfo, Request); TDSHTTPCommandType.hcDELETE: CacheService.ProcessDELETERequest(ARequestInfo, AResponseInfo, Request); else begin AResponseInfo.ResponseNo := 501; AResponseInfo.ContentText := Format(SCommandNotSupported, [ARequestInfo.Command]); end; end; end; finally CacheService.Free; AResponseInfo.CloseConnection := true; // Session cleared by TDSHTTPApplication.EndDispatch //TDSSessionManager.ClearThreadSession; end; end; function TDSRESTServer.CreateRESTService(const AuthUserName, AuthPassword: string): TDSRESTService; begin Assert(FDSServerName <> ''); Assert(DSServer <> nil); Result := TDSRESTService.Create(DSServer, '', 0, AuthUserName, AuthPassword, IPImplementationID) end; function TDSHTTPServer.CreateRESTService(const AuthUserName, AuthPassword: string): TDSRESTService; begin if FCredentialsPassthrough then Result := TDSRESTService.Create(FDSServerName, FDSHostname, FDSPort, AuthUserName, AuthPassword, IPImplementationID) else Result := TDSRESTService.Create(FDSServerName, FDSHostname, FDSPort, FDSAuthUser, FDSAuthPassword, IPImplementationID); end; // Entry point for rest. Should be able to create session before calling this method procedure TDSRESTServer.DoDSRESTCommand(ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; Request: string); var CmdType: TDSHTTPCommandType; ResponseOk: Integer; RESTService: TDSRESTService; Len: Integer; ParamName: string; SessionID: string; Session: TDSSession; IsNewSession: Boolean; SessionFailure: Boolean; RespHandler: TDSServiceResponseHandler; OwnService: Boolean; begin OwnService := True; RespHandler := nil; CmdType := ARequestInfo.CommandType; ResponseOk := 200; RESTService := CreateRESTService(ARequestInfo.AuthUserName, ARequestInfo.AuthPassword); // process query parameters Len := 0; while (Len < ARequestInfo.Params.Count) and (ResponseOk < 300) do begin ParamName := ARequestInfo.Params.Names[Len]; //check for session ID parameter in the URL if (Uppercase(ParamName) = 'SESSIONID') or (Uppercase(ParamName) = 'SID') then begin SessionID := ARequestInfo.Params.Values[ParamName] end else if not RESTService.ProcessQueryParameter(ParamName, ARequestInfo.Params.ValueFromIndex[Len]) then begin ResponseOK := 409; AResponseInfo.ResponseText := Format(CANNOT_PROCESS_PARAM, [ARequestInfo.Params.Names[Len], ARequestInfo.Params.Values[ARequestInfo.Params.Names[Len]]]); end; Inc(Len); end; if (ResponseOK < 300) and not RESTService.CheckConvertersForConsistency then begin // 409 - Indicates that the request could not be processed because of conflict in the request AResponseInfo.ResponseNo := 409; AResponseInfo.ResponseText := QUERY_PARAM_CONFLICT; end; //if no session ID is given in the URL, then try to load it from the Pragma header field if SessionID = EmptyStr then begin SessionID := TDSHTTPApplication.Instance.GetRequestSessionId(aRequestInfo, False); end; //Try to load the session with the given session ID into the current thread SessionFailure := not TDSHTTPApplication.FInstance.LoadRESTSession(SessionID, ARequestInfo.AuthUserName, FSessionTimeout, FSessionLifetime, nil (*FTunnelService*), FDSHTTPAuthenticationManager, ARequestInfo, IsNewSession); Session := TDSSessionManager.GetThreadSession; //free any stream which was stored from a previous execution if Session <> nil then begin Session.LastResultStream.Free; Session.LastResultStream := nil; if not SessionFailure then UpdateSessionTunnelHook(Request, Session, ARequestInfo); end; if not SessionFailure and IsClosingSession(Request) then begin try CloseRESTSession(Session, AResponseInfo); finally FreeAndNil(RESTService); TDSSessionManager.ClearThreadSession; end; exit; end; try if SessionFailure then begin AResponseInfo.ResponseNo := 403; //Forbidden AResponseInfo.ResponseText := SESSION_EXPIRED; AResponseInfo.ContentText := '{"SessionExpired":"' + SSessionExpiredMsg + '"}'; end else if ResponseOK >= 300 then begin // pre-parsing failed and the decision is in ResponseOK, response text already set AResponseInfo.ResponseNo := ResponseOK; end //don't need to authenticate if returning to a previously authenticated session else if (FDSHTTPAuthenticationManager <> nil) and IsNewSession and not FDSHTTPAuthenticationManager.Authenticate( DATASNAP_CONTEXT, RESTContext, ARequestInfo.AuthUserName, ARequestInfo.AuthPassword, ARequestInfo, AResponseInfo) then if ARequestInfo.AuthUserName <> EmptyStr then AResponseInfo.ResponseNo := 403 else begin AResponseInfo.SetHeaderAuthentication('Basic', 'REST'); AResponseInfo.ResponseNo := 401 end else begin if Session <> nil then begin AResponseInfo.Pragma := 'dssession=' + Session.SessionName; AResponseInfo.Pragma := AResponseInfo.Pragma + ',dssessionexpires=' + IntToStr(Session.ExpiresIn); end; OwnService := False; //create the response handler for populating the response info RespHandler := TDSResponseHandlerFactory.CreateResponseHandler(RESTService, ARequestInfo, TDSHTTPCommandType.hcUnknown, Self); if RespHandler = nil then begin AResponseInfo.ResponseNo := 406; //Not Acceptable end else begin if RespHandler is TDSServiceResponseHandler then begin TDSServiceResponseHandler(RespHandler).OnParseRequest := Self.OnParseRequest; TDSServiceResponseHandler(RespHandler).OnParsingRequest := Self.OnParsingRequest; end; //add the query parameters to invocation metadata if ARequestInfo.Params.Count > 0 then GetInvocationMetadata().QueryParams.AddStrings(ARequestInfo.Params); // dispatch to the appropriate service case CmdType of TDSHTTPCommandType.hcGET: RESTService.ProcessGETRequest(Request, nil, nil, RespHandler); TDSHTTPCommandType.hcPOST: RESTService.ProcessPOSTRequest(Request, ARequestInfo.Params, byteContent( ARequestInfo.PostStream ), RespHandler); TDSHTTPCommandType.hcPUT: begin RESTService.ProcessPUTRequest(Request, ARequestInfo.Params, byteContent( ARequestInfo.PostStream ), RespHandler); end; TDSHTTPCommandType.hcDELETE: RESTService.ProcessDELETERequest(Request, nil, nil, RespHandler); else begin GetInvocationMetadata().ResponseCode := 501; GetInvocationMetadata().ResponseContent := Format(SCommandNotSupported, [ARequestInfo.Command]); end; end; //populate the Response Info from the execution result RespHandler.PopulateResponse(AResponseInfo, GetInvocationMetadata()); end; end; finally if RespHandler = nil then FreeAndNil(RESTService); if RespHandler <> nil then RespHandler.Close; if OwnService then FreeAndNil(RESTService); if (GetInvocationMetadata(False) <> nil) and GetInvocationMetadata.CloseSession and (TDSSessionManager.GetThreadSession <> nil) then begin if TDSSessionManager.GetThreadSession.SessionName <> '' then TDSSessionManager.Instance.CloseSession(TDSSessionManager.GetThreadSession.SessionName); TDSSessionManager.ClearThreadSession; end; // Session cleared by TDSHTTPApplication.EndDispatch // TDSSessionManager.ClearThreadSession; end; end; procedure TDSRESTServer.DoDSOtherCommand( const AContext: TDSHTTPContext; const ARequestInfo: TDSHTTPRequest; const AResponseInfo: TDSHTTPResponse; const APrefix: string; const ARequest: string; ALocalConnection: Boolean); begin Assert(False); end; procedure TDSHTTPServer.DoDSOtherCommand( const AContext: TDSHTTPContext; const ARequestInfo: TDSHTTPRequest; const AResponseInfo: TDSHTTPResponse; const APrefix: string; const ARequest: string; ALocalConnection: Boolean); begin if SameText(APrefix, FCacheContext) then DoDSCacheCommand(ARequestInfo, AResponseInfo, ARequest, FDSServerName <> EmptyStr) else DoTunnelCommand(AContext, ARequestInfo, AResponseInfo) end; procedure TDSHTTPServer.DoTunnelCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse); var CmdType: TDSHTTPCommandType; JsonResponse: TJSONValue; Len: Integer; NeedsAuthentication: Boolean; CloseConnection: Boolean; ClientInfo: TDBXClientInfo; begin JsonResponse := nil; CmdType := ARequestInfo.CommandType; // Note that CredentialsPassthrough, DSAuthUser and DSAuthPassword properties // do not apply when tunneling using a DBX connection (which is what is happening in this method). // Instead, the DBX connection string credentials from the client are passed though the // tunnel without modification. // The CredentialsPassthrough, DSAuthUser and DSAuthPassword properties // do apply when tunneling using a REST connection. See TDSHTTPServer.DoJSONCommand. // Optionally, the client may send user/password in HTTP headers in addition to the // credentials in the DBX connection string. If the tunnel is between processea, this gives // the HTTP end of the tunnel a chance to authenticate before the TCP/IP end. // HTTP authentication is ignored when tunneling in-process because authentication will take place // when the DBX connection string is received from the client. NeedsAuthentication := (not FTunnelService.HasLocalServer) and FTunnelService.NeedsAuthentication(ARequestInfo.Params); ClientInfo.IpAddress := ARequestInfo.RemoteIP; ClientInfo.Protocol := ARequestInfo.ProtocolVersion; ClientInfo.AppName := ARequestInfo.UserAgent; //initialize the session so that it will be available when authenticating. FTunnelService.InitializeSession(ARequestInfo.Params, ClientInfo); try try if (FDSHTTPAuthenticationManager <> nil) and NeedsAuthentication and not FDSHTTPAuthenticationManager.Authenticate(DATASNAP_CONTEXT, TUNNEL_CONTEXT, ARequestInfo.AuthUserName, ARequestInfo.AuthPassword, ARequestInfo, AResponseInfo) then AResponseInfo.ResponseNo := 401 else begin case CmdType of TDSHTTPCommandType.hcGET: begin Len := 0; AResponseInfo.ContentStream := FTunnelService.ProcessGET(ARequestInfo.Params, Len, CloseConnection); AResponseInfo.ContentLength := Len; AResponseInfo.CloseConnection := CloseConnection; if Len = 0 then begin // no data are available from DS - server error AResponseInfo.ResponseNo := 500; AResponseInfo.ResponseText := NO_SERVER_DATA; AResponseInfo.CloseConnection := true; end; end; TDSHTTPCommandType.hcPUT, TDSHTTPCommandType.hcPOST: begin FTunnelService.ProcessPOST(ARequestInfo.Params, ByteContent(ARequestInfo.PostStream), JsonResponse, CloseConnection); AResponseInfo.CloseConnection := CloseConnection; end; TDSHTTPCommandType.hcDELETE: begin AResponseInfo.ResponseNo := 501; AResponseInfo.ResponseText := Format(PROTOCOL_COMMAND_NOT_SUPPORTED, [ARequestInfo.Command]); AResponseInfo.CloseConnection := true; end else begin AResponseInfo.ResponseNo := 501; AResponseInfo.ResponseText := Format(PROTOCOL_COMMAND_NOT_SUPPORTED, [ARequestInfo.Command]); AResponseInfo.CloseConnection := true; end; end; if JsonResponse <> nil then begin AResponseInfo.ResponseNo := 200; AResponseInfo.ContentText := StringOf(ByteContent(JsonResponse)); end; end; except on Ex: Exception do begin AResponseInfo.ResponseNo := 500; AResponseInfo.ResponseText := Ex.message; AResponseInfo.CloseConnection := true; end; end; finally JsonResponse.Free; // if client dropped the connection session can be terminated. try if not AContext.Connected then TDSTunnelService.TerminateSession(ARequestInfo.Params); except on Exception do TDSTunnelService.TerminateSession(ARequestInfo.Params); end; end; end; procedure TDSRESTServer.DoCommand(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse); var Request: string; NextRequest: string; NextContext: string; RestCtxt: string; StartDispatch: Boolean; begin // HTTPDispatch object if necessary StartDispatch := not TDSHTTPApplication.Instance.Dispatching; if StartDispatch then TDSHTTPApplication.Instance.StartDispatch(AContext, ARequestInfo, AResponseInfo); try {$IFNDEF POSIX} if CoInitFlags = -1 then CoInitializeEx(nil, COINIT_MULTITHREADED) else CoInitializeEx(nil, CoInitFlags); {$ENDIF} try // check for context, if not found send the appropriate error message Request := ARequestInfo.URI; if Consume(FDSContext, Request, NextRequest) then begin Request := NextRequest; if Consume(FRESTContext, Request, NextRequest) then begin // datasnap/rest DoDSRESTCommand(ARequestInfo, AResponseInfo, NextRequest); end else if ConsumeOtherContext(Request, NextContext, NextRequest) then begin DoDSOtherCommand(AContext, ARequestInfo, AResponseInfo, NextContext, NextRequest, FDSServerName <> EmptyStr); end else begin RestCtxt := Trim(FRESTContext); if RestCtxt = EmptyStr then RestCtxt := SProtocolRestEmpty; AResponseInfo.ResponseNo := 501; {rest or other service not found in URI} AResponseInfo.ContentText := Format(SProtocolNotSupported, [Request, RestCtxt]); AResponseInfo.CloseConnection := true; end; end else begin // This may dispatch .js files for example DoCommandOtherContext(AContext, ARequestInfo, AResponseInfo, Request); end; if Assigned(Self.FTrace ) then begin FTrace(Self, AContext, ARequestInfo, AResponseInfo); end; finally ClearInvocationMetadata(); {$IFNDEF POSIX} CoUnInitialize; {$ENDIF} end; finally if StartDispatch then TDSHTTPApplication.Instance.EndDispatch; end; end; procedure TDSRESTServer.DoCommandOtherContext(AContext: TDSHTTPContext; ARequestInfo: TDSHTTPRequest; AResponseInfo: TDSHTTPResponse; const ARequest: string); begin AResponseInfo.ResponseNo := 404; {datasnap not found} AResponseInfo.ResponseText := Format(INVALID_DATASNAP_CONTEXT, [ARequest]); AResponseInfo.CloseConnection := true; end; function TDSRESTServer.ConsumeOtherContext(const AContext: string; out APrefix: string; out AUnused: string): Boolean; begin APrefix := ''; AUnused := ''; Result := False; end; function TDSHTTPServer.ConsumeOtherContext(const AContext: string; out APrefix: string; out AUnused: string): Boolean; begin APrefix := TUNNEL_CONTEXT; Result := Consume(APrefix, AContext, AUnused); if not Result then begin APrefix := FCacheContext; Result := Consume(APrefix, AContext, AUnused); end; end; function TDSRESTServer.Consume(const Prefix: string; const Context: string; out Unused: string): Boolean; var SlashDel, StartIdx: Integer; Ctx: string; begin // empty prefix is accepted if Prefix = '' then begin Unused := Context; exit(true); end; // find first and the second REQUEST_DELIMITER indexes StartIdx := 1; SlashDel := Context.IndexOf(REQUEST_DELIMITER) + 1; if SlashDel = 1 then begin StartIdx := 2; SlashDel := Context.IndexOf(REQUEST_DELIMITER, StartIdx) + 1; end; if SlashDel = 0 then SlashDel := Context.IndexOf(REQUEST_PARAM_DELIMITER, StartIdx) + 1; if SlashDel = 0 then SlashDel := Context.Length + 1; Ctx := Context.Substring(StartIdx - 1, SlashDel - StartIdx); if Ctx.IndexOf('%') >= 0 then // Optimization Ctx := Decode(Ctx); if AnsiCompareText(Prefix, Ctx) = 0 then begin Unused := Context.Substring(SlashDel - 1, Context.Length - SlashDel + 1); Result := true; end else Result := false; // prefix not found end; {TCustomDSHTTPServerTransport} constructor TCustomDSRESTServerTransport.Create(AOwner: TComponent); begin inherited Create(AOwner); FDSRESTContext := REST_CONTEXT; FDSContext := DATASNAP_CONTEXT; FSessionTimeout := 1200000; FResultEvent := nil; end; constructor TCustomDSHTTPServerTransport.Create(AOwner: TComponent); begin inherited Create(AOwner); FDSCacheContext := CACHE_CONTEXT; FDSHostname := 'localhost'; FDSPort := 211; FCredentialsPassThrough := false; FDSAuthUser := EmptyStr; FDSAuthPassword := EmptyStr; end; function TCustomDSHTTPServerTransport.CreateRESTServer: TDSRESTServer; begin FHttpServer := CreateHttpServer; Result := FHttpServer; end; procedure TCustomDSRESTServerTransport.DefineProperties(Filer: TFiler); begin inherited; // For backwards compatibility Filer.DefineProperty('Trace', ReadTrace, nil, False); Filer.DefineProperty('FormatResult', ReadFormatResult, nil, False); end; type TOpenReader = class(TReader); procedure TCustomDSRESTServerTransport.ReadProperty(Reader: TReader; const ANewProperty: string); var LIdent: string; LMethod: TMethod; begin LIdent := Reader.ReadIdent; LMethod := TOpenReader(Reader).FindMethodInstance(Reader.Root, LIdent); if LMethod.Code <> nil then System.TypInfo.SetMethodProp(Self, ANewProperty, LMethod); end; procedure TCustomDSRESTServerTransport.ReadTrace(Reader: TReader); const sNewProperty = 'OnHTTPTrace'; begin ReadProperty(Reader, sNewProperty); end; procedure TCustomDSRESTServerTransport.ReadFormatResult(Reader: TReader); const sNewProperty = 'OnFormatResult'; begin ReadProperty(Reader, sNewProperty); end; destructor TCustomDSRESTServerTransport.Destroy; var TempData: TObject; begin Server := nil; // Break ARC cycle, which is result of HTTPServer calls // TDSSessionManager.AddSessionEvent and keeps reference to event TempData := FRestServer; FRestServer := nil; TempData.DisposeOf; //FreeAndNil(FDSHTTPAuthenticationManager); inherited Destroy; end; function TCustomDSRESTServerTransport.GetResultEvent: TDSRESTResultEvent; begin if FRESTServer <> nil then Result := FRESTServer.ResultEvent else Result := FResultEvent; end; procedure TCustomDSRESTServerTransport.SetResultEvent(const RestEvent: TDSRESTResultEvent); begin FResultEvent := RestEvent; if FRESTServer <> nil then FRESTServer.ResultEvent := RestEvent; end; function TCustomDSRESTServerTransport.GetRESTContext: string; begin if FRESTServer <> nil then Result := FRESTServer.RESTContext else Result := FDSRestContext + '/'; end; procedure TCustomDSRESTServerTransport.SetRESTContext(const Ctx: string); begin if (Ctx <> EmptyStr) and (Ctx.Chars[Ctx.Length - 1] = '/') then FDSRestContext := Ctx.Substring(0, Ctx.Length - 1) else FDSRestContext := Ctx; if FRESTServer <> nil then FRESTServer.RESTContext := Ctx; end; procedure TCustomDSRESTServerTransport.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) then if (AComponent = Server) then Server := nil else if (Assigned(FRestServer)) and (AComponent = FRestServer.DSAuthenticationManager) then FRestServer.DSAuthenticationManager := nil; if AComponent = FAuthenticationManager then FAuthenticationManager := nil; end; procedure TCustomDSRESTServerTransport.SetTraceEvent(Event: TDSHTTPServiceTraceEvent); begin FTrace := Event; if FRESTServer <> nil then FRESTServer.FTrace := Event; end; function TCustomDSRESTServerTransport.GetTraceEvent: TDSHTTPServiceTraceEvent; begin if FRESTServer <> nil then Result := FRESTServer.FTrace else Result := FTrace; end; procedure TCustomDSRESTServerTransport.SetParseRequestEvent(Event: TParseRequestEvent); begin FParseRequestEvent := Event; if FRESTServer <> nil then FRESTServer.FParseRequestEvent := Event; end; function TCustomDSRESTServerTransport.GetParseRequestEvent: TParseRequestEvent; begin if FRESTServer <> nil then Result := FRESTServer.FParseRequestEvent else Result := FParseRequestEvent; end; procedure TCustomDSRESTServerTransport.SetParsingRequestEvent(Event: TParsingRequestEvent); begin FParsingRequestEvent := Event; if FRESTServer <> nil then FRESTServer.FParsingRequestEvent := Event; end; function TCustomDSRESTServerTransport.GetParsingRequestEvent: TParsingRequestEvent; begin if FRESTServer <> nil then Result := FRESTServer.FParsingRequestEvent else Result := FParsingRequestEvent; end; procedure TCustomDSRESTServerTransport.InitializeRESTServer; begin FRESTServer.SessionTimeout := FSessionTimeout; FRESTServer.DSContext := FDSContext; FRESTServer.RESTContext := FDSRestContext; FRESTServer.DSAuthenticationManager := FAuthenticationManager; FRESTServer.FTrace := FTrace; FRESTServer.FParseRequestEvent := FParseRequestEvent; FRESTServer.FParsingRequestEvent := FParsingRequestEvent; FRESTServer.ResultEvent := FResultEvent; FRESTServer.FSessionLifetime := FSessionLifetime; UpdateDSServerName; end; procedure TCustomDSHTTPServerTransport.InitializeRESTServer; begin inherited; InitializeHttpServer; end; procedure TCustomDSHTTPServerTransport.InitializeHttpServer; begin inherited; FHttpServer.CacheContext := FDSCacheContext; FHttpServer.Filters := Filters; FHTTPServer.CredentialsPassThrough := FCredentialsPassthrough; FHTTPServer.DSAuthUser := FDSAuthUser; FHTTPServer.DSAuthPassword := FDSAuthPassword; FHTTPServer.DSPort := FDSPort; FHTTPServer.DSHostname := FDSHostname; end; procedure TCustomDSRESTServerTransport.Loaded; begin inherited; // Initialize server after properties have been loaded RequiresServer; end; procedure TCustomDSRESTServerTransport.SetAuthenticationManager( const AuthenticationManager: TDSCustomAuthenticationManager); begin FAuthenticationManager := AuthenticationManager; if FRESTServer <> nil then FRESTServer.DSAuthenticationManager := AuthenticationManager; end; procedure TCustomDSHTTPServerTransport.SetCacheContext(const Ctx: string); begin if (Ctx <> EmptyStr) and (Ctx.Chars[Ctx.Length - 1] = '/') then FDSCacheContext := Ctx.Substring(0, Ctx.Length - 1) else FDSCacheContext := Ctx; if FHTTPServer <> nil then FHTTPServer.CacheContext := Ctx; end; procedure TCustomDSRESTServerTransport.SetDSContext(const Ctx: string); begin if (Ctx <> EmptyStr) and (Ctx.Chars[Ctx.Length - 1] = '/') then FDSContext := Ctx.Substring(0, Ctx.Length - 1) else FDSContext := Ctx; if FRESTServer <> nil then FRESTServer.DSContext := Ctx; end; procedure TCustomDSHTTPServerTransport.SetDSHostname(Host: string); begin FDSHostname := Host; if FHttpServer <> nil then FHttpServer.DSHostname := Host; end; function TCustomDSRESTServerTransport.GetAuthenticationManager: TDSCustomAuthenticationManager; begin if FRESTServer <> nil then Result := FRESTServer.DSAuthenticationManager else Result := FAuthenticationManager; end; function TCustomDSHTTPServerTransport.GetCacheContext: string; begin if FHTTPServer <> nil then Result := FHTTPServer.CacheContext else Result := FDSCacheContext + '/'; end; function TCustomDSRESTServerTransport.GetDSContext: string; begin if FRESTServer <> nil then Result := FRESTServer.DSContext else Result := FDSContext + '/'; end; function TCustomDSHTTPServerTransport.GetDSHostname: string; begin if FHttpServer <> nil then Result := FHttpServer.DSHostname else Result := FDSHostname; end; procedure TCustomDSHTTPServerTransport.SetDSPort(Port: Integer); begin FDSPort := Port; if FHttpServer <> nil then FHttpServer.DSPort := Port; end; procedure TCustomDSRESTServerTransport.SetServer(const AServer: TDSCustomServer); begin if AServer <> Server then begin if Server <> nil then Server.RemoveFreeNotification(Self); if AServer <> nil then AServer.FreeNotification(Self); inherited SetServer(AServer); if FRESTServer <> nil then UpdateDSServerName; end; end; procedure TCustomDSRESTServerTransport.UpdateDSServerName; begin FRESTServer.DSServer := Self.Server; if Server <> nil then begin FRESTServer.DSServerName := Server.Name; FRESTServer.CreateProtocolHandlerFactory(self) end else begin FRESTServer.DSServerName := EmptyStr; FRESTServer.ClearProtocolHandlerFactory end; end; function TCustomDSRESTServerTransport.IsDSContextStored: Boolean; begin Result := not SameText(GetDSContext, 'datasnap/'); end; function TCustomDSRESTServerTransport.IsRESTContextStored: Boolean; begin Result := not SameText(GetRESTContext, 'rest/'); end; function TCustomDSHTTPServerTransport.IsCacheContextStored: Boolean; begin Result := not SameText(GetCacheContext, 'cache/'); end; function TCustomDSHTTPServerTransport.IsDSHostnameStored: Boolean; begin Result := not SameText(GetDSHostname, 'localhost'); end; function TCustomDSHTTPServerTransport.GetDSPort: Integer; begin if Assigned(FHttpServer) then Result := FHttpServer.DSPort else Result := FDSPort; end; procedure TCustomDSRESTServerTransport.RequiresServer; begin if FRestServer = nil then begin FRESTServer := CreateRESTServer; InitializeRESTServer; end; end; function TCustomDSRESTServerTransport.GetRESTServer: TDSRESTServer; begin RequiresServer; // Should not create during loading process because properties of transport may determine type of http server Assert(not (csLoading in ComponentState)); Result := FRESTServer; end; function TCustomDSHttpServerTransport.GetHttpServer: TDSHttpServer; begin RequiresServer; // Should not create during loading process because properties of transport may determine type of http server Assert(not (csLoading in ComponentState)); Result := FHttpServer; end; procedure TCustomDSHTTPServerTransport.SetFilters(const Value: TTransportFilterCollection); begin inherited SetFilters(Value); if FHttpServer <> nil then FHttpServer.Filters := GetFilters; end; procedure TCustomDSRESTServerTransport.SetIPImplementationID( const AIPImplementationID: string); begin inherited; if Assigned(FRESTServer) then FRESTServer.FIPImplementationID := AIPImplementationID; end; procedure TCustomDSHttpServerTransport.ServerCloseAllTunnelSessions; begin // Call private method of FHttpServer if FHttpServer <> nil then FHttpServer.CloseAllTunnelSessions; end; function TCustomDSHTTPServerTransport.GetCredentialsPassThrough: Boolean; begin if FHttpServer <> nil then Result := FHttpServer.CredentialsPassThrough else Result := FCredentialsPassThrough; end; function TCustomDSHTTPServerTransport.GetDSAuthPassword: string; begin if FHttpServer <> nil then Result := FHttpServer.DSAuthPassword else Result := FDSAuthPassword; end; function TCustomDSHTTPServerTransport.GetDSAuthUser: string; begin if FHttpServer <> nil then Result := FHttpServer.DSAuthUser else Result := FDSAuthUser; end; procedure TCustomDSHTTPServerTransport.SetCredentialsPassThrough(const AFlag: Boolean); begin FCredentialsPassThrough := AFlag; if FHttpServer <> nil then FHttpServer.CredentialsPassThrough := AFlag end; procedure TCustomDSHTTPServerTransport.SetDSAuthPassword(const UserPassword: string); begin FDSAuthPassword := UserPassword; if FHttpServer <> nil then FHttpServer.DSAuthPassword := UserPassword end; procedure TCustomDSHTTPServerTransport.SetDSAuthUser(const UserName: string); begin FDSAuthUser := UserName; if FHttpServer <> nil then FHttpServer.DSAuthUser := UserName end; procedure TCustomDSRESTServerTransport.SetSessionTimeout(const Milliseconds: Integer); begin FSessionTimeout := Milliseconds; if FRESTServer <> nil then FRESTServer.SessionTimeout := Milliseconds; end; function TCustomDSRESTServerTransport.GetSessionTimeout: Integer; begin if FRESTServer <> nil then Result := FRESTServer.SessionTimeout else Result := FSessionTimeout end; function TCustomDSRESTServerTransport.GetIPImplementationID: string; begin if FRESTServer <> nil then Result := FRESTServer.IPImplementationID else Result := inherited; end; { TDSResponseHandlerFactory } class function TDSResponseHandlerFactory.CreateResponseHandler(DSService: TDSService; RequestInfo: TDSHTTPRequest; CommandType: TDSHTTPCommandType; HTTPServer: TDSHTTPServer): TDSServiceResponseHandler; begin Result := CreateResponseHandler(DSService, RequestInfo, CommandType, TDSRESTServer(HTTPServer)); end; class function TDSResponseHandlerFactory.CreateResponseHandler(DSService: TDSService; RequestInfo: TDSHTTPRequest; CommandType: TDSHTTPCommandType; HTTPServer: TDSRESTServer): TDSServiceResponseHandler; var Accept: string; begin if RequestInfo <> nil then Accept := RequestInfo.Accept; if (CommandType = TDSHTTPCommandType.hcUnknown) and (RequestInfo <> nil) then CommandType := RequestInfo.CommandType; if RequestInfo = nil then Result := TDSNullResponseHandler.Create(DSService, CommandType) else if (AnsiContainsStr(Accept, 'application/rest')) then Result := TDSCacheResponseHandler.Create(DSService, CommandType) else begin Result := TDSDefaultResponseHandler.Create(not DSService.StreamAsJSON, DSService, CommandType); if Assigned(HTTPServer) and Assigned(HTTPServer.ResultEvent) then TDSDefaultResponseHandler(Result).ResultEvent := HTTPServer.ResultEvent; end; end; { TDSHTTPCacheContextService } constructor TDSHTTPCacheContextService.Create(Session: TDSSession; LocalConnection: Boolean); begin Assert(Session <> nil); inherited Create; FSession := Session; FLocalConnection := LocalConnection; end; function TDSHTTPCacheContextService.ParseRequst(Request: string; out CacheId, CommandIndex, ParameterIndex: Integer): Boolean; var SlashLeft, SlashRight, SlashAux: Integer; begin CacheId := -1; CommandIndex := -1; ParameterIndex := -1; Result := True; SlashLeft := Request.IndexOf(REQUEST_DELIMITER) + 1; if SlashLeft = 0 then begin //the user is interested in the cache as a whole, and not any specific object Exit(True); end; if SlashLeft > 1 then begin // first / is missing SlashRight := SlashLeft; SlashLeft := 1; end else SlashRight := Request.IndexOf(REQUEST_DELIMITER, SlashLeft) + 1; SlashAux := SlashRight; if SlashAux < 1 then SlashAux := Request.Length + 1; if SlashAux > (SlashLeft + 1) then begin try CacheId := StrToInt(Request.SubString(Slashleft, SlashAux-SlashLeft-1)); except Exit(False); end; if SlashRight = SlashAux then begin SlashAux := Request.IndexOf(REQUEST_DELIMITER, SlashRight) + 1; SlashLeft := SlashRight; SlashRight := SlashAux; if SlashAux < SlashLeft then SlashAux := Request.Length + 1; if SlashAux > (SlashLeft + 1) then begin try CommandIndex := StrToInt(Request.Substring(Slashleft, SlashAux-SlashLeft-1)); except Exit(False); end; if SlashRight = SlashAux then begin SlashAux := Request.IndexOf(REQUEST_DELIMITER, SlashRight) + 1; SlashLeft := SlashRight; if SlashAux < SlashLeft then SlashAux := Request.Length + 1; if SlashAux > (SlashLeft + 1) then begin try ParameterIndex := StrToInt(Request.Substring(Slashleft, SlashAux-SlashLeft-1)); except Exit(False); end; end; end; end; end; end; end; procedure TDSHTTPCacheContextService.GetCacheContents(out Value: TJSONValue); var Ids: TList<Integer>; Key: Integer; Aux: TJSONValue; begin Value := TJSONObject.Create; Ids := FSession.ParameterCache.GetItemIDs; for Key in Ids do begin GetCacheItemContents(Key, Aux); TJSONObject(Value).AddPair(TJSONPair.Create(IntToStr(Key), Aux)); end; FreeAndNil(Ids); end; procedure TDSHTTPCacheContextService.GetCacheItemContents(const CacheId: Integer; out Value: TJSONValue); var Item: TResultCommandHandler; CmdArray: TJSONArray; Aux: TJSONValue; I: Integer; begin Item := FSession.ParameterCache.GetItem(CacheId); if Item = nil then begin Value := TJSONNull.Create; Exit; end; CmdArray := TJSONArray.Create; for I := 0 to Item.GetCommandCount - 1 do begin Aux := nil; GetCommandContents(CacheId, I, Aux); if Aux <> nil then CmdArray.Add(TJSONObject(Aux)); end; Value := TJSONObject.Create; TJSONObject(Value).AddPair(TJSONPair.Create('commands', CmdArray)); end; procedure TDSHTTPCacheContextService.GetCommandContents(const CacheId: Integer; const CommandIndex: Integer; out Value: TJSONValue); var Item: TResultCommandHandler; Param: TDBXParameter; TypeNames: TJSONArray; Count: Integer; I: Integer; begin Item := FSession.ParameterCache.GetItem(CacheId); if Item = nil then begin Value := TJSONNull.Create; Exit; end; Count := Item.GetParameterCount(CommandIndex); Value := TJSONObject.Create; TypeNames := TJSONArray.Create; for I := 0 to Count - 1 do begin Param := Item.GetCommandParameter(CommandIndex, I); TypeNames.Add(Param.Name); end; TJSONObject(Value).AddPair(TJSONPair.Create('parameters', TypeNames)); end; function TDSHTTPCacheContextService.GetOriginalParamIndex(const Command: TDBXCommand; const Parameter: TDBXParameter): Integer; var I: Integer; begin Result := -1; if (Command <> nil) and (Parameter <> nil) then begin for I := 0 to Command.Parameters.Count - 1 do begin if Command.Parameters[I] = Parameter then Exit(I); end; end; end; procedure TDSHTTPCacheContextService.InvalidRequest(Response: TDSHTTPResponse; Request: string); begin if Response <> nil then begin Response.ResponseNo := 400; //Bad Request Response.ResponseText := Format(INVALID_REQUEST, [Request]); Response.CloseConnection := true; end; end; procedure TDSHTTPCacheContextService.ProcessDELETERequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: string); var CacheId, CommandIndex, ParameterIndex: Integer; begin //DELETE only allowed on cache as a whole, or on a whole cache item, not individual Commands or Parameters. if not ParseRequst(Request, CacheId, CommandIndex, ParameterIndex) or (CommandIndex <> -1) or (ParameterIndex <> -1) then begin InvalidRequest(Response, Request); Exit; end; if (CacheId = -1) then FSession.ParameterCache.ClearAllItems else FSession.ParameterCache.RemoveItem(CacheId); end; function TDSHTTPCacheContextService.StreamsAsJSON(const RequestInfo: TDSHTTPRequest): Boolean; var StreamAsJson: Boolean; UrlParamValue: string; begin StreamAsJson := False; UrlParamValue := RequestInfo.Params.Values['json']; if UrlParamValue <> '' then begin try StreamAsJSON := StrToBool(UrlParamValue); except end; end else begin StreamAsJSON := AnsiContainsStr(RequestInfo.Accept, 'application/json'); end; Result := StreamAsJSON; end; procedure TDSHTTPCacheContextService.GetParameterValue(const RequestInfo: TDSHTTPRequest; const CacheId, CommandIndex, ParameterIndex: Integer; out Response: TJSONValue; out ResponseStream: TStream; out IsError: Boolean); var Item: TResultCommandHandler; Command: TDBXCommand; Parameter: TDBXParameter; ConvList: TObjectList<TDBXRequestFilter>; OriginalIndex: Integer; begin Item := FSession.ParameterCache.GetItem(CacheId); IsError := False; if Item = nil then begin Response := TJSONString.Create(Format(SNoCachItem, [CacheId])); IsError := True; Exit; end; Parameter := Item.GetCommandParameter(CommandIndex, ParameterIndex); if Parameter = nil then begin Response := TJSONString.Create(Format(SNoCacheParameter, [CommandIndex, ParameterIndex])); IsError := True; Exit; end; if not StreamsAsJSON(RequestInfo) and (Parameter.DataType = TDBXDataTypes.BinaryBlobType) then begin ResponseStream := Parameter.Value.GetStream(True); if ResponseStream = nil then Response := TJSONNull.Create; end else begin ConvList := TObjectList<TDBXRequestFilter>.Create(false); Command := Item.GetCommand(CommandIndex); OriginalIndex := GetOriginalParamIndex(Command, Parameter); try Response := nil; //use a request filter on the returned data, if one was specified if OriginalIndex > -1 then begin FiltersForCriteria([OriginalIndex+1], OriginalIndex = Command.Parameters.Count - 1, ConvList); if ConvList.Count = 1 then begin if not ConvList.Items[0].CanConvert(Command.Parameters[OriginalIndex].Value) then Raise TDSServiceException.Create(Format(SCannotConvertParam, [OriginalIndex, ConvList.Items[0].Name])); Response := ConvList.Items[0].ToJSON(Command.Parameters[OriginalIndex].Value, FLocalConnection) end; end; if Response = nil then Response := TDBXJSONTools.DBXToJSON(Parameter.Value, Parameter.DataType, FLocalConnection); finally FreeAndNil(ConvList); end; end; end; function TDSHTTPCacheContextService.ByteContent(JsonValue: TJSONValue): TArray<Byte>; var Buffer: TArray<Byte>; begin SetLength(Buffer, JsonValue.EstimatedByteSize); SetLength(Buffer, JsonValue.ToBytes(Buffer, 0)); Result := Buffer; end; procedure TDSHTTPCacheContextService.ProcessGETRequest(const RequestInfo: TDSHTTPRequest; Response: TDSHTTPResponse; Request: string); var CacheId, CommandIndex, ParameterIndex: Integer; ResultObj: TJSONObject; SubResult: TJSONValue; ResultStream: TStream; IsError: Boolean; ResultStr: string; begin ResultObj := nil; SubResult := nil; ResultStream := nil; IsError := False; if not ParseRequst(Request, CacheId, CommandIndex, ParameterIndex) then begin InvalidRequest(Response, Request); Exit; end; //datasnap/cache if (CacheId = -1) then begin GetCacheContents(SubResult); end //datasnap/cache/CacheId else if (CommandIndex = -1) then begin GetCacheItemContents(CacheId, SubResult); end //datasnap/cache/CacheId/CommandIndex else if (ParameterIndex = -1) then begin GetCommandContents(CacheId, CommandIndex, SubResult); end //datasnap/cache/CacheId/CommandIndex/ParameterIndex else begin GetParameterValue(RequestInfo, CacheId, CommandIndex, ParameterIndex, SubResult, ResultStream, IsError); end; try if Assigned(ResultStream) then begin Response.ContentStream := ResultStream; Response.FreeContentStream := False; end else if Assigned(SubResult) then begin if IsError then ResultStr := 'error' else ResultStr := 'result'; ResultObj := TJSONObject.Create; ResultObj.AddPair(TJSONPair.Create(ResultStr, SubResult)); Response.ContentText := StringOf(ByteContent(ResultObj)); Response.ContentType := 'application/json'; end; finally //Only free SubResult if it hasn't been added to ResultObj if ResultObj <> nil then ResultObj.Free else if Assigned(SubResult) then SubResult.Free; end; end; { TDSDefaultResponseHandler } procedure TDSDefaultResponseHandler.Close; var Session: TDSSession; begin //cache the Handler, so the stream isn't killed before the response is sent if FStoreHandler then begin Session := TDSSessionManager.Instance.GetThreadSession; if Session = nil then Raise TDSServiceException.Create(SNoSessionFound); if Session.LastResultStream <> nil then begin Session.LastResultStream.Free; Session.LastResultStream := nil; end; // that the object needs to stick around until the response is sent, not until session // is terminated. Session.LastResultStream := Self; end else Free; end; constructor TDSDefaultResponseHandler.Create(AllowBinaryStream: Boolean; DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean); begin inherited Create(CommandType, DSService, ServiceInstanceOwner); FStoreHandler := False; FDSService := DSService; end; destructor TDSDefaultResponseHandler.Destroy; begin ClearCommands(); inherited; end; function TDSDefaultResponseHandler.HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; begin {If there is only one output/return parameter and it is a Stream, return it as a stream} if (not FDSService.StreamAsJSON) and FAllowStream and (Parameter.DataType = TDBXDataTypes.BinaryBlobType) then begin //if FAllowStream is true there should be no case where we are //setting a value for stream when it already has a value Assert(ResponseStream = nil); ResponseStream := Parameter.Value.GetStream(True); if ResponseStream <> nil then begin //set this object to store itself in the Session, to be freed later, //after the stream it holds is no longer required by the REST response sent to the client. FStoreHandler := True; end else Response := TJSONNull.Create; exit(True); end; Result := False; end; procedure TDSDefaultResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); begin if (ResponseStream = nil) and Assigned(Response) then begin ResponseInfo.ContentText := StringOf(ByteContent(Response)); ResponseInfo.ContentType := 'application/json'; end else if (ResponseStream <> nil) then begin ResponseInfo.ContentStream := ResponseStream; ResponseInfo.FreeContentStream := False; end; end; { TDSCacheResponseHandler } constructor TDSCacheResponseHandler.Create(DSService: TDSService; CommandType: TDSHTTPCommandType; ServiceInstanceOwner: Boolean); begin inherited Create(CommandType, DSService, ServiceInstanceOwner); FCacheId := -1; end; destructor TDSCacheResponseHandler.Destroy; begin inherited; end; function TDSCacheResponseHandler.GetCacheObject: TDSCacheResultCommandHandler; begin if (FResultHandler = nil) then FResultHandler := TDSCacheResultCommandHandler.Create(Self); Result := FResultHandler; end; function TDSCacheResponseHandler.GetComplexParams(Command: TDBXCommand; out Index: Integer; AddIfNotFound: Boolean): TDSCommandComplexParams; var CP: TDSCommandComplexParams; I: Integer; begin Result := nil; Index := -1; for I := 0 to GetCacheObject.CacheCommands.Count - 1 do begin CP := GetCacheObject.CacheCommands[I]; if CP.Command = Command then begin Index := I; Exit(CP); end; end; if AddIfNotFound then begin Index := GetCacheObject.CacheCommands.Count; CP := TDSCommandComplexParams.Create(Command); GetCacheObject.CacheCommands.Add(CP); Result := CP; end; end; procedure TDSCacheResponseHandler.Close; begin //If FCacheId is not specified then this object isn't stored in the Session Cache, so should be freed here. if FCacheId = -1 then Free; end; function TDSCacheResponseHandler.HandleParameter(const Command: TDBXCommand; const Parameter: TDBXParameter; out Response: TJSONValue; var ResponseStream: TStream): Boolean; var CP: TDSCommandComplexParams; DataType: Integer; CommandIndex: Integer; ParameterIndex: Integer; Session: TDSSession; Cache: TDSSessionCache; UrlString: string; begin Result := False; Session := TDSSessionManager.GetThreadSession; if (Session <> nil) and (Parameter <> nil) then begin DataType := Parameter.DataType; if ((DataType = TDBXDataTypes.TableType) or (DataType = TDBXDataTypes.ObjectType) or ((DataType = TDBXDataTypes.JsonValueType) and (SameText(Parameter.TypeName, 'TJSONArray') or SameText(Parameter.TypeName, 'TJSONValue') or (SameText(Parameter.TypeName, 'TJSONObject') or (not SameText(Parameter.TypeName.Substring(0, 5), 'TJSON'))))) or (DataType = TDBXDataTypes.BlobType) or (DataType = TDBXDataTypes.BinaryBlobType)) then begin CP := GetComplexParams(Command, CommandIndex); if (CP <> nil) then begin ParameterIndex := CP.AddParameter(Parameter); Cache := Session.ParameterCache; if (Cache <> nil) and (ParameterIndex > -1) then begin if FCacheId = -1 then FCacheId := Cache.AddItem(GetCacheObject()); if FCacheId > -1 then begin Result := True; UrlString := (IntToStr(FCacheId) + '/' + IntToStr(CommandIndex) + '/' + IntToStr(ParameterIndex)); Response := TJSONString.Create(UrlString); end; end; end; end; end; end; procedure TDSCacheResponseHandler.PopulateContent(ResponseInfo: TDSHTTPResponse; Response: TJSONValue; ResponseStream: TStream); begin //ResponseStream should NEVER be assigned in this case, //as any streams should instead be stored in the session cache Assert(ResponseStream = nil); if Response <> nil then begin ResponseInfo.ContentText := StringOf(ByteContent(Response)); ResponseInfo.ContentType := 'application/rest'; end; end; procedure TDSCacheResponseHandler.ProcessResultObject(var ResultObj: TJSONObject; Command: TDBXCommand); var CommandIndex: Integer; begin if (ResultObj <> nil) and (FResultHandler <> nil) and (FResultHandler.CacheCommands.Count > 0) and (FCacheId > -1) then begin GetComplexParams(Command, CommandIndex, False); //Add to the result object two key/value pairs: cacheId and cmdIndex. //These can later be used to construct URLs into different levels of the Session Parameter cache if (CommandIndex > -1) then begin ResultObj.AddPair(TJSONPair.Create('cacheId', TJSONNumber.Create(FCacheId))); ResultObj.AddPair(TJSONPair.Create('cmdIndex', TJSONNumber.Create(CommandIndex))); end; end; end; { TDSHTTPApplication } procedure TDSHTTPApplication.SetSessionRequestInfo(const ASession: TDSSession; const ARequest: TDSHTTPRequest); begin if ARequest <> nil then begin if ARequest.RemoteIP <> EmptyStr then ASession.PutData('RemoteIP', ARequest.RemoteIP); ASession.PutData('RemoteAppName', ARequest.UserAgent); ASession.PutData('CommunicationProtocol', ARequest.ProtocolVersion); ASession.PutData('ProtocolSubType', 'rest'); end; end; threadvar FDSHTTPDispatch: TDSHTTPDispatch; function TDSHTTPApplication.GetDispatching: Boolean; begin Result := FDSHTTPDispatch <> nil; end; procedure TDSHTTPApplication.EndDispatch; begin TDSSessionManager.ClearThreadSession; FreeAndNil(FDSHTTPDispatch); end; procedure TDSHTTPApplication.StartDispatch(const AContext: TDSHTTPContext; const ARequest: TDSHTTPRequest; const AResponse: TDSHTTPResponse); var LDispatch: TDSHTTPDispatch; begin Assert(FDSHTTPDispatch = nil); LDispatch := TDSHTTPDispatch.Create(AContext, ARequest, AResponse); // Owns objects // set threadvar FDSHTTPDispatch := LDispatch; end; function TDSHTTPApplication.GetHTTPDispatch: TDSHTTPDispatch; begin Result := FDSHTTPDispatch; end; initialization TDSHTTPApplication.FInstance := TDSHTTPApplication.Create; finalization TDSHTTPApplication.FInstance.Free; end.
{*******************************************************} { } { Delphi Visual Component Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit SvrMainForm; interface uses {$IFDEF MSWINDOWS} Winapi.Windows, System.Win.Registry, {$ENDIF} System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ActnList, Vcl.StdCtrls, SvrHTTPIndy, Vcl.Menus, System.IniFiles, Vcl.ExtCtrls, Vcl.ComCtrls, SvrLog, SvrLogFrame, SvrStatsFrame; type TWebAppDbgMainForm = class(TForm) pbToggle: TButton; ActionList1: TActionList; ToggleServerAction: TAction; MainMenu1: TMainMenu; PropertiesItem: TMenuItem; StartServer1: TMenuItem; StopServer1: TMenuItem; Properties1: TMenuItem; Exit1: TMenuItem; N1: TMenuItem; N2: TMenuItem; Help1: TMenuItem; About1: TMenuItem; ExitAction: TAction; StopAction: TAction; StartAction: TAction; AboutAction: TAction; PropertiesAction: TAction; BrowseAction: TAction; PopupMenu1: TPopupMenu; Properties2: TMenuItem; StartServer2: TMenuItem; StopServer2: TMenuItem; Exit2: TMenuItem; Label2: TLabel; Home: TLabel; MainUpdateAction: TAction; ClearAction: TAction; Label1: TLabel; Port: TLabel; GroupBox1: TGroupBox; LogFrame: TLogFrame; ToggleLogAction: TAction; CheckBox1: TCheckBox; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; StatsFrame: TStatsFrame; procedure ToggleServerActionExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ToggleServerActionUpdate(Sender: TObject); procedure StopActionExecute(Sender: TObject); procedure StopActionUpdate(Sender: TObject); procedure StartActionExecute(Sender: TObject); procedure StartActionUpdate(Sender: TObject); procedure PropertiesActionExecute(Sender: TObject); procedure ExitActionExecute(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure HomeClick(Sender: TObject); procedure HideActionExecute(Sender: TObject); procedure SysTray1DblClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure MainUpdateActionExecute(Sender: TObject); procedure MainUpdateActionUpdate(Sender: TObject); procedure ToggleLogActionExecute(Sender: TObject); procedure ToggleLogActionUpdate(Sender: TObject); procedure AboutActionExecute(Sender: TObject); procedure StatsFrameResetCountsActionExecute(Sender: TObject); private FBrowser: string; function GetUDPPort: Integer; procedure SetUDPPort(const Value: Integer); protected {$IFDEF LINUX} function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override; {$ENDIF} private FShowAtStartup: Boolean; FActiveAtStartup: Boolean; FHideOnClose: Boolean; FWebServer: TCustomWebServer; FLogOn: Boolean; function GetSearchPath: string; function GetServerActive: Boolean; function GetServerPort: Integer; procedure SetSearchPath(const Value: string); procedure SetServerActive(const Value: Boolean); procedure SetServerPort(const Value: Integer); function GetDefaultURL: string; procedure SetDefaultURL(const Value: string); function CreateRegistry: TRegIniFile; procedure Load(Reg: TRegIniFile); procedure Save(Reg: TRegIniFile); function GetTranslatedDefaultURL: string; procedure OnLog(Sender: TObject; Transaction: TTransactionLogEntry; var Release: Boolean); function GetLogMax: Integer; procedure SetLogMax(const Value: Integer); function GetLogDelete: Integer; procedure SetLogDelete(const Value: Integer); property ServerActive: Boolean read GetServerActive write SetServerActive; property ServerSearchPath: string read GetSearchPath write SetSearchPath; property ServerPort: Integer read GetServerPort write SetServerPort; property UDPPort: Integer read GetUDPPort write SetUDPPort; property Browser: string read FBrowser write FBrowser; property DefaultURL: string read GetDefaultURL write SetDefaultURL; property TranslatedDefaultURL: string read GetTranslatedDefaultURL; property LogMax: Integer read GetLogMax write SetLogMax; property LogDelete: Integer read GetLogDelete write SetLogDelete; property ShowAtStartup: Boolean read FShowAtStartup write FShowAtStartup; property ActiveAtStartup: Boolean read FActiveAtStartup write FActiveAtStartup; property HideOnClose: Boolean read FHideOnClose write FHideOnClose; property LogOn: Boolean read FLogOn write FLogOn; end; {$IFDEF LINUX} function PIDFileName: string; function PIDFromFile: Integer; procedure WritePIDFile; procedure DeletePIDFile; {$ENDIF} var WebAppDbgMainForm: TWebAppDbgMainForm; implementation uses SvrPropDlg, Winapi.ShellAPI, SvrConst, WebAppDbgAbout, SockAppReg; {$R *.dfm} procedure TWebAppDbgMainForm.ToggleServerActionExecute(Sender: TObject); begin ServerActive := not ServerActive; end; {$IFDEF LINUX} procedure SignalProc(SigNum: Integer); cdecl; forward; {$ENDIF} procedure TWebAppDbgMainForm.FormCreate(Sender: TObject); var Reg: TRegIniFile; begin {$IFDEF LINUX} signal(SIGUSR2, SignalProc); {$ENDIF} Caption := sWebAppDebugger; Application.Title := sWebAppDebugger; FWebServer := TCustomWebServer.Create(Self); FWebServer.OnLog := OnLog; FWebServer.Port := 8081; Browser := 'mozilla'; // Do not localize FWebServer.DefaultURL := 'ServerInfo.ServerInfo'; // Do not localize {$IFDEF MSWINDOWS} FWebServer.SearchPath := '$(BDS)\source\webmidas;$(BDS)\demos\websnap\images'; // Do not localize {$ENDIF} LogOn := True; ShowAtStartup := True; ActiveAtStartup := False; Reg := CreateRegistry; try Load(Reg); finally Reg.CloseKey; Reg.Free; end; FWebServer.RunningWebAppListener.Active := True; if ActiveAtStartup then FWebServer.Active := True; end; procedure TWebAppDbgMainForm.ToggleServerActionUpdate(Sender: TObject); begin if ServerActive then (Sender as TAction).Caption := sStopServer else (Sender as TAction).Caption := sStartServer; end; procedure TWebAppDbgMainForm.StopActionExecute(Sender: TObject); begin ServerActive := False; end; procedure TWebAppDbgMainForm.StopActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := ServerActive; end; procedure TWebAppDbgMainForm.StartActionExecute(Sender: TObject); begin ServerActive := True; end; procedure TWebAppDbgMainForm.StartActionUpdate(Sender: TObject); begin (Sender as TAction).Enabled := not ServerActive; end; function TWebAppDbgMainForm.GetSearchPath: string; begin Result := FWebServer.SearchPath; end; function TWebAppDbgMainForm.GetServerActive: Boolean; begin Result := FWebServer.Active; end; function TWebAppDbgMainForm.GetServerPort: Integer; begin Result := FWebServer.Port; end; procedure TWebAppDbgMainForm.SetSearchPath(const Value: string); begin FWebServer.SearchPath := Value; end; procedure TWebAppDbgMainForm.SetServerActive(const Value: Boolean); begin FWebServer.Active := Value; end; procedure TWebAppDbgMainForm.SetServerPort(const Value: Integer); begin if ServerActive and (Value <> FWebServer.Port) then begin FWebServer.Active := False; FWebServer.Port := Value; FWebServer.Active := True; end else FWebServer.Port := Value; end; procedure TWebAppDbgMainForm.SetUDPPort(const Value: Integer); begin with FWebServer.RunningWebAppListener do if Active and (Value <> Port) then begin Active := False; Port := Value; Active := True; end else Port := Value; end; procedure TWebAppDbgMainForm.PropertiesActionExecute(Sender: TObject); var Reg: TRegIniFile; begin with TDlgProperties.Create(Application) do try ServerPort := Self.ServerPort; ServerSearchPath := Self.ServerSearchPath; DefaultURL := Self.DefaultURL; LogMax := Self.LogMax; LogDelete := Self.LogDelete; ShowAtStartup := Self.ShowAtStartup; ActiveAtStartup := Self.ActiveAtStartup; HideOnClose := Self.HideOnClose; LogFrame := Self.LogFrame; UDPPort := Self.UDPPort; Browser := Self.Browser; if ShowModal = mrOk then begin Self.ServerPort := ServerPort; Self.ServerSearchPath := ServerSearchPath; Self.DefaultURL := DefaultURL; Self.LogMax := LogMax; Self.LogDelete := LogDelete; Self.ShowAtStartup := ShowAtStartup; Self.ActiveAtStartup := ActiveAtStartup; Self.HideOnClose := HideOnClose; Self.UDPPort := UDPPort; Self.Browser := Browser; UpdateColumns; Reg := CreateRegistry; try Save(Reg); finally Reg.CloseKey; Reg.Free; end; end; finally Free; end; end; procedure TWebAppDbgMainForm.ExitActionExecute(Sender: TObject); begin Application.Terminate; end; procedure TWebAppDbgMainForm.FormDestroy(Sender: TObject); var Reg: TRegIniFile; begin LogFrame.SynchColumnInfo; Reg := CreateRegistry; try Save(Reg); finally Reg.CloseKey; Reg.Free; end; FWebServer.Free; end; {$IFDEF LINUX} const QEventType_ExecFailed = QEventType(Integer(QEventType_ClxUser) + $01); QEventType_Activate = QEventType(Integer(QEventType_ClxUser) + $02); procedure SignalProc(SigNum: Integer); cdecl; begin case SigNum of SIGUSR1: begin QApplication_postEvent(WebAppDbgMainForm.Handle, QCustomEvent_create(QEventType_ExecFailed, nil)); QApplication_wakeUpGuiThread(Application.Handle); end; SIGUSR2: begin // User attempted to start another instance of the web app debugger. Write the PID to a file // to confirm that an instance is already running. WritePIDFile; QApplication_postEvent(WebAppDbgMainForm.Handle, QCustomEvent_create(QEventType_Activate, nil)); QApplication_wakeUpGuiThread(Application.Handle); end; end; end; var LastBrowser: string; {$ENDIF} procedure TWebAppDbgMainForm.HomeClick(Sender: TObject); {$IFDEF LINUX} // Modified version of SysUtils.FileSearch. This version will not find // a directory. function FileSearch(const Name, DirList: string): string; var I, P, L: Integer; C: Char; begin Result := Name; P := 1; L := Length(DirList); while True do begin if FileExists(Result) and not DirectoryExists(Result) then Exit; // Changed while (P <= L) and (DirList[P] = PathSep) do Inc(P); if P > L then Break; I := P; while (P <= L) and (DirList[P] <> PathSep) do begin if DirList[P] in LeadBytes then P := NextCharIndex(DirList, P) else Inc(P); end; Result := Copy(DirList, I, P - I); C := AnsiLastChar(Result)^; if (C <> DriveDelim) and (C <> PathDelim) then Result := Result + PathDelim; Result := Result + Name; end; Result := ''; end; const FailToken = '!!Fail!!'; MaxToken = 256; var PID: Integer; Argv: array of PChar; Sockets: TSocketArray; ParentPID: Integer; Env: array of PChar; P: PChar; LibPath: string; I, J: Integer; S: TStrings; Path: string; {$ENDIF} begin // Add browse code here if ServerActive then if TranslatedDefaultURL <> '' then {$IFDEF MSWINDOWS} ShellExecute(0, // jmt.!!! Application.Handle, nil, PChar(TranslatedDefaultURL), nil, nil, SW_SHOWNOACTIVATE); {$ENDIF} {$IFDEF LINUX} begin LastBrowser := Browser; if Pos(PathSep, LastBrowser) = 0 then begin Path := getenv('PATH'); LastBrowser := FileSearch(LastBrowser, Path); if LastBrowser = '' then begin ShowMessage(Format(sBrowserNotFound, [Browser])); Exit; end; end else if not FileExists(LastBrowser) then begin ShowMessage(Format(sBrowserNotFound, [Browser])); Exit; end; SetLength(Argv, 3); Argv[0] := PChar(LastBrowser); Argv[1] := PChar(TranslatedDefaultURL); Argv[2] := nil; // Remove path of mozilla widget from environment so that mozilla widget so's will // not interfere with newer versions of mozilla. P := System.envp^; I := 0; while P^ <> #0 do begin SetLength(Env, I + 1); if StrLComp(P, 'LD_LIBRARY_PATH=', Length('LD_LIBRARY_PATH=')) = 0 then begin S := TStringList.Create; try ExtractStrings([':'], [], @P[Length('LD_LIBRARY_PATH=')], S); S.Delimiter := ':'; for J := S.Count - 1 downto 0 do if Pos('mozilla', S[J]) > 0 then S.Delete(J); LibPath := 'LD_LIBRARY_PATH=' + S.DelimitedText; finally S.Free; end; Env[I] := PChar(LibPath); end else Env[I] := P; P := P + StrLen(P) + 1; Inc(I); end; SetLength(Env, I+1); Env[I] := nil; ParentPID := getpid; FWebServer.GetOpenSockets(Sockets); signal(SIGUSR1, SignalProc); PID := fork; if PID = 0 then begin CloseOpenSockets(Sockets); if execve(PChar(Argv[0]), @Argv[0], @Env[0]) = -1 then kill(ParentPID, SIGUSR1); _exit(1); end; end; {$ENDIF} end; function TWebAppDbgMainForm.GetDefaultURL: string; begin Result := FWebServer.DefaultURL; end; procedure TWebAppDbgMainForm.SetDefaultURL(const Value: string); begin FWebServer.DefaultURL := Value; end; function TWebAppDbgMainForm.CreateRegistry: TRegIniFile; const sKey = '\Software\CodeGear\WebAppDbg'; { do not localize } begin Result := TRegIniFile.Create; try Result.RootKey := HKEY_LOCAL_MACHINE; if not Result.OpenKey(sKey, True) then raise Exception.CreateFmt(sCouldNotOpenRegKey, [sKey]); except Result.Free; raise; end; end; const sPort = 'Port'; sPath = 'Path'; sDefaultURL = 'DefaultURL'; sLogMax = 'LogMax'; sLogDelete = 'LogDelete'; sShowAtStartup = 'ShowAtStartup'; sActiveAtStartup = 'ActiveAtStartup'; sColumns = 'Columns'; sHideOnClose = 'HideOnClose'; sLogOn = 'LogOn'; sLeft = 'Left'; sTop = 'Top'; sWidth = 'Width'; sHeight = 'Height'; sWindowState = 'WindowState'; sBrowser = 'Browser'; procedure TWebAppDbgMainForm.Save(Reg: TRegIniFile); begin Reg.WriteInteger('', sPort, ServerPort); Reg.WriteString('', sPath, ServerSearchPath); Reg.WriteString('', sDefaultURL, DefaultURL); Reg.WriteInteger('', sLogMax, LogMax); Reg.WriteInteger('', sLogDelete, LogDelete); Reg.WriteBool('', sShowAtStartup, ShowAtStartup); Reg.WriteBool('', sActiveAtStartup, ActiveAtStartup); Reg.WriteBool('', sHideOnClose, HideOnClose); Reg.WriteBool('', sLogOn, LogOn); Reg.WriteInteger('', sWindowState, Integer(Self.WindowState)); Reg.WriteInteger('', sUDPPort, UDPPort); Reg.WriteString('', sBrowser, Browser); if WindowState = wsNormal then begin Reg.WriteInteger('', sLeft, Self.Left); Reg.WriteInteger('', sTop, Self.Top); Reg.WriteInteger('', sWidth, Self.Width); Reg.WriteInteger('', sHeight, Self.Height); end; LogFrame.Save(Reg, sColumns); end; procedure TWebAppDbgMainForm.Load(Reg: TRegIniFile); begin ServerPort := Reg.ReadInteger('', sPort, ServerPort); ServerSearchPath := Reg.ReadString('', sPath, ServerSearchPath); DefaultURL := Reg.ReadString('', sDefaultURL, DefaultURL); LogMax := Reg.ReadInteger('', sLogMax, LogMax); LogDelete := Reg.ReadInteger('', sLogDelete, LogDelete); ShowAtStartup := Reg.ReadBool('', sShowAtStartup, ShowAtStartup); ActiveAtStartup := Reg.ReadBool('', sActiveAtStartup, ActiveAtStartup); HideOnClose := Reg.ReadBool('', sHideOnClose, HideOnClose); LogOn := Reg.ReadBool('', sLogOn, LogOn); UDPPort := Reg.ReadInteger('', sUDPPort, UDPPort); Browser := Reg.ReadString('', sBrowser, Browser); if Reg.ValueExists(sLeft) then begin Position := poDesigned; Self.Left := Reg.ReadInteger('', sLeft, Self.Left); Self.Top := Reg.ReadInteger('', sTop, Self.Top); Self.Width := Reg.ReadInteger('', sWidth, Self.Width); Self.Height := Reg.ReadInteger('', sHeight, Self.Height); Self.WindowState := TWindowState(Reg.ReadInteger('', sWindowState, Integer(Self.WindowState))); end; LogFrame.Load(Reg, sColumns); end; procedure TWebAppDbgMainForm.HideActionExecute(Sender: TObject); begin Visible := False; end; procedure TWebAppDbgMainForm.SysTray1DblClick(Sender: TObject); begin Visible := not Visible; end; procedure TWebAppDbgMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TWebAppDbgMainForm.MainUpdateActionExecute(Sender: TObject); begin // end; procedure TWebAppDbgMainForm.MainUpdateActionUpdate(Sender: TObject); begin if (TranslatedDefaultURL <> '') then Home.Caption := TranslatedDefaultURL else Home.Caption := sNoDefaultURL; if ServerActive and (TranslatedDefaultURL <> '') then begin Home.Font.Color := clHighlight; Home.Font.Style := [fsUnderline]; Home.Cursor := crHandPoint; end else begin Home.Font.Color := clWindowText; Home.Font.Style := []; Home.Cursor := crDefault; end; Port.Caption := IntToStr(ServerPort); end; function TWebAppDbgMainForm.GetTranslatedDefaultURL: string; begin Result := FWebServer.TranslatedDefaultURL; end; procedure TWebAppDbgMainForm.OnLog(Sender: TObject; Transaction: TTransactionLogEntry; var Release: Boolean); begin StatsFrame.LogStatistics(Transaction); if LogOn then begin LogFrame.Add(Transaction); Release := False; end else Release := True; end; function TWebAppDbgMainForm.GetLogMax: Integer; begin Result := LogFrame.LogMax; end; procedure TWebAppDbgMainForm.SetLogMax(const Value: Integer); begin LogFrame.LogMax := Value; end; function TWebAppDbgMainForm.GetLogDelete: Integer; begin Result := LogFrame.LogDelete; end; procedure TWebAppDbgMainForm.SetLogDelete(const Value: Integer); begin LogFrame.LogDelete := Value; end; procedure TWebAppDbgMainForm.ToggleLogActionExecute(Sender: TObject); begin FLogOn := CheckBox1.Checked; end; procedure TWebAppDbgMainForm.ToggleLogActionUpdate(Sender: TObject); begin (Sender as TAction).Checked := FLogOn; end; procedure TWebAppDbgMainForm.AboutActionExecute(Sender: TObject); begin ShowAboutBox; end; function TWebAppDbgMainForm.GetUDPPort: Integer; begin Result := FWebServer.RunningWebAppListener.Port; end; {$IFDEF LINUX } function TWebAppDbgMainForm.EventFilter(Sender: QObjectH; Event: QEventH): Boolean; var EventType: QEventType; begin EventType := QEvent_type(Event); case EventType of QEventType_ExecFailed: ShowMessage(Format(sBrowserExecFailed, [LastBrowser])); QEventType_Activate: begin // User attempted to start another instance of the web app debugger QWidget_showNormal(Self.Handle); QWidget_setActiveWindow(Self.Handle); BringToFront; end; end; Result := inherited EventFilter(Sender, Event); end; {$ENDIF} {$IFDEF LINUX} function PIDFileName: string; const sPIDFile = 'webappdbgpid.txt'; begin __mkdir(PChar(getenv('HOME') + '/.borland'), S_IRWXU or S_IRWXG or S_IRWXO); result := getenv('HOME') + '/.borland/wappappdbg.lck'; end; function PIDFromFile: Integer; var PIDFile: string; S: TStream; begin Result := 0; PIDFile := PIDFileName; if FileExists(PIDFile) then begin S := TFileStream.Create(PIDFile, 0); try S.Read(Result, sizeof(Integer)); finally S.Free; end; end; end; procedure WritePIDFile; var PID: Integer; S: TStream; begin S := TFileStream.Create(PIDFileName, fmCreate); try PID := getpid; S.Write(PID, sizeof(Integer)) finally S.Free; end; end; procedure DeletePIDFile; var PIDFile: string; begin PIDFile := PIDFileName; if FileExists(PIDFile) then DeleteFile(PIDFile); end; {$ENDIF} procedure TWebAppDbgMainForm.StatsFrameResetCountsActionExecute( Sender: TObject); begin StatsFrame.ResetCountsActionExecute(Sender); if StatsFrame.Button1.Focused then pbToggle.SetFocus; end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {*******************************************************} { XML RTL Constants } {*******************************************************} unit Xml.XMLConst; interface const CRLF = #13#10; resourcestring { xmldom.pas } SDuplicateRegistration = '"%s" DOMImplementation already registered'; SNoMatchingDOMVendor = 'No matching DOM Vendor: "%s"'; SNoDOMNodeEx = 'Selected DOM Vendor does not support this property or method'; SDOMNotSupported = 'Property or Method "%s" is not supported by DOM Vendor "%s"'; { msxmldom.pas } SNodeExpected = 'Node cannot be null'; SMSDOMNotInstalled = 'Microsoft MSXML is not installed'; { oxmldom.pas } {$IFDEF MSWINDOWS} SErrorDownloadingURL = 'Error downloading URL: %s'; SUrlMonDllMissing = 'Unable to load %s'; {$ENDIF} SNotImplemented = 'This property or method is not implemented in the Open XML Parser'; { XMLDoc.pas } SNotActive = 'No active document'; SNodeNotFound = 'Node "%s" not found'; SMissingNode = 'IDOMNode required'; SNoAttributes = 'Attributes are not supported on this node type'; SInvalidNodeType = 'Invalid node type'; SMismatchedRegItems = 'Mismatched paramaters to RegisterChildNodes'; SNotSingleTextNode = 'Element "%s" does not contain a single text node'; SNoDOMParseOptions = 'DOM Implementation does not support IDOMParseOptions'; SNotOnHostedNode = 'Invalid operation on a hosted node'; SMissingItemTag = 'ItemTag property is not initialized'; SNodeReadOnly = 'Node is readonly'; SUnsupportedEncoding = 'Unsupported character encoding "%s", try using LoadFromFile'; SNoRefresh = 'Refresh is only supported if the FileName or XML properties are set'; SMissingFileName = 'FileName cannot be blank'; SLine = 'Line'; SUnknown = 'Unknown'; { XMLSchema.pas } SInvalidSchema = 'Invalid or unsupported XML Schema document'; SNoLocalTypeName = 'Local type declarations cannot have a name. Element: %s'; SUnknownDataType = 'Unknown datatype "%s"'; SInvalidValue = 'Invalid %s value: "%s"'; SInvalidGroupDecl = 'Invalid group declaration in "%s"'; SMissingName = 'Missing Type name'; SInvalidDerivation = 'Invalid complex type derivation: %s'; SNoNameOnRef = 'Name not allowed on a ref item'; SNoGlobalRef = 'Global schema items may not contain a ref'; SNoRefPropSet = '%s cannot be set on a ref item'; SSetGroupRefProp = 'Set the GroupRef property for the cmGroupRef content model'; SNoContentModel = 'ContentModel not set'; SNoFacetsAllowed = 'Facets and Enumeration not allowed on this kind of datatype "%s"'; SNotBuiltInType = 'Invalid built-in type name "%s"'; SInvalidTargetNS = 'Included schema file "%s" has an invalid targetNamespace.'+CRLF+CRLF+ 'Expected: %s'+CRLF+'Found: %s'; SUndefinedTargetNS = 'No targetNamespace attribute'; SBuiltInType = 'Built-in Type'; { XMLDataToSchema.pas } SXMLDataTransDesc = 'XMLData to XML Schema Translator (.xml -> .xsd)'; { XMLSchema99.pas } S99TransDesc = '1999 XML Schema Translator (.xsd <-> .xsd)'; { DTDSchema.pas } SDTDTransDesc = 'DTD to XML Schema Translator (.dtd <-> .xsd)'; { XDRSchema.pas } SXDRTransDesc = 'XDR to XML Schema Translator (.xdr <-> .xsd)'; implementation end.
unit RemoveReturnsAfterBegin; {(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is RemoveReturnsAfterBegin, released May 2003. The Initial Developer of the Original Code is Anthony Steele. Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele. All Rights Reserved. Contributor(s): Anthony Steele. 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/NPL/ 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 or later (the "GPL") See http://www.gnu.org/licenses/gpl.html ------------------------------------------------------------------------------*) {*)} {$I JcfGlobal.inc} interface uses SourceToken, SwitchableVisitor; type TRemoveReturnsAfterBegin = class(TSwitchableVisitor) protected function EnabledVisitSourceToken(const pcNode: TObject): Boolean; override; public constructor Create; override; function IsIncludedInSettings: boolean; override; end; implementation uses JcfSettings, Tokens, TokenUtils; { TRemoveReturnsAfterBegin } constructor TRemoveReturnsAfterBegin.Create; begin inherited; end; function TRemoveReturnsAfterBegin.EnabledVisitSourceToken(const pcNode: TObject): Boolean; var lcSourceToken: TSourceToken; lcNext: TSourceToken; lcTest: TSourceToken; liReturnCount: integer; liMaxReturns: integer; begin Result := False; lcSourceToken := TSourceToken(pcNode); if lcSourceToken.TokenType <> ttBegin then exit; if not InStatements(lcSourceToken) then exit; lcNext := lcSourceToken.NextTokenWithExclusions([ttWhiteSpace, ttReturn]); liReturnCount := 0; liMaxReturns := 2; lcTest := lcSourceToken; { remove all returns up to that point (except one) } while (lcTest <> lcNext) do begin if (lcTest.TokenType = ttReturn) then begin // allow two returns -> 1 blank line Inc(liReturnCount); if (liReturnCount > liMaxReturns) then begin BlankToken(lcTest); end; end; lcTest := lcTest.NextToken; end; end; function TRemoveReturnsAfterBegin.IsIncludedInSettings: boolean; begin Result := JcfFormatSettings.Returns.RemoveBlockBlankLines; end; end.
unit uDataGridView; {$WARN SYMBOL_PLATFORM OFF} interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,Forms, Dialogs, StdCtrls, {$IFEND} CNClrLib.Control.EnumTypes, CNClrLib.Control.EventArgs, CNClrLib.Control.Base, CNClrLib.Control.DataGridView; type TForm1 = class(TForm) ButtonLoadData: TButton; CnDataGridView1: TCnDataGridView; procedure ButtonLoadDataClick(Sender: TObject); procedure FormShow(Sender: TObject); private procedure ManuallyAddDataGridViewRows; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses CNClrLib.Windows, CNClrLib.Host; procedure TForm1.ButtonLoadDataClick(Sender: TObject); begin // Resize the height of the column headers. CnDataGridView1.AutoResizeColumnHeadersHeight(); // Resize all the row heights to fit the contents of all non-header cells. CnDataGridView1.AutoResizeRows(TDataGridViewAutoSizeRowsMode.asrmsAllCellsExceptHeaders); end; procedure TForm1.FormShow(Sender: TObject); begin ManuallyAddDataGridViewRows; end; procedure TForm1.ManuallyAddDataGridViewRows; var row1, row2, row3, row4, row5, row6: TArray<String>; rows: TArray<TArray<String>>; rowArray: TArray<String>; begin // Create an unbound DataGridView by declaring a column count. CnDataGridView1.ColumnCount := 4; CnDataGridView1.ColumnHeadersVisible := true; // Set the column header style. with CnDataGridView1.ColumnHeadersDefaultCellStyle do begin BackColor.Name := 'Beige'; Font.Name := 'Verdana'; Font.Size := 10; Font.Style := [TFontStyle.fsBold]; end; // Set the column header names. CnDataGridView1.Columns[0].Name := 'Recipe'; CnDataGridView1.Columns[1].Name := 'Category'; CnDataGridView1.Columns[2].Name := 'Main Ingredients'; CnDataGridView1.Columns[3].Name := 'Rating'; // Populate the rows. SetLength(row1, 4); row1[0] := 'Meatloaf'; row1[1] := 'Main Dish'; row1[2] := 'ground beef'; row1[3] := '**'; SetLength(row2, 4); row2[0] := 'Key Lime Pie'; row2[1] := 'Dessert'; row2[2] := 'lime juice, evaporated milk'; row2[3] := '****'; SetLength(row3, 4); row3[0] := 'Orange-Salsa Pork Chops'; row3[1] := 'Main Dish'; row3[2] := 'pork chops, salsa, orange juice'; row3[3] := '****'; SetLength(row4, 4); row4[0] := 'Black Bean and Rice Salad'; row4[1] := 'Salad'; row4[2] := 'black beans, brown rice'; row4[3] := '****'; SetLength(row5, 4); row5[0] := 'Chocolate Cheesecake'; row5[1] := 'Dessert'; row5[2] := 'cream cheese'; row5[3] := '****'; SetLength(row6, 4); row5[0] := 'Black Bean Dip'; row5[1] := 'Appetizer'; row5[2] := 'black beans, sour cream'; row5[3] := '****'; SetLength(rows, 6); rows[0] := row1; rows[1] := row2; rows[2] := row3; rows[3] := row4; rows[4] := row5; rows[5] := row6; for rowArray in rows do begin CnDataGridView1.Rows.Add_1(TClrArrayHelper.ToObjectArray(rowArray)); end; end; end.
(***************************************************************************** * Pascal Solution to "Bart Stays After School" from the * * * * Seventh Annual UCF ACM UPE High School Programming Tournament * * May 15, 1993 * * * *****************************************************************************) program bart; var f: text; n: integer; sentence: string; i: integer; begin assign( f, 'bart.in' ); reset( f ); while not eof( f ) do begin readln( f, n ); readln( f, sentence ); for i := 1 to n do begin writeln( sentence ); end; writeln; end; close( f ); end.
unit MediaStorage.Transport.FileServer; interface uses SysUtils,Classes, Windows, dInterfacesFileAgent,dInterfacesObjectFileStorage,MediaStorage.Transport; type //Транспорт через собственный FileServer TRecordObjectTransport_FileServer =class (TRecordObjectTransportBase,IRecordObjectTransport) private FConnectionString: string; FPrebuffer_OperationalKB: cardinal; FPrebuffer_FileKB: cardinal; public function TypeCode: byte; //Название транспорта function Name: string; //Доставляет файл и дает на него ссылку function GetReader: IRecordObjectReader; //Создает экземпляр писателя файла function GetWriter: IRecordObjectWriter; function FileExists: boolean; function FileSize: int64; function ConnectionString: string; function NeedCopying: boolean; constructor Create(const aConnectionString: string;aPrebuffer_OperationalKB: cardinal=100; aPrebuffer_FileKB: cardinal=100); end; implementation uses HHCommon, uFileAgent,uTrace {$IFDEF STATIC_LINK_FILEAGENT} ,uFileAgent_impl {$ENDIF} ; const SearchResultTitles: array [boolean] of string = ('Не найден','Найден'); function ExtractHostFromNetAddress(const aNetAddress: string): string; var i: integer; begin if (not (Length(aNetAddress)>2)) or (not (aNetAddress[1]='\')) or (not (aNetAddress[2]='\')) then raise Exception.Create('Указанный адрес не является сетевым'); i:=3; while i<=Length(aNetAddress) do begin if i<Length(aNetAddress) then if aNetAddress[i+1]='\' then break; inc(i); end; result:=Copy(aNetAddress,3,i-3+1); end; function GetFileAgent(аPrebuffer_OperationalKB: cardinal): IFileAgent; var aTempPath: string; begin {$IFDEF STATIC_LINK_FILEAGENT} result:=uFileAgent_impl.GetXClassIface as IFileAgent; {$ELSE} result:=fsiFileAgent; {$ENDIF} //result.ConnectCount:=1; //result.ConnectDelay:=0; Assert(аPrebuffer_OperationalKB>0); result.BlockSize:=аPrebuffer_OperationalKB*1024; SetLength(aTempPath,MAX_PATH); GetTempPath(length(aTempPath), pchar(aTempPath)); aTempPath:=IncludeTrailingPathDelimiter(pchar(aTempPath))+'FileAgentCache'; result.CacheDirectory:=aTempPath; end; type TRecordObjectReader_FileServer = class (TRecordObjectFileBase,IRecordObjectReader) private FFileAgentStreamMediator : TStream; FPrebuffer_OperationalKB: cardinal; FPrebuffer_FileKB: cardinal; public function GetStream: TStream; function GetWholeFile: string; procedure PrepareFromBegin; procedure PrepareFromEnd; constructor Create(const aConnectionString: string;aPrebuffer_OperationalKB: cardinal; aPrebuffer_FileKB: cardinal); destructor Destroy; override; end; TRecordObjectWriter_FileServer = class (TRecordObjectFileBase,IRecordObjectWriter) private FFileName : string; public procedure WriteAndCommit(const aData; aSize: integer); overload; //Записывает данные из указанного файла в себя и сразу же закрывает сессию. Можно вызывать только 1 раз procedure WriteAndCommit(const aFileName: string); overload; constructor Create(const aFileName: string); destructor Destroy; override; end; TFileAgentStreamMediator = class (TStream) private FPrebuffer_OperationalKB: cardinal; FFileAgentReader: IFileReader; public constructor Create(const aFileAgentReader: IFileReader; aPrebuffer_OperationalKB: cardinal); destructor Destroy; override; function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; end; { TRecordObjectTransport_FileServer } function TRecordObjectTransport_FileServer.ConnectionString: string; begin result:=FConnectionString; end; constructor TRecordObjectTransport_FileServer.Create(const aConnectionString: string;aPrebuffer_OperationalKB: cardinal; aPrebuffer_FileKB: cardinal); begin inherited Create; Assert(aPrebuffer_OperationalKB>0); FPrebuffer_OperationalKB:=aPrebuffer_OperationalKB; FPrebuffer_FileKB:=aPrebuffer_FileKB; FConnectionString:=aConnectionString; ExtractHostFromNetAddress(FConnectionString); //Проверим, а вообще это сетевой путь end; function TRecordObjectTransport_FileServer.FileExists: boolean; const aMethodName = 'TRecordObjectTransport_FileServer.FileExists'; var aFileAgent : IFileAgent; aTraceID : cardinal; begin aTraceID:=TraceProcBegin(aMethodName); try aFileAgent:=GetFileAgent(FPrebuffer_OperationalKB); result:=aFileAgent.FileExists(FConnectionString); TraceLine('Поиск файла '+FConnectionString+':'+SearchResultTitles[result]); finally TraceProcEnd(aMethodName,aTraceID); end; end; function TRecordObjectTransport_FileServer.FileSize: int64; const aMethodName = 'TRecordObjectTransport_FileServer.FileSize'; var aFileAgent : IFileAgent; aTraceID : cardinal; begin aTraceID:=TraceProcBegin(aMethodName); try aFileAgent:=GetFileAgent(FPrebuffer_OperationalKB); result:=aFileAgent.FileSize(FConnectionString); finally TraceProcEnd(aMethodName,aTraceID); end; end; function TRecordObjectTransport_FileServer.GetReader: IRecordObjectReader; begin result:=TRecordObjectReader_FileServer.Create(ConnectionString,FPrebuffer_OperationalKB,FPrebuffer_FileKB); end; function TRecordObjectTransport_FileServer.TypeCode: byte; begin result:=1; end; function TRecordObjectTransport_FileServer.GetWriter: IRecordObjectWriter; begin result:=TRecordObjectWriter_FileServer.Create(ConnectionString); end; function TRecordObjectTransport_FileServer.NeedCopying: boolean; begin result:=true; end; function TRecordObjectTransport_FileServer.Name: string; begin result:='File Server'; end; { TRecordObjectReader_FileServer } constructor TRecordObjectReader_FileServer.Create(const aConnectionString: string;aPrebuffer_OperationalKB: cardinal; aPrebuffer_FileKB: cardinal); var aFileAgent : IFileAgent; aFileAgentReader : IFileReader; begin Assert(aPrebuffer_OperationalKB>0); FPrebuffer_OperationalKB:=aPrebuffer_OperationalKB; FPrebuffer_FileKB:=aPrebuffer_FileKB; aFileAgent:=GetFileAgent(FPrebuffer_OperationalKB); aFileAgentReader:=aFileAgent.GetFileStreamEx(aConnectionString); FFileAgentStreamMediator:=TFileAgentStreamMediator.Create(aFileAgentReader,FPrebuffer_OperationalKB); end; destructor TRecordObjectReader_FileServer.Destroy; begin FreeAndNil(FFileAgentStreamMediator); inherited; end; function TRecordObjectReader_FileServer.GetStream: TStream; begin result:=FFileAgentStreamMediator; end; function TRecordObjectReader_FileServer.GetWholeFile: string; var aLocalFile : TFileStream; aSize: int64; begin with TFileAgentStreamMediator(FFileAgentStreamMediator) do begin aSize:=FFileAgentReader.Size; FFileAgentReader.PrepareSync(0,aSize); result:=FFileAgentReader.GetLocalFileName; end; FreeAndNil(FFileAgentStreamMediator); //Проверка aLocalFile:=TFileStream.Create(PChar(result),fmOpenRead or fmShareDenyNone); try Assert(aSize=aLocalFile.Size); finally aLocalFile.Free; end; end; procedure TRecordObjectReader_FileServer.PrepareFromBegin; begin if FFileAgentStreamMediator<>nil then //Такое может быть в случае GetWholeFile //X КБ с начала TFileAgentStreamMediator(FFileAgentStreamMediator).FFileAgentReader.Prepare(0,FPrebuffer_FileKB*1024); end; procedure TRecordObjectReader_FileServer.PrepareFromEnd; begin if FFileAgentStreamMediator<>nil then //Такое может быть в случае GetWholeFile with TFileAgentStreamMediator(FFileAgentStreamMediator) do begin //Оперативный буфер с начала FFileAgentReader.Prepare(0,FPrebuffer_OperationalKB*1024); //Файловый буфер с конца FFileAgentReader.Prepare(FFileAgentReader.Size-integer(FPrebuffer_FileKB*1024),FPrebuffer_FileKB*1024); end; end; { TRecordObjectWriter_FileServer } constructor TRecordObjectWriter_FileServer.Create(const aFileName: string); begin inherited Create; FFileName:=aFileName; end; destructor TRecordObjectWriter_FileServer.Destroy; begin inherited; end; procedure TRecordObjectWriter_FileServer.WriteAndCommit(const aFileName: string); var aFileAgent : IFileAgent; begin aFileAgent:=GetFileAgent(100*1024); aFileAgent.CopyFile(aFileName,FFileName); aFileAgent:=nil; end; procedure TRecordObjectWriter_FileServer.WriteAndCommit(const aData; aSize: integer); begin raise Exception.Create('Не реализовано'); end; { TFileAgentStreamMediator } constructor TFileAgentStreamMediator.Create(const aFileAgentReader: IFileReader;aPrebuffer_OperationalKB: cardinal); begin Assert(aPrebuffer_OperationalKB>0); FPrebuffer_OperationalKB:=aPrebuffer_OperationalKB; FFileAgentReader:=aFileAgentReader; inherited Create; end; destructor TFileAgentStreamMediator.Destroy; begin FFileAgentReader:=nil; inherited; end; function TFileAgentStreamMediator.Read(var Buffer; Count: Integer): Longint; begin //FIX Считывание заголовков из MP6 //TODO продумать, как сделать настройку if Count<=sizeof(HV_FRAME_HEAD) then begin result:=FFileAgentReader.ReadNoCache(Buffer,Count); end else begin result:=FFileAgentReader.Read(Buffer,Count); //Ставим на докачку следующие X КБ оперативного буфера FFileAgentReader.Prepare(FFileAgentReader.Position,FPrebuffer_OperationalKB*1024); end; end; function TFileAgentStreamMediator.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; begin result:=FFileAgentReader.Seek(Offset,Word(Origin)); end; function TFileAgentStreamMediator.Write(const Buffer; Count: Integer): Longint; begin raise Exception.Create('Операция не поддерживается'); end; end.
//Code Owner: https://stackoverflow.com/a/43591761 unit AESencdec; interface uses DCPcrypt2, DCPsha256, DCPblockciphers, DCPrijndael, System.SysUtils; type TChainingMode = (cmCBC, cmCFB8bit, cmCFBblock, cmOFB, cmCTR, cmECB); TPaddingMode = (pmZeroPadding, pmANSIX923, pmISO10126, pmISO7816, pmPKCS7, pmRandomPadding); TAESEncDec = class public procedure BytePadding(var Data: TBytes; BlockSize: integer; PaddingMode: TPaddingMode); function EncryptAES(const Data: TBytes; const Key: TBytes; KeySize: integer; const InitVector: TBytes; ChainingMode: TChainingMode; PaddingMode: TPaddingMode): TBytes; end; implementation procedure TAESEncDec.BytePadding(var Data: TBytes; BlockSize: integer; PaddingMode: TPaddingMode); // Supports: ANSI X.923, ISO 10126, ISO 7816, PKCS7, zero padding and random padding var I, DataBlocks, DataLength, PaddingStart, PaddingCount: integer; begin BlockSize := BlockSize div 8; // convert bits to bytes // Zero and Random padding do not use end-markers, so if Length(Data) is a multiple of BlockSize, no padding is needed if PaddingMode in [pmZeroPadding, pmRandomPadding] then if Length(Data) mod BlockSize = 0 then Exit; DataBlocks := (Length(Data) div BlockSize) + 1; DataLength := DataBlocks * BlockSize; PaddingCount := DataLength - Length(Data); // ANSIX923, ISO10126 and PKCS7 store the padding length in a 1 byte end-marker, so any padding length > $FF is not supported if PaddingMode in [pmANSIX923, pmISO10126, pmPKCS7] then if PaddingCount > $FF then Exit; PaddingStart := Length(Data); SetLength(Data, DataLength); case PaddingMode of pmZeroPadding, pmANSIX923, pmISO7816: // fill with $00 bytes FillChar(Data[PaddingStart], PaddingCount, 0); pmPKCS7: // fill with PaddingCount bytes FillChar(Data[PaddingStart], PaddingCount, PaddingCount); pmRandomPadding, pmISO10126: // fill with random bytes for I := PaddingStart to DataLength - 1 do Data[I] := Random($FF); end; case PaddingMode of pmANSIX923, pmISO10126: Data[DataLength - 1] := PaddingCount; // set end-marker with number of bytes added pmISO7816: Data[PaddingStart] := $80; // set fixed end-markder $80 end; end; function TAESEncDec.EncryptAES(const Data: TBytes; const Key: TBytes; KeySize: integer; const InitVector: TBytes; ChainingMode: TChainingMode; PaddingMode: TPaddingMode): TBytes; var Cipher: TDCP_rijndael; begin Cipher := TDCP_rijndael.Create(nil); try Cipher.Init(Key[0], KeySize, @InitVector[0]); // Copy Data => Crypt Result := Copy(Data, 0, Length(Data)); // Padd Crypt to required length (for Block based algorithms) if ChainingMode in [cmCBC, cmECB] then BytePadding(Result, Cipher.BlockSize, PaddingMode); // Encrypt Crypt using the algorithm specified in ChainingMode case ChainingMode of cmCBC: Cipher.EncryptCBC(Result[0], Result[0], Length(Result)); cmCFB8bit: Cipher.EncryptCFB8bit(Result[0], Result[0], Length(Result)); cmCFBblock: Cipher.EncryptCFBblock(Result[0], Result[0], Length(Result)); cmOFB: Cipher.EncryptOFB(Result[0], Result[0], Length(Result)); cmCTR: Cipher.EncryptCTR(Result[0], Result[0], Length(Result)); cmECB: Cipher.EncryptECB(Result[0], Result[0]); end; finally Cipher.Free; end; end; end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000, 2001 Borland Software Corporation } { } { *************************************************************************** } unit QCheckLst; {$T-,H+,X+} interface uses Types, SysUtils, Qt, Classes, QGraphics, QControls, QStdCtrls, QImgList; type TCheckListBox = class(TCustomListBox) private FAllowGrayed: Boolean; FFlat: Boolean; FOnClickCheck: TNotifyEvent; FSaveStates: TList; procedure ResetItemHeight; procedure SetChecked(Index: Integer; AChecked: Boolean); function GetChecked(Index: Integer): Boolean; procedure SetState(Index: Integer; AState: TCheckBoxState); function GetState(Index: Integer): TCheckBoxState; procedure ToggleClickCheck(Index: Integer); procedure InvalidateCheck(Index: Integer); function CreateWrapper(Index: Integer): TObject; function ExtractWrapper(Index: Integer): TObject; function GetWrapper(Index: Integer): TObject; function HaveWrapper(Index: Integer): Boolean; procedure SetFlat(Value: Boolean); function GetItemEnabled(Index: Integer): Boolean; procedure SetItemEnabled(Index: Integer; const Value: Boolean); protected procedure ClickCheck; dynamic; procedure CreateWidget; override; procedure DeleteString(Index: Integer); override; procedure DrawCheck(R: TRect; AState: TCheckBoxState; AEnabled: Boolean); virtual; function DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState): Boolean; override; function GetCheckWidth: Integer; virtual; function GetItemData(Index: Integer): LongInt; override; procedure KeyPress(var Key: Char); override; procedure MeasureItem(Control: TWinControl; Index: Integer; var Height, Width: Integer); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure ResetContent; override; procedure SetItemData(Index: Integer; AData: LongInt); override; procedure SaveWidgetState; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Checked[Index: Integer]: Boolean read GetChecked write SetChecked; property ItemEnabled[Index: Integer]: Boolean read GetItemEnabled write SetItemEnabled; property State[Index: Integer]: TCheckBoxState read GetState write SetState; published property Style; { Must be published before Items } property Align; property AllowGrayed: Boolean read FAllowGrayed write FAllowGrayed default False; property Anchors; property BorderStyle; property Color; property Columns; property ColumnLayout; property Constraints; property DragMode; property Enabled; property Flat: Boolean read FFlat write SetFlat default True; property Font; property ItemHeight; property Items; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property RowLayout; property Rows; property ShowHint; property Sorted; property TabOrder; property TabStop; property Visible; property OnClick; property OnClickCheck: TNotifyEvent read FOnClickCheck write FOnClickCheck; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDrawItem; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyString; property OnKeyUp; property OnMeasureItem; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; implementation uses QConsts; {$R QCheckLst.res} const NumImages = 10; type TCheckListImage = (ciCheck, ciCheckGray, ciGray, ciUncheck); var DefImages: TImageList = nil; FCheckHeight, FCheckWidth: Integer; ImageResNames: array[0..NumImages-1] of PChar = ( 'CLB_CHK', 'CLB_CHK3D', 'CLB_DIS', 'CLB_DIS3D', 'CLB_GRY', 'CLB_GRY3D', 'CLB_GRYCHK', 'CLB_GRYCHK3D', 'CLB_UNCHK', 'CLB_UNCHK3D'); function DefaultImages: TImageList; var B: TBitmap; I: Integer; begin if not Assigned(DefImages) then begin DefImages := TImageList.CreateSize(12, 12); B := TBitmap.Create; try for I := 0 to NumImages - 1 do begin B.LoadFromResourceName(HInstance, ImageResNames[I]); DefImages.AddMasked(B, clOlive); end; finally B.Free; end; end; Result := DefImages; end; procedure GetCheckSize; begin FCheckHeight := DefaultImages.Height; FCheckWidth := DefaultImages.Width; end; type TCheckListBoxDataWrapper = class private FData: LongInt; FState: TCheckBoxState; FDisabled: Boolean; procedure SetChecked(Check: Boolean); function GetChecked: Boolean; public class function GetDefaultState: TCheckBoxState; property Checked: Boolean read GetChecked write SetChecked; property State: TCheckBoxState read FState write FState; property Disabled: Boolean read FDisabled write FDisabled; end; function MakeSaveState(State: TCheckBoxState; Disabled: Boolean): TObject; begin Result := TObject((Byte(State) shl 16) or Byte(Disabled)); end; function GetSaveState(AObject: TObject): TCheckBoxState; begin Result := TCheckBoxState(Integer(AObject) shr 16); end; function GetSaveDisabled(AObject: TObject): Boolean; begin Result := Boolean(Integer(AObject) and $FF); end; { TCheckListBoxDataWrapper } procedure TCheckListBoxDataWrapper.SetChecked(Check: Boolean); begin if Check then FState := cbChecked else FState := cbUnchecked; end; function TCheckListBoxDataWrapper.GetChecked: Boolean; begin Result := FState = cbChecked; end; class function TCheckListBoxDataWrapper.GetDefaultState: TCheckBoxState; begin Result := cbUnchecked; end; { TCheckListBox } constructor TCheckListBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FFlat := True; end; procedure TCheckListBox.CreateWidget; begin inherited CreateWidget; ResetItemHeight; end; function TCheckListBox.GetCheckWidth: Integer; begin Result := FCheckWidth + 2; end; procedure TCheckListBox.ResetItemHeight; begin end; function TCheckListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState): Boolean; var R: TRect; SaveEvent: TDrawItemEvent; ACheckWidth: Integer; Enable: Boolean; begin if (Style = lbStandard) and Assigned(OnDrawItem) then begin { Force lbStandard list to ignore OnDrawItem event. } SaveEvent := OnDrawItem; OnDrawItem := nil; try Result := inherited DrawItem(Index, Rect, State); finally OnDrawItem := SaveEvent; end; end else begin R := Rect; R.Left := GetCheckWidth; Result := inherited DrawItem(Index, R, State); end; Enable := True; ACheckWidth := GetCheckWidth; if Index < Items.Count then begin R := Rect; R.Right := R.Left + ACheckWidth; Rect.Left := R.Right + 1; Enable := (Self.Enabled and GetItemEnabled(Index)); Canvas.Brush.Color := clWindow; Canvas.FillRect(R); DrawCheck(R, GetState(Index), Enable); end; if Result then Exit; if odSelected in State then begin Canvas.Brush.Color := clHighlight; if Enable then Canvas.Font.Color := clHighlightText else Canvas.Font.Color := clGray; end else begin Canvas.Brush.Color := Color; if not Enable then Canvas.Font.Color := clGray else Canvas.Font.Color := Font.Color; end; Canvas.FillRect(Rect); Canvas.TextRect(Rect, Rect.Left, Rect.Top, Items[Index], Integer(AlignmentFlags_AlignLeft) or Integer(AlignmentFlags_AlignVCenter)); if odFocused in State then Canvas.DrawFocusRect(Rect); Result := True; end; procedure TCheckListBox.DrawCheck(R: TRect; AState: TCheckBoxState; AEnabled: Boolean); const ImageIndex: array[Boolean, Boolean, TCheckBoxState] of Integer = (((3, 7, 7), (2, 6, 6)), ((9, 1, 5), (8, 0, 4))); var DrawRect: TRect; begin DrawRect.Left := R.Left + (R.Right - R.Left - FCheckWidth) div 2; DrawRect.Top := R.Top + (R.Bottom - R.Top - FCheckWidth) div 2; DrawRect.Right := DrawRect.Left + FCheckWidth; DrawRect.Bottom := DrawRect.Top + FCheckHeight; if Flat then begin Inc(DrawRect.Left); Inc(DrawRect.Top); Dec(DrawRect.Right); Dec(DrawRect.Bottom); end; Canvas.Brush.Color := clWindow; Canvas.FillRect(DrawRect); if Flat then begin Dec(DrawRect.Left); Dec(DrawRect.Top); end; DefaultImages.Draw(Canvas, DrawRect.Left, DrawRect.Top, ImageIndex[AEnabled, FFlat, AState]); end; procedure TCheckListBox.SetChecked(Index: Integer; AChecked: Boolean); begin if AChecked <> GetChecked(Index) then begin TCheckListBoxDataWrapper(GetWrapper(Index)).SetChecked(AChecked); InvalidateCheck(Index); end; end; procedure TCheckListBox.SetItemEnabled(Index: Integer; const Value: Boolean); begin if Value <> GetItemEnabled(Index) then begin TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled := not Value; InvalidateCheck(Index); end; end; procedure TCheckListBox.SetState(Index: Integer; AState: TCheckBoxState); begin if AState <> GetState(Index) then begin TCheckListBoxDataWrapper(GetWrapper(Index)).State := AState; InvalidateCheck(Index); end; end; procedure TCheckListBox.InvalidateCheck(Index: Integer); var R: TRect; begin R := ItemRect(Index); R.Right := R.Left + GetCheckWidth; InvalidateRect(R, not (csOpaque in ControlStyle)); Update; end; function TCheckListBox.GetChecked(Index: Integer): Boolean; begin if HaveWrapper(Index) then Result := TCheckListBoxDataWrapper(GetWrapper(Index)).GetChecked else Result := False; end; function TCheckListBox.GetItemEnabled(Index: Integer): Boolean; begin if HaveWrapper(Index) then Result := not TCheckListBoxDataWrapper(GetWrapper(Index)).Disabled else Result := True; end; function TCheckListBox.GetState(Index: Integer): TCheckBoxState; begin if HaveWrapper(Index) then Result := TCheckListBoxDataWrapper(GetWrapper(Index)).State else Result := TCheckListBoxDataWrapper.GetDefaultState; end; procedure TCheckListBox.KeyPress(var Key: Char); begin inherited; if (Key = ' ') then ToggleClickCheck(ItemIndex); end; procedure TCheckListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Index: Integer; begin inherited; if Button = mbLeft then begin Index := ItemAtPos(Point(X,Y), True); if (Index <> -1) and GetItemEnabled(Index) then if X - ItemRect(Index).Left < GetCheckWidth then begin ItemIndex := Index; ToggleClickCheck(Index); end; end; end; procedure TCheckListBox.ToggleClickCheck; var State: TCheckBoxState; begin if (Index >= 0) and (Index < Items.Count) and GetItemEnabled(Index) then begin State := Self.State[Index]; case State of cbUnchecked: if AllowGrayed then State := cbGrayed else State := cbChecked; cbChecked: State := cbUnchecked; cbGrayed: State := cbChecked; end; Self.State[Index] := State; ClickCheck; end; end; procedure TCheckListBox.ClickCheck; begin if Assigned(FOnClickCheck) then FOnClickCheck(Self); end; function TCheckListBox.GetItemData(Index: Integer): LongInt; begin Result := 0; if HaveWrapper(Index) then Result := TCheckListBoxDataWrapper(GetWrapper(Index)).FData; end; function TCheckListBox.GetWrapper(Index: Integer): TObject; begin Result := ExtractWrapper(Index); if Result = nil then Result := CreateWrapper(Index); end; function TCheckListBox.ExtractWrapper(Index: Integer): TObject; begin Result := TCheckListBoxDataWrapper(inherited GetItemData(Index)); if Integer(Result) = -1 then raise EListError.CreateResFmt(@SListIndexError, [Index]); if (Result <> nil) and (not (Result is TCheckListBoxDataWrapper)) then Result := nil; end; function TCheckListBox.CreateWrapper(Index: Integer): TObject; begin Result := TCheckListBoxDataWrapper.Create; inherited SetItemData(Index, LongInt(Result)); end; function TCheckListBox.HaveWrapper(Index: Integer): Boolean; begin Result := ExtractWrapper(Index) <> nil; end; procedure TCheckListBox.SetItemData(Index: Integer; AData: LongInt); var Wrapper: TCheckListBoxDataWrapper; SaveState: TObject; begin Wrapper := TCheckListBoxDataWrapper(GetWrapper(Index)); Wrapper.FData := AData; if FSaveStates <> nil then if FSaveStates.Count > 0 then begin SaveState := FSaveStates[0]; Wrapper.FState := GetSaveState(SaveState); Wrapper.FDisabled := GetSaveDisabled(SaveState); FSaveStates.Delete(0); end; end; procedure TCheckListBox.ResetContent; var I: Integer; begin for I := 0 to Items.Count - 1 do if HaveWrapper(I) then GetWrapper(I).Free; inherited; end; procedure TCheckListBox.DeleteString(Index: Integer); begin if HaveWrapper(Index) then GetWrapper(Index).Free; inherited; end; procedure TCheckListBox.SetFlat(Value: Boolean); begin if Value <> FFlat then begin FFlat := Value; Update; end; end; procedure TCheckListBox.MeasureItem(Control: TWinControl; Index: Integer; var Height, Width: Integer); begin Width := Width + GetCheckWidth; inherited MeasureItem(Control, Index, Height, Width); end; procedure TCheckListBox.SaveWidgetState; var I: Integer; begin inherited SaveWidgetState; if Items.Count > 0 then begin FSaveStates := TList.Create; for I := 0 to Items.Count - 1 do FSaveStates.Add(MakeSaveState(State[I], not ItemEnabled[I])); end; end; destructor TCheckListBox.Destroy; begin FSaveStates.Free; inherited Destroy; end; initialization GetCheckSize; finalization FreeAndNil(DefImages); end.
program queue2; type TQueue = record data: array of integer; head: integer; tail: integer; size: integer; len: integer; end; procedure queue_init(var queue: TQueue; len: integer); begin SetLength(queue.data, len); queue.len := len; queue.head := 0; queue.tail := 0; queue.size := 0; end; procedure queue_destroy(var queue: TQueue); begin queue_init(queue, 0); end; function queue_size(var queue: TQueue): integer; begin queue_size := queue.size; end; function queue_length(var queue: TQueue): integer; begin queue_length := queue.len; end; function queue_is_full(var queue: TQueue): boolean; begin queue_is_full := queue_size(queue) >= queue_length(queue); end; function queue_is_empty(var queue: TQueue): boolean; begin queue_is_empty := queue_size(queue) <= 0; end; function queue_add(var queue: TQueue; number: integer): boolean; begin if queue_is_full(queue) then begin queue_add := false; exit; end; queue.data[queue.head] := number; queue.head := queue.head + 1; queue.size := queue.size + 1; if queue.head >= queue.len then queue.head := 0; if (queue.head = queue.tail) and (not queue_is_full(queue)) then begin writeln('Head has catched up Tail but the queue is not full!'); halt; end; queue_add := true; end; function queue_get(var queue: TQueue; var number: integer): boolean; begin if queue_is_empty(queue) then begin queue_get := false; exit; end; number := queue.data[queue.tail]; queue.tail := queue.tail + 1; queue.size := queue.size - 1; if queue.tail >= queue.len then queue.tail := 0; if (queue.tail = queue.head) and (not queue_is_empty(queue)) then begin writeln('Tail has catched up Head but the queue is not empty!'); halt; end; queue_get := true; end; procedure queue_debug(var queue: TQueue); var k: integer; begin writeln('>>> Size/Length: ', queue.size, '/', queue.len, ' Head: ', queue.head, ' Tail: ', queue.tail); write('>>> '); for k:=0 to queue.len - 1 do write(queue.data[k], ' '); writeln; end; var q1, q2: TQueue; i: integer; begin queue_init(q1, 14); queue_init(q2, 4); i := 0; while queue_add(q1, i) do i := i + 1; queue_add(q2, 22); queue_add(q2, 23); queue_add(q2, 24); queue_add(q2, 25); queue_get(q2, i); queue_get(q2, i); queue_add(q2, 26); queue_add(q2, 27); queue_add(q2, 28); queue_add(q2, 29); writeln('Queue1 size: ', queue_size(q1)); queue_debug(q1); writeln('Queue2 size: ', queue_size(q2)); queue_debug(q2); write('Queue1: '); while queue_get(q1, i) do write(i, ' '); writeln; write('Queue2: '); while queue_get(q2, i) do write(i, ' '); writeln; writeln('After empting queues...'); writeln('Queue1 size: ', queue_size(q1)); queue_debug(q1); writeln('Queue2 size: ', queue_size(q2)); queue_debug(q2); queue_destroy(q1); queue_destroy(q2); writeln('After destroying...'); writeln('Queue1 size: ', queue_size(q1)); queue_debug(q1); writeln('Queue2 size: ', queue_size(q2)); queue_debug(q2); end.
unit uMainForm; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.Ani, FMX.Edit, FMX.Filter.Effects, FMX.Layouts, FMX.Effects, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FMX.ListView, FMX.TabControl, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, FMX.ScrollBox, FMX.Memo, FireDAC.Stan.StorageBin, FMX.ComboEdit, FMX.EditBox, FMX.ComboTrackBar, System.Threading {$IFDEF MSWINDOWS} , WinApi.Windows, FMX.MultiView, FMX.Memo.Types, FMX.Grid.Style, Data.Bind.Controls, Fmx.Bind.Grid, Data.Bind.Grid, Fmx.Bind.Navigator, FMX.Grid {$ENDIF} ; type TMainForm = class(TForm) Rectangle1: TRectangle; MaterialOxfordBlueSB: TStyleBook; Layout1: TLayout; TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; ListView1: TListView; ProjectsFDMemTable: TFDMemTable; BuildButton: TButton; Layout3: TLayout; PathEdit: TEdit; SearchEditButton1: TSearchEditButton; ScanButton: TButton; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; ErrorLogMemo: TMemo; VertScrollBox1: TVertScrollBox; Layout2: TLayout; Layout4: TLayout; Layout5: TLayout; Layout6: TLayout; ExecParamsEdit: TEdit; RSVarsFDMemTable: TFDMemTable; RSVArsComboEdit: TComboEdit; BindSourceDB2: TBindSourceDB; PlatformFDMemTable: TFDMemTable; PlatformComboEdit: TComboEdit; BindSourceDB3: TBindSourceDB; CPUTB: TComboTrackBar; LinkFillControlToField: TLinkFillControlToField; LinkFillControlToField2: TLinkFillControlToField; LinkListControlToField1: TLinkListControlToField; StatusLabel: TLabel; Layout9: TLayout; Layout10: TLayout; CleanSwitch: TSwitch; Label2: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; TabItem3: TTabItem; StatusBar1: TStatusBar; Layout7: TLayout; Layout8: TLayout; TwineSwitch: TSwitch; Label1: TLabel; ClearButton: TButton; ResetButton: TButton; Layout11: TLayout; Layout12: TLayout; RetrySwitch: TSwitch; Label3: TLabel; ExtStringGrid: TStringGrid; BindNavigator1: TBindNavigator; ExtFDMemTable: TFDMemTable; BindSourceDB4: TBindSourceDB; LinkGridToDataSourceBindSourceDB4: TLinkGridToDataSource; procedure ScanButtonClick(Sender: TObject); procedure SearchEditButton1Click(Sender: TObject); procedure BuildButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ClearButtonClick(Sender: TObject); procedure ResetButtonClick(Sender: TObject); private { Private declarations } FCancel: Boolean; function ProcessTask(const AId: Integer): ITask; procedure BuildProject(const AId: Integer; const APath: String); procedure BuildEnd(const ATime: String); {$IFDEF MSWINDOWS} function ExeAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; {$ENDIF} public { Public declarations } end; const STS_READY = 'Ready'; STS_BUILDING = 'Building...'; STS_SUCCESS = 'Complete'; STS_FAIL = 'Failed'; var MainForm: TMainForm; implementation {$R *.fmx} uses System.Diagnostics, System.IOUtils; procedure TMainForm.ScanButtonClick(Sender: TObject); var LList: TStringDynArray; LSearchOption: TSearchOption; LItem: String; begin LSearchOption := TSearchOption.soAllDirectories; ExtFDMemTable.First; while not ExtFDMemTable.Eof do begin LList := LList + TDirectory.GetFiles(PathEdit.Text, ExtFDMemTable.FieldByName('Extension').AsWideString, LSearchOption); ExtFDMemTable.Next; end; ProjectsFDMemTable.EmptyDataSet; ProjectsFDMemTable.BeginBatch; for LItem in LList do begin ProjectsFDMemTable.Append; ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Filename').AsString := ExtractFileName(LItem); ProjectsFDMemTable.FieldByName('FullPath').AsString := LItem; ProjectsFDMemTable.FieldByName('Status').AsString := STS_READY; ProjectsFDMemTable.Post; end; ProjectsFDMemTable.EndBatch; StatusLabel.Text := ProjectsFDMemTable.RecordCount.ToString + ' projects found.'; end; procedure TMainForm.SearchEditButton1Click(Sender: TObject); var LDirectory: String; begin if SelectDirectory('Open Projects',ExtractFilePath(ParamStr(0)),LDirectory) then begin PathEdit.Text := LDirectory; end; end; function TMainForm.ProcessTask(const AId: Integer): ITask; begin Result := TTask.Create(procedure var LIndex: Integer; LPath: String; begin for LIndex := 0 to ProjectsFDMemTable.RecordCount-1 do begin LPath := ''; TThread.Synchronize(nil,procedure begin if RetrySwitch.IsChecked=True then if ProjectsFDMemTable.Locate('Status',VarArrayOf([STS_FAIL]),[])=True then begin ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Status').AsString := STS_READY; ProjectsFDMemTable.Post; end; if ProjectsFDMemTable.Locate('Status',VarArrayOf([STS_READY]),[])=True then begin LPath := ProjectsFDMemTable.FieldByName('FullPath').AsString; ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Status').AsString := STS_BUILDING; ProjectsFDMemTable.Post; end; end); if LPath='' then Exit; BuildProject(AId, LPath); if FCancel then Break; end; end); end; procedure TMainForm.ResetButtonClick(Sender: TObject); begin ErrorLogMemo.Lines.Clear; ProjectsFDMemTable.First; while not ProjectsFDMemTable.EOF do begin ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Status').AsString := STS_READY; ProjectsFDMemTable.Post; ProjectsFDMemTable.Next; end; end; procedure TMainForm.BuildEnd(const ATime: String); begin if FCancel=False then StatusLabel.Text := 'Completed in '+ATime+'ms' else StatusLabel.Text := 'Canceled'; BuildButton.Tag := 0; BuildButton.Text := BuildButton.Hint; FCancel := False; end; procedure TMainForm.BuildButtonClick(Sender: TObject); var LTasks: array of ITask; LThreadCount: Integer; LIndex: Integer; begin case BuildButton.Tag of 0: begin FCancel := False; BuildButton.Tag := 1; BuildButton.Text := 'Cancel'; StatusLabel.Text := ''; LThreadCount := Trunc(CPUTB.Value); var StopWatch := TStopWatch.Create; StopWatch.Start; for LIndex := 1 to LThreadCount do begin LTasks := LTasks + [ProcessTask(LIndex)]; LTasks[High(LTasks)].Start; end; TTask.Run(procedure begin TTask.WaitForAll(LTasks); TThread.Synchronize(nil,procedure begin StopWatch.Stop; BuildEnd(StopWatch.ElapsedMilliseconds.ToString); end); end); end; 1: begin FCancel := True; end; end; end; procedure TMainForm.BuildProject(const AId: Integer; const APath: String); var LCurrentFile: String; LReturnCode: integer; SL: TStringList; OutBat: TStringList; LAdditionalPath: String; LPlatform: String; LName: String; LProject: TStringList; begin SL := TStringList.Create; SL.LoadFromFile(RSVArsComboEdit.Text); LPlatform := 'Win32'; LName := ExtractFileName(APath).Replace(ExtractFileExt(APath),''); if TwineSwitch.IsChecked=True then begin LProject := TStringList.Create; LProject.LoadFromFile(APath); if LProject.Text.IndexOf('<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />')=-1 then begin LProject.Text := LProject.Text.Replace('<Import Project="$(BDS)\Bin\CodeGear.Cpp.Targets" Condition="Exists(''$(BDS)\Bin\CodeGear.Cpp.Targets'')"/>','<Import Project="$(BDS)\Bin\CodeGear.Cpp.Targets" Condition="Exists(''$(BDS)\Bin\CodeGear.Cpp.Targets'')"/>'+'<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />'); LProject.SaveToFile(APath); end; LProject.Free; end else begin LProject := TStringList.Create; LProject.LoadFromFile(APath); if LProject.Text.IndexOf('<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />')>-1 then begin LProject.Text := LProject.Text.Replace('<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />', ''); LProject.SaveToFile(APath); end; LProject.Free; end; OutBat := TStringList.Create; try LAdditionalPath := ''; OutBat.Text := Trim(SL.Text); if APath.ToUpper.IndexOf('FLATBOX2D')>0 then LAdditionalPath := ';DCC_UnitSearchPath=$(DCC_UnitSearchPath)\FlatBox2d;$(DCC_UnitSearchPath)'; OutBat.Append(Format(ExecParamsEdit.Text, [APAth, PlatformComboEdit.Text, LAdditionalPath, CPUTB.Text]) + ' > ' + 'list'+AId.ToString + '.log'); if CleanSwitch.IsChecked then OutBat.Append(Format('msbuild "%s" /t:Clean /p:Platform=%s ', [APath, PlatformComboEdit.Text])); OutBat.SaveToFile(ExtractFilePath(ParamStr(0)) + 'list'+AId.ToString + '.bat'); LCurrentFile := 'cmd /c call '+ExtractFilePath(ParamStr(0))+'list'+AId.ToString+'.bat'; {$IFDEF MSWINDOWS} LReturnCode := ExeAndWait(LCurrentFile, SW_HIDE); {$ENDIF} OutBat.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'list'+AId.ToString + '.log'); if OutBat.Text.IndexOf('Build succeeded.')>0 then begin TThread.Synchronize(nil,procedure begin if ProjectsFDMemTable.Locate('FullPath',VarArrayOf([APath]),[]) then begin ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Status').AsString := STS_SUCCESS; ProjectsFDMemTable.Post; end; end); end else begin TThread.Synchronize(nil,procedure begin if ProjectsFDMemTable.Locate('FullPath',VarArrayOf([APath]),[]) then begin ProjectsFDMemTable.Edit; ProjectsFDMemTable.FieldByName('Status').AsString := STS_FAIL; ProjectsFDMemTable.Post; end; ErrorLogMemo.Lines.Append(OutBat.Text); end); end; TThread.Synchronize(nil,procedure begin Application.ProcessMessages; end); if TwineSwitch.IsChecked=True then begin LProject := TStringList.Create; LProject.LoadFromFile(APath); if LProject.Text.IndexOf('<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />')>-1 then begin LProject.Text := LProject.Text.Replace('<Import Project="C:\Program Files (x86)\JomiTech\TwineCompile\TCTargets104.targets" />', ''); LProject.SaveToFile(APath); end; LProject.Free; end; finally OutBat.Free; SL.Free; end; end; procedure TMainForm.ClearButtonClick(Sender: TObject); begin ProjectsFDMemTable.EmptyDataSet; end; {$IFDEF MSWINDOWS} function TMainForm.ExeAndWait(ExeNameAndParams: string; ncmdShow: Integer = SW_SHOWNORMAL): Integer; var StartupInfo: TStartupInfo; ProcessInformation: TProcessInformation; Res: Bool; lpExitCode: DWORD; begin with StartupInfo do //you can play with this structure begin cb := SizeOf(TStartupInfo); lpReserved := nil; lpDesktop := nil; lpTitle := nil; dwFlags := STARTF_USESHOWWINDOW; wShowWindow := ncmdShow; cbReserved2 := 0; lpReserved2 := nil; end; Res := CreateProcess(nil, PChar(ExeNameAndParams), nil, nil, True, CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation); while True do begin GetExitCodeProcess(ProcessInformation.hProcess, lpExitCode); if lpExitCode <> STILL_ACTIVE then Break; Application.ProcessMessages; end; Result := Integer(lpExitCode); end; {$ENDIF} procedure TMainForm.FormCreate(Sender: TObject); begin BuildButton.Hint := BuildButton.Text; CPUTB.Text := System.CPUCount.ToString; TLinkObservers.ControlChanged(CPUTB); end; end.
unit fMyLib; interface uses Variants, SysUtils, DBTables, Classes, Forms; const LuniScurte: array[1..12] of string[3] = ('Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct', 'Noi', 'Dec'); Luni: array[1..12] of string = ('Ianuarie', 'Februarie', 'Martie', 'Aprilie', 'Mai', 'Iunie', 'Iulie', 'August', 'Septembrie', 'Octombrie', 'Noiembrie', 'Decembrie'); type TKeyPressEvent = procedure(Sender: TObject; var Key: Char) of object; EErrorChecking = class(Exception); TMyForm = class(TForm) private FKeyPreview: boolean; FOnKeyPress: TKeyPressEvent; published property KeyPreview: Boolean read FKeyPreview write FKeyPreview default True; procedure KeyPress(var Key: Char); dynamic; end; //Error checking procedure RaiseEx(EType, EMessage: string); //Shortcuts function i2s(AValue: Variant): string; function s2i(AValue: string): Variant; function iif(Cond: boolean; Val1, Val2: Variant): Variant; function l(Value: string): integer; //MySQL function DoSQL(AQuery: TQuery; const SQL: string = ''): integer; function GetTableList(AQuery: TQuery; const dbName: string = ''): TStringList; procedure DoLogging(Event: string; const IsSQL: boolean = false); procedure ProcessException(E: Exception; const Data: string = ''); //File Utils function fileSize(FileName: string): integer; //DateUtils function UltimaZi(LunaAn:string; const An4Cifre: boolean = false; const DoarZiua: boolean = False):string; //StringUtils function InStr(SubString, Target: string; const CaseSensitive: boolean = false): boolean; //Returns true if substring exists within target function GetDigits(AValue: string): integer; //Supresses all the alphanumeric characters in the string except digits and returns that number implementation procedure TMyForm.KeyPress(var Key: Char); begin if Key = #27 then begin Self.Free; Exit; end; if Assigned(FOnKeyPress) then FOnKeyPress(Self, Key); end; procedure RaiseEx(EType, EMessage: string); var E: EErrorChecking; begin E := EErrorChecking.CreateFmt('ErrProcVer:%s - %s', [EType, EMessage]); raise E; end; function i2s(AValue: Variant): string; begin try Result := IntToStr(AValue); except end; end; function s2i(AValue: string): Variant; begin try Result := StrToInt(AValue); except end; end; function iif(Cond: boolean; Val1, Val2: Variant): Variant; begin if Cond then Result := Val1 else Result := Val2; end; function l(Value: string): integer; begin Result := Length(Value); end; function DoSQL(AQuery: TQuery; const SQL: string = ''): integer; var s: string; begin Result := -1; if AQuery = nil then Exit; if SQL = '' then s := AQuery.SQL.Text else s := SQL; try if Pos(Trim(Copy(s, 1, Pos(' ', s))), 'SELECT|SHOW|DESCRIBE') <> 0 then begin AQuery.SQL.Text := s; AQuery.Open; Result := AQuery.RowsAffected; end else begin AQuery.SQL.Text := s; AQuery.ExecSQL; Result := AQuery.RowsAffected; end; DoLogging(s); except on E: Exception do begin ProcessException(E, s); AQuery.Close; end; end; //if Result = -1 then Result := 0; end; function GetTableList(AQuery: TQuery; const dbName: string = ''): TStringList; var s: string; begin Result := TStringList.Create; if AQuery = nil then begin RaiseEx('GetTableList','AQuery is nil'); Exit end; s := ''; if dbName <> '' then s := ' IN ' + dbName; DoSQL(AQuery, 'SHOW TABLES' + s); while not AQuery.Eof do begin Result.Add(UpperCase(AQuery.Fields[0].AsString)); AQuery.Next; end; end; procedure DoLogging(Event: string; const IsSQL: boolean = false); var myfs: TFileStream; begin if not IsSQL then Exit; Event := Event + #10#13; if FileExists(ExtractFilePath(Application.ExeName) + '\log.txt') then myfs := TFileStream.Create(ExtractFilePath(Application.ExeName) + '\log.txt', fmOpenWrite) else myfs := TFileStream.Create(ExtractFilePath(Application.ExeName) + '\log.txt', fmCreate); myfs.Seek(myfs.Size, soFromBeginning); myfs.Write(Event[1], Length(Event)); myfs.Free; end; procedure ProcessException(E: Exception; const Data: string = ''); var s: string; begin s := E.Message + Data; DoLogging(s, True); end; function fileSize(FileName: string): integer; var myfs: TFileStream; begin Result := -1; if FileName = '' then Exit; myfs := TFileStream.Create(FileName, fmShareDenyNone); Result := myfs.Size; myfs.Free; end; function UltimaZi(LunaAn:string; const An4Cifre: boolean = false; const DoarZiua: boolean = False):string; var Luna: word; An: word; begin if Length(LunaAn) > 4 then raise Exception.CreateFmt('Formatul datei este invalid: ''%s''. Corect: LLAA.', [LunaAn]); Luna := StrToInt(Copy(LunaAn,1,2)); An := StrToInt(Copy(LunaAn,3,2)); if Luna = 2 then //if(( year % 4 == 0 && year % 100 != 0 ) || year % 400 = 0 ) if (((An mod 4) = 0) and ((An mod 100) <> 0)) or ((An mod 400) = 0) then Result := '29' else Result := '28' + LunaAn else if (Luna < 8) then if((Luna mod 2) = 0) then Result := '30' + LunaAn else Result := '31' + LunaAn else if((Luna mod 2) = 0) then Result := '31' + LunaAn else Result := '30' + LunaAn; if An4Cifre then Result := Copy(Result, 1, 4) + '20' + Copy(Result,5,2); if DoarZiua then Result := Copy(Result, 1, 2); end; function InStr(SubString, Target: string; const CaseSensitive: boolean = false): boolean; begin Result := False; if CaseSensitive then begin if Pos(SubString, Target) <> 0 then Result := True; end else begin if Pos(UpperCase(SubString), UpperCase(Target)) <> 0 then Result := True; end; end; function GetDigits(AValue: string): integer; var i: integer; le: integer; begin Result := 0; i := 1; le := l(AValue); while i <= le do begin if (byte(AValue[i]) >= 48) and (byte(AValue[i]) <= 57) then Result := Result * 10 + byte(AValue[i]) - 48; Inc(i); end; end; end.
{ ---------------------------------------------------------------------------- } { HeightMapGenerator MB3D } { Copyright (C) 2017 Andreas Maschke } { ---------------------------------------------------------------------------- } unit PNMReader; interface uses SysUtils, Classes, Windows; type TPGM16Reader = class private FBuffer: PWord; FWidth, FHeight: Integer; public constructor Create; destructor Destroy; override; procedure LoadFromFile( const Filename: String); property Width: Integer read FWidth; property Height: Integer read FHeight; property Buffer: PWord read FBuffer; end; implementation constructor TPGM16Reader.Create; begin inherited; FBuffer := nil; end; destructor TPGM16Reader.Destroy; begin if FBuffer <> nil then FreeMem( FBuffer ); end; procedure TPGM16Reader.LoadFromFile( const Filename: String); var Reader: TStreamReader; Line: String; MaxValue: Integer; I, J: Integer; Lst: TStringList; CurrPGMBuffer: PWord; begin Reader := TStreamReader.Create( Filename, TEncoding.ANSI); try Line := Trim( Reader.ReadLine ); if Line <> 'P2' then raise Exception.Create('Unexpected Header <'+Line+'>'); Line := Trim( Reader.ReadLine ); if ( Length(Line) > 0 ) and ( Line[1] = '#' ) then // ignore comment Line := Trim( Reader.ReadLine ); Lst := TStringList.Create; try I := Pos(' ', Line ); FWidth := StrToInt( Copy( Line, 1, I - 1 ) ); FHeight := StrToInt( Copy( Line, I + 1, Length(Line) - I ) ); if ( FWidth < 1 ) or ( FHeight < 1 ) then raise Exception.Create('Invalid Size <'+Line+'>'); MaxValue := StrToInt( Trim( Reader.ReadLine ) ); if MaxValue < 1 then raise Exception.Create('Invalid Depth <'+IntToStr(MaxValue)+'>'); GetMem( FBuffer, FWidth * FHeight * SizeOf( Word ) ); Lst.Delimiter := ' '; CurrPGMBuffer := FBuffer; for I:=0 to FHeight - 1 do begin Lst.DelimitedText := Trim( Reader.ReadLine ); if Lst.Count <> FWidth then raise Exception.Create('Invalid Line <'+IntToStr(I)+'>: Found <'+IntToStr(Lst.Count)+' items, expected <'+IntToStr(FWidth)); for J := 0 to Width - 1 do begin CurrPGMBuffer^ := Word( StrToInt( Lst[J] ) ); CurrPGMBuffer := PWord( Longint( CurrPGMBuffer ) + SizeOf( Word ) ); end; end; finally Lst.Free; end; finally Reader.Free; end; end; end.
{ Pascal function that tests if a number is a palindrome } { A palindrome is a number that is equal to its reverse (if you spell it backwards it remains the same number). The function that that does the testing is is_palindrome(). This function uses the auxiliary function reverse_digits(). } function reverse_digits(original_number:longint):longint; var aux, reversed_number: longint; begin reversed_number := 0; while (original_number <> 0) do begin reversed_number := reversed_number * 10 + original_number mod 10; original_number := original_number div 10; end; reverse_digits := reversed_number; end; function is_palindrome(number:longint):boolean; begin if (number = reverse_digits(number)) then is_palindrome := true else is_palindrome := false; end; begin writeln(is_palindrome(123)); writeln(is_palindrome(131)); writeln(is_palindrome(0)); end.
{*******************************************************} { } { Delphi FireMonkey Platform } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit FMX.Platform.Mac; interface uses FMX.Types, FMX.Platform, Macapi.ObjectiveC; function ActualPlatformClass: TPlatformClass; function FmxHandleToObjC(FmxHandle: TFmxHandle): IObjectiveC; implementation {$R *.res} uses System.Classes, System.SysUtils, System.Types, System.UITypes, System.TypInfo, System.SyncObjs, FMX.Forms, FMX.Dialogs, FMX.Menus, Macapi.CocoaTypes, Macapi.Foundation, Macapi.AppKit, Macapi.ObjCRuntime, Macapi.CoreFoundation, System.RegularExpressions, System.StrUtils, System.Variants, FMX.Consts, System.Generics.Collections, FMX.Context.Mac; type {$M+} TApplicationDelegate = class(TOCLocal, NSApplicationDelegate) public procedure applicationWillTerminate(Notification: Pointer); cdecl; procedure applicationDidFinishLaunching(Notification: Pointer); cdecl; end; { TPlatformCocoa } TPlatformCocoa = class(TPlatform) private NSApp: NSApplication; FAppDelegate: NSApplicationDelegate; FRunLoopObserver: CFRunLoopObserverRef; FAppKitMod: HMODULE; FHandleCounter: TFmxHandle; FObjectiveCMap: TDictionary<TFmxHandle, IObjectiveC>; FModalStack: TStack<TCommonCustomForm>; FRestartModal: Boolean; function NewFmxHandle: TFmxHandle; procedure ValidateHandle(FmxHandle: TFmxHandle); function HandleToObjC(FmxHandle: TFmxHandle): IObjectiveC; overload; function HandleToObjC(FmxHandle: TFmxHandle; const IID: TGUID; out Intf): Boolean; overload; function AllocHandle(const Objc: IObjectiveC): TFmxHandle; procedure DeleteHandle(FmxHandle: TFmxHandle); procedure CreateChildMenuItems(AChildMenu: IItemsContainer; AParentMenu: NSMenu); procedure CreateApplicationMenu; procedure DoReleaseWindow(AForm: TCommonCustomForm); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; { App } procedure Run; override; procedure Terminate; override; function HandleMessage: Boolean; override; procedure WaitMessage; override; { System Metrics } function GetDefaultFontFamilyName: String; override; { Timer } function CreateTimer(Interval: Integer; TimerFunc: TTimerProc): TFmxHandle; override; function DestroyTimer(Timer: TFmxHandle): Boolean; override; function GetTick: single; override; { Window } function FindForm(AHandle: TFmxHandle): TCommonCustomForm; override; function CreateWindow(AForm: TCommonCustomForm): TFmxHandle; override; procedure DestroyWindow(AForm: TCommonCustomForm); override; procedure ReleaseWindow(AForm: TCommonCustomForm); override; procedure ShowWindow(AForm: TCommonCustomForm); override; procedure HideWindow(AForm: TCommonCustomForm); override; function ShowWindowModal(AForm: TCommonCustomForm): TModalResult; override; procedure InvalidateWindowRect(AForm: TCommonCustomForm; R: TRectF); override; procedure SetWindowRect(AForm: TCommonCustomForm; ARect: TRectF); override; function GetWindowRect(AForm: TCommonCustomForm): TRectF; override; function GetClientSize(AForm: TCommonCustomForm): TPointF; override; procedure SetClientSize(AForm: TCommonCustomForm; const ASize: TPointF); override; procedure SetWindowCaption(AForm: TCommonCustomForm; const ACaption: string); override; procedure SetCapture(AForm: TCommonCustomForm); override; procedure SetWindowState(AForm: TCommonCustomForm; const AState: TWindowState); override; procedure ReleaseCapture(AForm: TCommonCustomForm); override; function ClientToScreen(AForm: TCommonCustomForm; const Point: TPointF): TPointF; override; function ScreenToClient(AForm: TCommonCustomForm; const Point: TPointF): TPointF; override; { Menus } procedure StartMenuLoop(const AView: IMenuView); override; function ShortCutToText(ShortCut: TShortCut): string; override; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); override; function TextToShortCut(Text: String): integer; override; procedure CreateOSMenu(AForm: TCommonCustomForm; const AMenu: IItemsContainer); override; procedure UpdateMenuItem(const AItem: TMenuItem); override; { Drag and Drop } procedure BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap); override; { Clipboard } procedure SetClipboard(Value: Variant); override; function GetClipboard: Variant; override; { Cursor } procedure SetCursor(AForm: TCommonCustomForm; const ACursor: TCursor); override; { Mouse } function GetMousePos: TPointF; override; { Screen } function GetScreenSize: TPointF; override; { International } function GetCurrentLangID: string; override; function GetLocaleFirstDayOfWeek: string; override; { Dialogs } function DialogOpenFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; override; function DialogPrint(var ACollate, APrintToFile: Boolean; var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange; AOptions: TPrintDialogOptions): Boolean; override; function PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; override; function DialogPageSetup(var AMargin, AMinMargin :TRect; var APaperSize: TPointF; var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; override; function DialogSaveFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; override; function DialogPrinterSetup: Boolean; override; { Text Service } function GetTextServiceClass: TTextServiceClass; override; end; {$M+} TFMXWindow = class; TTextServiceCocoa = class; TFMXViewBase = class(TOCLocal, NSTextInputClient) private FOwner: TFMXWindow; FShift: TShiftState; FMarkedRange: NSRange; FBackingStore: NSMutableAttributedString;//NSTextStorage; FSelectedRange: NSRange; protected function GetNativeView: NSView; public constructor Create(AOwner: TFMXWindow); destructor Destroy; override; function acceptsFirstResponder: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; procedure rightMouseDown(theEvent: NSEvent); cdecl; procedure rightMouseUp(theEvent: NSEvent); cdecl; procedure drawRect(dirtyRect: NSRect); cdecl; // function menuForEvent(event: Pointer {NSEvent}): Pointer; {NSMenu} // May need to do something special to delegate this method. procedure keyDown(event: NSEvent); cdecl; procedure keyUp(event: NSEvent); cdecl; procedure mouseUp(event: NSEvent); cdecl; procedure mouseDown(event: NSEvent); cdecl; procedure mouseDragged(event: NSEvent); cdecl; procedure mouseMoved(event: NSEvent); cdecl; procedure scrollWheel(event: NSEvent); cdecl; { NSTextInputClient } procedure insertText(text: Pointer {NSString}; replacementRange: NSRange); cdecl; procedure doCommandBySelector(selector: SEL); cdecl; procedure setMarkedText(text: Pointer {NSString}; selectedRange: NSRange; replacementRange: NSRange); cdecl; procedure unMarkText; cdecl; function selectedRange: NSRange; cdecl; function markedRange: NSRange; cdecl; function hasMarkedText: Boolean; cdecl; function attributedSubstringForProposedRange(aRange: NSRange; actualRange: PNSRange): NSAttributedString; cdecl; function validAttributesForMarkedText: Pointer {NSArray}; cdecl; function firstRectForCharacterRange(aRange: NSRange; actualRange: PNSRange): NSRect; cdecl; function characterIndexForPoint(aPoint: NSPoint): NSUInteger; cdecl; function attributedString: NSAttributedString; cdecl; function fractionOfDistanceThroughGlyphForPoint(aPoint: NSPoint): CGFloat; cdecl; function baselineDeltaForCharacterAtIndex(anIndex: NSUInteger): CGFloat; cdecl; function windowLevel: NSInteger; cdecl; function drawsVerticallyForCharacterAtIndex(charIndex: NSUInteger): Boolean; cdecl; { Text Service } function FocusedTextService: TTextServiceCocoa; procedure UpdateTextServiceControl; { } property NativeView: NSView read GetNativeView; property Owner: TFMXWindow read FOwner; end; FMXView = interface(NSView) ['{56304E8C-08A2-4386-B116-D4E364FDC2AD}'] function acceptsFirstResponder: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; procedure rightMouseDown(theEvent: NSEvent); cdecl; procedure rightMouseUp(theEvent: NSEvent); cdecl; procedure drawRect(dirtyRect: NSRect); cdecl; procedure keyDown(event: NSEvent); cdecl; procedure keyUp(event: NSEvent); cdecl; procedure mouseUp(event: NSEvent); cdecl; procedure mouseDown(event: NSEvent); cdecl; procedure mouseDragged(event: NSEvent); cdecl; procedure mouseMoved(event: NSEvent); cdecl; procedure scrollWheel(event: NSEvent); cdecl; end; TFMXView = class(TFMXViewBase, NSTextInputClient) public constructor Create(AOwner: TFMXWindow; AFRameRect: NSRect); function GetObjectiveCClass: PTypeInfo; override; end; FMXView3D = interface(NSOpenGLView) ['{FC9E6699-53C6-4117-BAF0-A7BD455BAF75}'] function acceptsFirstResponder: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; procedure rightMouseDown(theEvent: NSEvent); cdecl; procedure rightMouseUp(theEvent: NSEvent); cdecl; procedure drawRect(dirtyRect: NSRect); cdecl; procedure keyDown(event: NSEvent); cdecl; procedure keyUp(event: NSEvent); cdecl; procedure mouseUp(event: NSEvent); cdecl; procedure mouseDown(event: NSEvent); cdecl; procedure mouseDragged(event: NSEvent); cdecl; procedure mouseMoved(event: NSEvent); cdecl; procedure scrollWheel(event: NSEvent); cdecl; end; TFMXView3D = class(TFMXViewBase, NSTextInputClient) public constructor Create(AOwner: TFMXWindow; AFrameRect: NSRect); destructor Destroy; override; function GetObjectiveCClass: PTypeInfo; override; end; FMXWindow = interface(NSWindow) ['{A4C4B329-38C4-401F-8937-1C380801B1C8}'] function draggingEntered(Sender: Pointer): NSDragOperation; cdecl; procedure draggingExited(Sender: Pointer {id}); cdecl; function draggingUpdated(Sender: Pointer): NSDragOperation; cdecl; function performDragOperation(Sender: Pointer): Boolean; cdecl; function canBecomeKeyWindow: Boolean; cdecl; function canBecomeMainWindow: Boolean; cdecl; function acceptsFirstResponder: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; function performKeyEquivalent(event: NSEvent): Boolean; cdecl; end; FMXPanelWindow = interface(NSPanel) ['{52EB2081-6E73-4D3E-8EF9-8008275A7D6B}'] function draggingEntered(Sender: Pointer): NSDragOperation; cdecl; procedure draggingExited(Sender: Pointer {id}); cdecl; function draggingUpdated(Sender: Pointer): NSDragOperation; cdecl; function performDragOperation(Sender: Pointer): Boolean; cdecl; function canBecomeKeyWindow: Boolean; cdecl; function canBecomeMainWindow: Boolean; cdecl; function acceptsFirstResponder: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; end; TFMXWindow = class(TOCLocal) //(NSWindow) private FViewObj: TFMXViewBase; FDelegate: NSWindowDelegate; FDelayRelease: Boolean; protected function GetView: NSView; public NeedUpdateShadow: Boolean; Wnd: TCommonCustomForm; LastEvent: NSEvent; // for DragNDrop function GetObjectiveCClass: PTypeInfo; override; destructor Destroy; override; function windowShouldClose(Sender: Pointer {id}): Boolean; cdecl; procedure windowWillClose(notification: NSNotification); cdecl; procedure windowDidBecomeKey(notification: NSNotification); cdecl; procedure windowDidResignKey(notification: NSNotification); cdecl; procedure windowDidResize(notification: NSNotification); cdecl; procedure windowDidMove(notification: NSNotification); cdecl; function draggingEntered(Sender: Pointer {NSDraggingInfo}): NSDragOperation; cdecl; procedure draggingExited(Sender: Pointer {NSDraggingInfo} {id}); cdecl; function draggingUpdated(Sender: Pointer {NSDraggingInfo}): NSDragOperation; cdecl; function performDragOperation(Sender: Pointer {NSDraggingInfo}): Boolean; cdecl; function acceptsFirstResponder: Boolean; cdecl; function canBecomeKeyWindow: Boolean; cdecl; function canBecomeMainWindow: Boolean; cdecl; function becomeFirstResponder: Boolean; cdecl; function resignFirstResponder: Boolean; cdecl; function performKeyEquivalent(event: NSEvent): Boolean; cdecl; property View: NSView read GetView; end; PFMXWindow = ^TFMXWindow; TFMXPanelWindow = class(TFMXWindow) public function GetObjectiveCClass: PTypeInfo; override; function canBecomeMainWindow: Boolean; cdecl; end; { TTextServiceCocoa } TTextServiceCocoa = class(TTextService) private FCaretPostion: TPoint; FText : string; FMarkedText : string; FImeMode: TImeMode; protected function GetText: string; override; procedure SetText(const Value: string); override; function GetCaretPostion: TPoint; override; procedure SetCaretPostion(const Value: TPoint); override; public procedure InternalSetMarkedText( const AMarkedText: string ); override; function InternalGetMarkedText: string; override; function CombinedText: string; override; function TargetClausePosition: TPoint; override; procedure EnterControl(const FormHandle: TFmxHandle); override; procedure ExitControl(const FormHandle: TFmxHandle); override; procedure DrawSingleLine( Canvas: TCanvas; const ARect: TRectF; const FirstVisibleChar: integer; const Font: TFont; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.taCenter ); override; procedure DrawSingleLine2( Canvas: TCanvas; const S: string; const ARect: TRectF; const Font: TFont; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.taCenter ); override; function HasMarkedText: boolean; override; function GetImeMode: TImeMode; override; procedure SetImeMode(const Value: TImeMode); override; { Cocoa } private FMarkedRange: NSRange; FSelectedRange: NSRange; public constructor Create(const Owner: TControl; SupportMultiLine: Boolean); override; destructor Destroy; override; // function InternalGetMarkedRect: TRectF; virtual; procedure SetMarkedRange(const Value: NSRange); procedure SetSselectedRange(const Value: NSRange); end; //procedure ShortCutToKey(ShortCut: TShortCut; var Key: Char; var ModifierMask: NSUInteger); forward; (* implementation {$R *.res} uses {FMX.Canvas.Mac, }System.RegularExpressions, System.StrUtils, System.Variants, FMX.Consts; *) function ActualPlatformClass: TPlatformClass; begin Result := TPlatformCocoa; end; procedure ShortCutToMACKey(ShortCut: TShortCut; var Key: Char; var ModifierMask: NSUInteger); var K: byte; begin K := Lo(ShortCut); ModifierMask := 0; case K of Ord('A')..Ord('Z') : Key := Char(K+ Ord('a') - Ord('A')); $08 : Key := Char(NSBackspaceCharacter); $09 : Key := Char(NSTabCharacter); $0d : Key := Char(NSEnterCharacter); $21 : Key := Char(NSPageUpFunctionKey); $22 : Key := Char(NSPageDownFunctionKey); $23 : Key := Char(NSEndFunctionKey); $24 : Key := Char(NSHomeFunctionKey); $25 : Key := Char(NSLeftArrowFunctionKey); $26 : Key := Char(NSUpArrowFunctionKey); $27 : Key := Char(NSRightArrowFunctionKey); $28 : Key := Char(NSDownArrowFunctionKey); $2e : Key := Char(NSDeleteCharacter); $70..$87 : Key := Char(NSF1FunctionKey+(K-$70)); else Key := Chr(K); end; if ShortCut and scCommand <> 0 then ModifierMask := ModifierMask or NSCommandKeyMask; if ShortCut and scShift <> 0 then ModifierMask := ModifierMask or NSShiftKeyMask; if ShortCut and scCtrl <> 0 then ModifierMask := ModifierMask or NSControlKeyMask; if ShortCut and scAlt <> 0 then ModifierMask := ModifierMask or NSAlternateKeyMask; end; var NSFMXPBoardtype: NSString; // pool: NSAutoreleasePool; // appDel: ApplicationDelegate; // NSVGScenePBoardtype: NSString; { TApplicationDelegate } procedure TApplicationDelegate.applicationWillTerminate(Notification: Pointer); begin Application.Free; Application := nil; end; procedure TApplicationDelegate.applicationDidFinishLaunching(Notification: Pointer); begin end; { TPlatformCocoa } constructor TPlatformCocoa.Create(AOwner: TComponent); var AutoReleasePool: NSAutoreleasePool; begin inherited; FAppKitMod := LoadLibrary('/System/Library/Frameworks/AppKit.framework/AppKit'); AutoReleasePool := TNSAutoreleasePool.Create; try AutoReleasePool.init; NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); FAppDelegate := TApplicationDelegate.Create; NSApp.setDelegate(FAppDelegate); Application := TApplication.Create(nil); FObjectiveCMap := TDictionary<TFmxHandle, IObjectiveC>.Create; finally AutoReleasePool.release; end; NSFMXPBoardtype := NSSTR('NSFMXPBoardtype' + IntToStr(Integer(Pointer(Application)))); SelectOpenGLContext; end; destructor TPlatformCocoa.Destroy; begin if FModalStack <> nil then FModalStack.Free; FreeLibrary(FAppKitMod); FreeAndNil(Application); FObjectiveCMap.Free; inherited; end; { App =========================================================================} procedure RunLoopObserverCallback(observer: CFRunLoopObserverRef; activity: CFRunLoopActivity; info: Pointer); cdecl; var Done: Boolean; begin Done := False; if (TThread.CurrentThread.ThreadID = MainThreadID) then CheckSynchronize; Application.DoIdle(Done); end; procedure TPlatformCocoa.Run; begin Application.RealCreateForms; CreateApplicationMenu; FRunLoopObserver := CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, True, 0, RunLoopObserverCallback, nil); CFRunLoopAddObserver(CFRunLoopGetCurrent, FRunLoopObserver, kCFRunLoopCommonModes); NSApp.Run; end; procedure TPlatformCocoa.Terminate; begin NSApp.terminate(nil); end; function TPlatformCocoa.HandleToObjC(FmxHandle: TFmxHandle): IObjectiveC; begin TMonitor.Enter(FObjectiveCMap); try ValidateHandle(FmxHandle); if FObjectiveCMap.ContainsKey(FmxHandle) then Result := FObjectiveCMap[FmxHandle] else Result := nil; finally TMonitor.Exit(FObjectiveCMap); end; end; function TPlatformCocoa.HandleMessage: Boolean; begin WaitMessage; Result := false; end; procedure TPlatformCocoa.WaitMessage; var TimeoutDate: NSDate; begin TimeoutDate := TNSDate.Wrap(TNSDate.OCClass.dateWithTimeIntervalSinceNow(0.1)); NSApp.nextEventMatchingMask(NSAnyEventMask, TimeoutDate, NSDefaultRunLoopMode, False); end; { Timer =======================================================================} type CocoaTimer = interface(NSObject) ['{337887FF-BA77-4703-BE0E-34DC1CB26276}'] procedure timerEvent; cdecl; procedure release; cdecl; end; TCocoaTimer = class(TOCLocal) private FFunc : TTimerProc; public function GetObjectiveCClass: PTypeInfo; override; procedure timerEvent; cdecl; procedure SetTimerFunc(AFunc: TTimerProc); procedure release; cdecl; end; function TCocoaTimer.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(CocoaTimer); end; procedure TCocoaTimer.timerEvent; begin if Assigned(@FFunc) then FFunc; end; procedure TCocoaTimer.release; var RC: Integer; begin RC := NSObject(Super).retainCount; NSObject(Super).release; if RC = 1 then Destroy; end; procedure TCocoaTimer.SetTimerFunc(AFunc: TTimerProc); begin FFunc := AFunc; end; function TPlatformCocoa.CreateTimer(Interval: Integer; TimerFunc: TTimerProc): TFmxHandle; var Timer: NSTimer; User: TCocoaTimer; LInterval: NSTimeInterval; begin User := TCocoaTimer.Create; try User.SetTimerFunc(TimerFunc); LInterval := Interval/1000; Timer := TNSTimer.Wrap(TNSTimer.OCClass.scheduledTimerWithTimeInterval(LInterval, User.GetObjectID, sel_getUid('timerEvent'), User.GetObjectID, True)); Result := AllocHandle(Timer); finally {user is retained (twice, because it's target), by the timer and } {released (twice) on timer invalidation} NSObject(User.Super).release; end; end; function TPlatformCocoa.DestroyTimer(Timer: TFmxHandle): Boolean; var CocoaTimer: NSTimer; begin Result := False; if HandleToObjC(Timer, NSTimer, CocoaTimer) then begin Result := True; CocoaTimer.invalidate; DeleteHandle(Timer); end; end; function TPlatformCocoa.GetTick: single; var H, M, S, MS: word; begin DecodeTime(time, H, M, S, MS); Result := ((((H * 60 * 60) + (M * 60) + S) * 1000) + MS) / 1000; end; { Window ======================================================================} const kCGBaseWindowLevelKey = 0; kCGMinimumWindowLevelKey = 1; kCGDesktopWindowLevelKey = 2; kCGBackstopMenuLevelKey = 3; kCGNormalWindowLevelKey = 4; kCGFloatingWindowLevelKey = 5; kCGTornOffMenuWindowLevelKey = 6; kCGDockWindowLevelKey = 7; kCGMainMenuWindowLevelKey = 8; kCGStatusWindowLevelKey = 9; kCGModalPanelWindowLevelKey = 10; kCGPopUpMenuWindowLevelKey = 11; kCGDraggingWindowLevelKey = 12; kCGScreenSaverWindowLevelKey = 13; kCGMaximumWindowLevelKey = 14; kCGOverlayWindowLevelKey = 15; kCGHelpWindowLevelKey = 16; kCGUtilityWindowLevelKey = 17; kCGDesktopIconWindowLevelKey = 18; kCGCursorWindowLevelKey = 19; kCGAssistiveTechHighWindowLevelKey = 20; kCGNumberOfWindowLevelKeys = 21; { Must be last. } { TFMXView } function TFMXView.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(FMXView); end; constructor TFMXView.Create(AOwner: TFMXWindow; AFrameRect: NSRect); var V: Pointer; begin inherited Create(AOwner); V := NSView(Super).initWithFrame(AFrameRect); if GetObjectID <> V then UpdateObjectID(V); end; { Text Service } constructor TTextServiceCocoa.Create(const Owner: TControl; SupportMultiLine: Boolean); begin inherited; end; destructor TTextServiceCocoa.Destroy; begin inherited; end; function TTextServiceCocoa.GetText: string; begin Result := FText; end; procedure TTextServiceCocoa.SetText(const Value: string); begin FText := Value; end; function TTextServiceCocoa.GetCaretPostion: TPoint; begin Result := FCaretPostion; end; procedure TTextServiceCocoa.SetCaretPostion(const Value: TPoint); begin FCaretPostion := Value; end; procedure TTextServiceCocoa.InternalSetMarkedText( const AMarkedText: string ); begin FMarkedText := AMarkedText; end; function TTextServiceCocoa.InternalGetMarkedText: string; begin Result := FMarkedText; end; function TTextServiceCocoa.CombinedText: string; begin if FMarkedText <> '' then Result := Copy(FText, 1, FCaretPostion.X) + FMarkedText + Copy(FText, FCaretPostion.X + 1, MaxInt) else Result := FText; end; function TTextServiceCocoa.TargetClausePosition: TPoint; begin Result := CaretPosition; end; procedure TTextServiceCocoa.EnterControl(const FormHandle: TFmxHandle); begin end; procedure TTextServiceCocoa.ExitControl(const FormHandle: TFmxHandle); begin end; procedure TTextServiceCocoa.DrawSingleLine( Canvas: TCanvas; const ARect: TRectF; const FirstVisibleChar: integer; const Font: TFont; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.taCenter ); function _TextWidth(const Str: string): Single; var R: TRectF; begin R := TRectF.Create(0, 0, 0, 0); GetMeasureBitmap.Canvas.Font.Assign(Font); GetMeasureBitmap.Canvas.MeasureText(R, Str, False, Flags, TTextAlign.taLeading, TTextAlign.taCenter); Result := RectWidth(R); end; var i: Integer; R: TRectF; State: TCanvasSaveState; BeforeCaret, AfterCaret: string; WholeTextWidth: Single; EditRectWidth: Single; MarkedLineBottom: Single; S: String; begin S := Copy(Text, 1, CaretPosition.X) + FMarkedText + Copy(Text, CaretPosition.X+1, MaxInt); Canvas.FillText(ARect, Copy(S, FirstVisibleChar, Length(S) - FirstVisibleChar + 1), False, AOpacity, Flags, ATextAlign, AVTextAlign); Canvas.Stroke.Assign(Canvas.Fill); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdSolid; MarkedLineBottom := ARect.Top + (ARect.Height / 2) + Font.Size / 2; Canvas.DrawLine(PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X)) - _TextWidth(Copy(S, 1, FirstVisibleChar-1)), MarkedLineBottom), PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FMarkedRange.length))) - _TextWidth(Copy(S, 1, FirstVisibleChar-1)), MarkedLineBottom), AOpacity); Canvas.StrokeThickness := 3; MarkedLineBottom := ARect.Top + (ARect.Height / 2) + Font.Size / 2; Canvas.DrawLine(PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FSelectedRange.location))) - _TextWidth(Copy(S, 1, FirstVisibleChar-1)), MarkedLineBottom), PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FSelectedRange.location) + Integer(FSelectedRange.length))) - _TextWidth(Copy(S, 1, FirstVisibleChar-1)), MarkedLineBottom), AOpacity); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdSolid; end; procedure TTextServiceCocoa.DrawSingleLine2( Canvas: TCanvas; const S: string; const ARect: TRectF; const Font: TFont; const AOpacity: Single; const Flags: TFillTextFlags; const ATextAlign: TTextAlign; const AVTextAlign: TTextAlign = TTextAlign.taCenter ); function _TextWidth(const Str: string): Single; var R: TRectF; begin R := TRectF.Create(0, 0, 0, 0); GetMeasureBitmap.Canvas.Font.Assign(Font); GetMeasureBitmap.Canvas.MeasureText(R, Str, False, Flags, TTextAlign.taLeading, TTextAlign.taCenter); Result := RectWidth(R); end; var i: Integer; R: TRectF; State: TCanvasSaveState; BeforeCaret, AfterCaret: string; WholeTextWidth: Single; EditRectWidth: Single; MarkedLineBottom: Single; begin {$IFDEF __LOG} writeln('*TTextServiceCocoa.DrawSingleLine2- enter'); writeln(' S:[', S, ']'); writeln(' FMarkedText:[', FMarkedText, ']'); writeln('FSelectedRange: loc:', FSelectedRange.location, ' len:', FSelectedRange.length); writeln(' FMarkedRange: loc:', FMarkedRange.location, ' len:', FMarkedRange.length); {$ENDIF} Canvas.FillText(ARect, S, False, AOpacity, Flags, ATextAlign, AVTextAlign); Canvas.Stroke.Assign(Canvas.Fill); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdSolid; MarkedLineBottom := ARect.Top + (ARect.Height / 2) + Font.Size / 2; Canvas.DrawLine(PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X)), MarkedLineBottom), PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FMarkedRange.length))), MarkedLineBottom), AOpacity); Canvas.StrokeThickness := 3; MarkedLineBottom := ARect.Top + (ARect.Height / 2) + Font.Size / 2; Canvas.DrawLine(PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FSelectedRange.location))), MarkedLineBottom), PointF(ARect.Left + _TextWidth(Copy(S, 1, CaretPosition.X + Integer(FSelectedRange.location) + Integer(FSelectedRange.length))), MarkedLineBottom), AOpacity); Canvas.StrokeThickness := 1; Canvas.StrokeDash := TStrokeDash.sdSolid; {$IFDEF __LOG} writeln('*TTextServiceCocoa.DrawSingleLine2- exit'); {$ENDIF} end; function TTextServiceCocoa.HasMarkedText: boolean; begin Result := FMarkedText <> ''; end; function TTextServiceCocoa.GetImeMode: TImeMode; begin Result := FImeMode; end; procedure TTextServiceCocoa.SetImeMode(const Value: TImeMode); begin FImeMode := Value; end; procedure TTextServiceCocoa.SetMarkedRange(const Value: NSRange); begin FMarkedRange := Value; end; procedure TTextServiceCocoa.SetSselectedRange(const Value: NSRange); begin FSelectedRange := Value; end; function TPlatformCocoa.GetTextServiceClass: TTextServiceClass; begin Result := TTextServiceCocoa; end; { TFMXViewBase } constructor TFMXViewBase.Create(AOwner: TFMXWindow); //var // LayoutMgr: NSLayoutManager; // TextContainer: NSTextContainer; // R: TRectF; // IMEContainerSize: NSSize; // ParaStyle: NSMutableParagraphStyle; // DefaultAttribs: NSMutableDictionary; begin inherited Create; FOwner := AOwner; FBackingStore := TNSMutableAttributedString.Create; FBackingStore := TNSMutableAttributedString.Wrap(FBackingStore.initWithString(NSSTR(''))); FMarkedRange.location := NSNotFound; FMarkedRange.length := 0; FSelectedRange.location := 0; FSelectedRange.length := 0; UpdateTextServiceControl; end; destructor TFMXViewBase.Destroy; begin FBackingStore.release; FOwner := nil; inherited; end; procedure TFMXViewBase.drawRect(dirtyRect: NSRect); var VR: TRectF; nctx: NSGraphicsContext; boundRect: NSRect; begin boundRect := NSView(Super).bounds; VR := RectF(dirtyRect.origin.x, boundRect.size.height - dirtyRect.origin.y - dirtyRect.size.height, dirtyRect.origin.x + dirtyRect.size.width, boundRect.size.height - dirtyRect.origin.y); if (FOwner <> nil) and (FOwner.Wnd <> nil) and not (FOwner.Wnd is TCustomForm3D) then begin nctx := TNSGraphicsContext.Wrap(TNSGraphicsContext.OCClass.currentContext); FOwner.Wnd.ContextHandle := THandle(nctx.graphicsPort); FOwner.Wnd.PaintRects([VR]); FOwner.Wnd.ContextHandle := 0; if FOwner.NeedUpdateShadow and NSWindow(FOwner.Super).isVisible then begin NSWindow(FOwner.Super).invalidateShadow; FOwner.NeedUpdateShadow := False; end; end; if (FOwner <> nil) and (FOwner.Wnd is TCustomForm3D) then begin FOwner.Wnd.PaintRects([VR]); if FOwner.NeedUpdateShadow and FOwner.Wnd.Visible { isVisible} then begin NSWindow(FOwner.Super).invalidateShadow; FOwner.NeedUpdateShadow := False; end; end; end; function TFMXViewBase.GetNativeView: NSView; begin Result := NSView(Super); end; function ShiftStateFromModFlags(M: NSUInteger): TShiftState; begin Result := []; if M and NSShiftKeyMask = NSShiftKeyMask then begin Include(Result, ssShift); M := M and not NSShiftKeyMask; end; if M and NSControlKeyMask = NSControlKeyMask then begin Include(Result, ssCtrl); M := M and not NSControlKeyMask; end; if M and NSAlternateKeyMask = NSAlternateKeyMask then begin Include(Result, ssAlt); M := M and not NSAlternateKeyMask; end; if M and NSCommandKeyMask = NSCommandKeyMask then begin Include(Result, ssCommand); end; end; procedure TFMXViewBase.rightMouseDown(theEvent: NSEvent); var mp: NSPoint; SS: TShiftState; begin mp := theEvent.locationInWindow; mp.y := NativeView.bounds.size.height - mp.y; SS := [ssRight] + ShiftStateFromModFlags(theEvent.modifierFlags); try FOwner.Wnd.mouseDown(TMouseButton.mbRight, SS, mp.x, mp.y); except Application.HandleException(Self); end; NativeView.rightMouseDown(theEvent); end; procedure TFMXViewBase.rightMouseUp(theEvent: NSEvent); var mp: NSPoint; SS: TShiftState; begin mp := theEvent.locationInWindow; mp.y := NativeView.bounds.size.height - mp.y; SS := [ssRight] + ShiftStateFromModFlags(theEvent.modifierFlags); try FOwner.Wnd.mouseUp(TMouseButton.mbRight, SS, mp.x, mp.y); except Application.HandleException(Self); end; NativeView.rightMouseUp(theEvent); end; procedure TFMXViewBase.mouseUp(event: NSEvent); var mp: NSPoint; SS: TShiftState; begin FOwner.LastEvent := nil; mp := event.locationInWindow; mp.y := TNSView.Wrap(event.window.contentView).bounds.size.height - mp.y; SS := [ssLeft] + ShiftStateFromModFlags(event.modifierFlags); try FOwner.Wnd.MouseUp(TMouseButton.mbLeft, SS, mp.x, mp.y); except Application.HandleException(Self); end; end; procedure TFMXViewBase.mouseDown(event: NSEvent); var mp: NSPoint; SS: TShiftState; begin mp := event.locationInWindow; mp.y := TNSView.Wrap(event.window.contentView).bounds.size.height - mp.y; FOwner.LastEvent:= event; SS := [ssLeft] + ShiftStateFromModFlags(event.modifierFlags); if event.clickCount = 2 then Include(SS, ssDouble); try FOwner.Wnd.MouseDown(TMouseButton.mbLeft, SS, mp.x, mp.y); except Application.HandleException(Self); end; end; procedure TFMXViewBase.mouseDragged(event: NSEvent); var mp: NSPoint; begin if event.window <> nil then begin mp := event.locationInWindow; mp.y := TNSView.Wrap(event.window.contentView).bounds.size.height - mp.y; try FOwner.LastEvent := event; FOwner.Wnd.MouseMove([ssLeft], mp.x, mp.y); FOwner.LastEvent := nil; except Application.HandleException(Self); end; end; end; procedure TFMXViewBase.mouseMoved(event: NSEvent); var mp: NSPoint; begin mp := event.locationInWindow; mp.y := TNSView.Wrap(event.window.contentView).bounds.size.height - mp.y; try FOwner.Wnd.MouseMove([], mp.x, mp.y); except Application.HandleException(Self); end; end; procedure TFMXViewBase.scrollWheel(event: NSEvent); var H: Boolean; begin H := False; if event.deltaY <> 0 then begin try FOwner.Wnd.MouseWheel([], round(event.deltaY * 120), H); except Application.HandleException(Self); end; end; end; const KEY_ENTER = $24; KEY_SPACE = $31; KEY_ESC = $35; KEY_F1 = $7A; KEY_F2 = $78; KEY_F3 = $63; KEY_F4 = $76; KEY_F5 = $60; KEY_F6 = $61; KEY_F7 = $62; KEY_F8 = $64; KEY_F9 = $65; KEY_F10 = $6D; KEY_F11 = $67; KEY_F12 = $6F; KEY_POWER = $7F7F; KEY_TAB = $30; KEY_INS = $72; KEY_DEL = $75; KEY_HOME = $73; KEY_END = $77; KEY_PAGUP = $74; KEY_PAGDN = $79; KEY_UP = $7E; KEY_DOWN = $7D; KEY_LEFT = $7B; KEY_RIGHT = $7C; KEY_NUMLOCK = $47; KEY_NUMPAD0 = $52; KEY_NUMPAD1 = $53; KEY_NUMPAD2 = $54; KEY_NUMPAD3 = $55; KEY_NUMPAD4 = $56; KEY_NUMPAD5 = $57; KEY_NUMPAD6 = $58; KEY_NUMPAD7 = $59; KEY_NUMPAD8 = $5b; KEY_NUMPAD9 = $5c; KEY_PADDIV = $4B; KEY_PADMULT = $43; KEY_PADSUB = $4E; KEY_PADADD = $45; KEY_PADDEC = $41; KEY_PADENTER = $4C; KEY_BACKSPACE = $33; KEY_CAPSLOCK = $39; KEY_TILDE = 50; // `/~ key KEY_MINUS = 27; // -/_ key KEY_EQUAL = 24; // =/+ key KEY_BACKSLASH = 42; // \/| key KEY_LEFTBRACKET = 33; // [/{ key KEY_RIGHTBRACKET = 30; // ]/} key KEY_SEMICOLON = 41; // ;/: key KEY_QUOTE = 39; // '/" key KEY_COMMA = 43; // ,/< key KEY_PERIOD = 47; // ./> key KEY_SLASH = 44; // //? key function VKeyFromKeyCode(AKeyCode: Word): Integer; begin Result := 0; case AKeyCode of KEY_F1 : Result:=vkF1; KEY_F2 : Result:=vkF2; KEY_F3 : Result:=vkF3; KEY_F4 : Result:=vkF4; KEY_F5 : Result:=vkF5; KEY_F6 : Result:=vkF6; KEY_F7 : Result:=vkF7; KEY_F8 : Result:=vkF8; KEY_F9 : Result:=vkF9; KEY_F10 : Result:=vkF10; KEY_F11 : Result:=vkF11; KEY_F12 : Result:=vkF12; KEY_TAB : Result:=vkTab; KEY_INS : Result:=vkInsert; KEY_DEL : Result:=vkDelete; KEY_HOME : Result:=vkHome; KEY_END : Result:=vkEnd; KEY_PAGUP : Result:=vkPrior; KEY_PAGDN : Result:=vkNext; KEY_UP : Result:=vkUp; KEY_DOWN : Result:=vkDown; KEY_LEFT : Result:= vkLeft; KEY_RIGHT : Result:= vkRight; KEY_NUMLOCK : Result:= vkNumLock; KEY_NUMPAD0 : Result:=vkNumpad0; KEY_NUMPAD1 : Result:=vkNumpad1; KEY_NUMPAD2 : Result:=vkNumpad2; KEY_NUMPAD3 : Result:=vkNumpad3; KEY_NUMPAD4 : Result:=vkNumpad4; KEY_NUMPAD5 : Result:=vkNumpad5; KEY_NUMPAD6 : Result:=vkNumpad6; KEY_NUMPAD7 : Result:=vkNumpad7; KEY_NUMPAD8 : Result:=vkNumpad8; KEY_NUMPAD9 : Result:=vkNumpad9; KEY_PADDIV : Result:=vkDivide; KEY_PADMULT : Result:=vkMultiply; KEY_PADSUB : Result:=vkSubtract; KEY_PADADD : Result:=vkAdd; KEY_PADDEC : Result:=vkDecimal; KEY_BACKSPACE: Result := vkBack; KEY_ENTER : Result := vkReturn; KEY_ESC : Result := vkEscape; end; end; procedure TFMXViewBase.keyDown(event: NSEvent); var K: word; Ch: WideChar; Shift: TShiftState; VKKeyCode: Integer; begin if hasMarkedText then // IME's conversion window.is active. begin NativeView.inputContext.handleEvent(event); exit; end; Shift := [] + ShiftStateFromModFlags(event.modifierFlags); VKKeyCode := VKeyFromKeyCode(event.keyCode); if VKKeyCode <> 0 then begin K := VKKeyCode; Ch := #0; FOwner.FDelayRelease := True; try try FOwner.Wnd.KeyDown(K, Ch, Shift); if (K <> 0) and (VKKeyCode >= vkNumpad0) and (VKKeyCode <= vkDivide) then NativeView.inputContext.handleEvent(event); except Application.HandleException(Self); end; finally FOwner.FDelayRelease := False; if csDestroying in FOwner.Wnd.ComponentState then FOwner.Wnd.Release; end; Exit; end; FShift := Shift; NativeView.inputContext.handleEvent(event); // if FMarkRange.length = 0 then // begin // K := event.keyCode; // Ch := #0; // FOwner.Wnd.KeyDown(K, Ch, Shift); // end; end; procedure TFMXViewBase.keyUp(event: NSEvent); var S: string; K: word; Ch: WideChar; Shift: TShiftState; VKKeyCode: Integer; begin if hasMarkedText then // IME's conversion window.is active. exit; FShift := []; Shift := [] + ShiftStateFromModFlags(event.modifierFlags); VKKeyCode := VKeyFromKeyCode(event.keyCode); if VKKeyCode <> 0 then begin K := VKKeyCode; Ch := #0; try FOwner.Wnd.KeyUp(K, Ch, Shift); except Application.HandleException(Self); end; Exit; end else begin S := UTF8ToString(event.characters.UTF8String); if Length(S) > 0 then begin K := 0; Ch := S[1]; try FOwner.Wnd.KeyUp(K, Ch, Shift); except Application.HandleException(Self); end; end; end; end; function TFMXViewBase.acceptsFirstResponder: Boolean; begin Result := True; end; function TFMXViewBase.becomeFirstResponder: Boolean; begin Result := True; end; function TFMXViewBase.resignFirstResponder: Boolean; begin Result := True; end; { NSTextInputClient implementation } function TFMXViewBase.firstRectForCharacterRange(aRange: NSRange; actualRange: PNSRange): NSRect; var glyphRect: NSRect; R: TRectF; TSObj: ITextServiceControl; begin if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextServiceControl, TSObj) then begin R := TRectF.Create(TSObj.GetTargetClausePointF); end else begin R := TControl(FOwner.Wnd.Focused.GetObject).AbsoluteRect; end; glyphRect := MakeNSRect(R.Left, NativeView.bounds.size.height-R.Bottom, R.Right - R.Left, R.Bottom - R.Top); // Convert the rect to screen coordinates glyphRect := NativeView.convertRectToBase(glyphRect); glyphRect.origin := NativeView.window.convertBaseToScreen(glyphRect.origin); Result := glyphRect; end; function TFMXViewBase.hasMarkedText: Boolean; begin Result := FMarkedRange.location <> NSNotFound; end; function ToNSString(const text : Pointer; var NStr: NSString): Boolean; begin if TNSObject.Wrap(text).isKindOfClass(objc_getClass(PAnsiChar('NSAttributedString'))) then begin NStr := TNSString.Wrap(objc_msgSend(text, sel_getUid(PAnsiChar('string')))); Result := True; end else begin NStr := TNSString.Wrap(text); Result := False; end; end; procedure TFMXViewBase.insertText(text: Pointer{NSString}; replacementRange: NSRange); var i: Integer; K: Word; R : NSRange; Ch: WideChar; Str: string; NStr: NSString; IsAttrString: Boolean; TSC: ITextServiceControl; begin unmarkText; NativeView.inputContext.invalidateCharacterCoordinates; IsAttrString := ToNSString(text, NStr); // if TNSObject.Wrap(text).isKindOfClass(objc_getClass(PAnsiChar('NSAttributedString'))) then // begin // NStr := TNSString.Wrap(objc_msgSend(text, sel_getUid(PAnsiChar('string')))); // IsAttrString := True; // end // else // begin // NStr := TNSString.Wrap(text); // IsAttrString := False; // end; if NStr.length > 0 then begin Str := UTF8ToString(NStr.UTF8String); for i := 1 to Length(Str) do begin K := 0; Ch := Str[i]; try FOwner.Wnd.KeyDown(K, Ch, FShift); except Application.HandleException(Self); end; end; // Get a valid range if replacementRange.location = NSNotFound then if FMarkedRange.location <> NSNotFound then replacementRange := FMarkedRange else replacementRange := FSelectedRange else begin replacementRange.location := 0; replacementRange.length := 0; end; // Add the text FBackingStore.beginEditing; try if NStr.length = 0 then begin FBackingStore.deleteCharactersInRange(replacementRange); unmarkText; end else begin FMarkedRange.location := replacementRange.location; FMarkedRange.length := NStr.length; UpdateTextServiceControl; if IsAttrString then FBackingStore.replaceCharactersInRange(replacementRange, TNSAttributedString.Wrap(text)) else FBackingStore.replaceCharactersInRange(replacementRange, TNSString.Wrap(text)); unmarkText; end; finally FBackingStore.endEditing; end; NativeView.inputContext.invalidateCharacterCoordinates; NativeView.setNeedsDisplay(True); end; FBackingStore.beginEditing; R.location := 0; R.length := FBackingStore.mutableString.length; FBackingStore.deleteCharactersInRange(R); FBackingStore.endEditing; FMarkedRange.location := NSNotFound; FMarkedRange.length := 0; FSelectedRange.location := 0; FSelectedRange.length := 0; UpdateTextServiceControl; end; function TFMXViewBase.selectedRange: NSRange; begin Result := FSelectedRange; end; procedure TFMXViewBase.setMarkedText(text: Pointer {NSString}; selectedRange, replacementRange: NSRange); var NStr: NSString; IsAttrString: Boolean; TSC: ITextServiceControl; begin //function ToNSString(const text : Pointer; var NStr: NSString): Boolean; IsAttrString := ToNSString(text, NStr); // if TNSObject.Wrap(text).isKindOfClass(objc_getClass(PAnsiChar('NSAttributedString'))) then // begin // NStr := TNSString.Wrap(objc_msgSend(text, sel_getUid(PAnsiChar('string')))); // IsAttrString := True; // end // else // begin // NStr := TNSString.Wrap(text); // IsAttrString := False; // end; NativeView.inputContext.invalidateCharacterCoordinates; try if (FOwner.Wnd.Focused <> nil) and Supports(FOwner.Wnd.Focused, ITextServiceControl, TSC) then TSC.GetTextService.InternalSetMarkedText(UTF8ToString(NStr.UTF8String)); except Application.HandleException(Self); end; // Get a valid range if replacementRange.location = NSNotFound then if FMarkedRange.location <> NSNotFound then replacementRange := FMarkedRange else replacementRange := FSelectedRange else begin replacementRange.location := 0; replacementRange.length := 0; end; // Add the text FBackingStore.beginEditing; try if NStr.length = 0 then begin FBackingStore.deleteCharactersInRange(replacementRange); unmarkText; end else begin FMarkedRange.location := replacementRange.location; FMarkedRange.length := NStr.length; UpdateTextServiceControl; if IsAttrString then FBackingStore.replaceCharactersInRange(replacementRange, TNSAttributedString.Wrap(text)) else FBackingStore.replaceCharactersInRange(replacementRange, TNSString.Wrap(text)); end; finally FBackingStore.endEditing; end; // Redisplay FSelectedRange.location := replacementRange.location + selectedRange.location; FSelectedRange.length := selectedRange.length; UpdateTextServiceControl; NativeView.inputContext.invalidateCharacterCoordinates; NativeView.setNeedsDisplay(True); end; procedure TFMXViewBase.unMarkText; var R : NSRange; TSC: ITextServiceControl; begin // NativeView.inputContext.invalidateCharacterCoordinates; try if (FOwner.Wnd.Focused <> Nil) and Supports(FOwner.Wnd.Focused, ITextServiceControl, TSC) then TSC.GetTextService.InternalSetMarkedText(''); except Application.HandleException(Self); end; FMarkedRange.location := NSNotFound; FMarkedRange.length := 0; UpdateTextServiceControl; NativeView.inputContext.discardMarkedText; //writeln(' unMarkText|BS Old:', UTF8ToString(FBackingStore.mutableString.UTF8String)); // FBackingStore.beginEditing; // R.location := 0; // R.length := FBackingStore.mutableString.length; // FBackingStore.deleteCharactersInRange(R); // FBackingStore.endEditing; //writeln(' unMarkText|BS New:', UTF8ToString(FBackingStore.mutableString.UTF8String)); end; function TFMXViewBase.validAttributesForMarkedText: Pointer {NSArray}; var Attribs: array[0..1] of Pointer; Attrib: NSString; AttrArray: NSArray; begin Attrib := NSMarkedClauseSegmentAttributeName; Attribs[0] := (Attrib as ILocalObject).GetObjectID; Attrib := NSGlyphInfoAttributeName; Attribs[1] := (Attrib as ILocalObject).GetObjectID; AttrArray := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@Attribs[0], 2)); Result := (AttrArray as ILocalObject).GetObjectID; // Attrib := NSMarkedClauseSegmentAttributeName; // Attribs[0] := (Attrib as ILocalObject).GetObjectID; // AttrArray := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@Attribs[0], 1)); // Result := (AttrArray as ILocalObject).GetObjectID; end; procedure TFMXViewBase.doCommandBySelector(selector: SEL); begin NativeView.doCommandBySelector(selector); end; function TFMXViewBase.drawsVerticallyForCharacterAtIndex( charIndex: NSUInteger): Boolean; begin Result := False; end; function TFMXViewBase.fractionOfDistanceThroughGlyphForPoint( aPoint: NSPoint): CGFloat; begin Result := 0; end; function TFMXViewBase.windowLevel: NSInteger; begin Result := NativeView.window.level; end; function TFMXViewBase.FocusedTextService: TTextServiceCocoa; var TSC : ITextServiceControl; begin Result := nil; if Owner <> nil then if Owner.Wnd <> nil then if Owner.Wnd.Focused <> nil then if Supports(FOwner.Wnd.Focused, ITextServiceControl, TSC) then Result := TTextServiceCocoa(TSC.GetTextService); end; procedure TFMXViewBase.UpdateTextServiceControl; var TSC: ITextServiceControl; begin if (FOwner.Wnd.Focused <> Nil) and Supports(FOwner.Wnd.Focused, ITextServiceControl, TSC) then begin TTextServiceCocoa( TSC.GetTextService ).SetMarkedRange(FMarkedRange); TTextServiceCocoa( TSC.GetTextService ).SetSselectedRange(FSelectedRange); end; end; function TFMXViewBase.attributedString: NSAttributedString; begin Result := FBackingStore; end; function TFMXViewBase.attributedSubstringForProposedRange(aRange: NSRange; actualRange: PNSRange): NSAttributedString; begin // Get a valid range if actualRange <> nil then begin if (aRange.location <> NSNotFound) and (aRange.location < (FBackingStore.length - 1)) then actualRange^.location := aRange.location else actualRange^.location := 0; if (aRange.length) <= (FBackingStore.length - actualRange^.location) then actualRange^.length := aRange.length else actualRange^.length := FBackingStore.length - actualRange^.location - 1; // Get the backing store matching the range if (actualRange^.location = 0) and (actualRange^.length = FBackingStore.length) then begin Result := FBackingStore; end else begin Result := FBackingStore.attributedSubstringFromRange(actualRange^); end; end else Result := nil; end; function TFMXViewBase.baselineDeltaForCharacterAtIndex( anIndex: NSUInteger): CGFloat; begin Result := 0; end; function TFMXViewBase.characterIndexForPoint(aPoint: NSPoint): NSUInteger; begin Result := 0; end; function TFMXViewBase.markedRange: NSRange; begin Result := FMarkedRange; end; { TFMXView3D } constructor TFMXView3D.Create(AOwner: TFMXWindow; AFrameRect: NSRect); var V: Pointer; begin inherited Create(AOwner); V := NSOpenGLView(Super).initWithFrame(AFrameRect, TNSOpenGLView.OCClass.defaultPixelFormat); if GetObjectID <> V then UpdateObjectID(V); end; destructor TFMXView3D.Destroy; begin NSOpenGLView(Super).clearGLContext; inherited; end; function TFMXView3D.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(FMXView3D); end; { TFMXWindow} function TFMXWindow.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(FMXWindow); end; function TFMXWindow.GetView: NSView; begin Result := FViewObj.NativeView; end; function TFMXWindow.windowShouldClose(Sender: Pointer {id}): Boolean; begin Result := False; if Application = nil then Exit; if Application.Terminated then Exit; try Result := Wnd.CloseQuery; except Application.HandleException(Self); end; end; procedure TFMXWindow.windowWillClose(notification: NSNotification); begin if Application = nil then Exit; if Application.Terminated then Exit; if Wnd <> nil then try Wnd.Close; except Application.HandleException(Self); end; end; procedure TFMXWindow.windowDidBecomeKey(notification: NSNotification); begin try Wnd.Activate; except Application.HandleException(Self); end; end; procedure TFMXWindow.windowDidResignKey(notification: NSNotification); begin if (Application = nil) or (Application.Terminated) then Exit; if Wnd <> nil then begin try Wnd.Deactivate; if not Wnd.StaysOpen then Wnd.Close; except Application.HandleException(Self); end; end; end; procedure TFMXWindow.windowDidResize(notification: NSNotification); var LFrame: NSRect; begin LFrame := NSWindow(Super).frame; try Wnd.SetBounds(round(LFrame.origin.x), round(TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - LFrame.origin.y - LFrame.size.height), round(LFrame.size.width), round(LFrame.size.height)); except Application.HandleException(Self); end; end; procedure TFMXWindow.windowDidMove(notification: NSNotification); var LFrame: NSRect; begin LFrame := NSWindow(Super).frame; try Wnd.SetBounds(round(LFrame.origin.x), round(TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - LFrame.origin.y - LFrame.size.height), round(LFrame.size.width), round(LFrame.size.height)); except Application.HandleException(Self); end; end; var GlobalData: TDragObject; function GetDataObject(sender: NSDraggingInfo): TDragObject; var PBoard: NSPasteboard; Str: NSString; Arr: NSArray; W: string; I: Integer; begin FillChar(Result, SizeOf(Result), 0); PBoard := sender.draggingPasteboard; if PBoard.types.containsObject((NSFMXPboardType as ILocalObject).GetObjectID) then begin Result := GlobalData; Exit; end; if PBoard.types.containsObject((NSPasteboardTypeString as ILocalObject).GetObjectID) then begin Str := PBoard.stringForType(NSPasteboardTypeString); W := UTF8ToString(str.UTF8String); Result.Data := W; end; if PBoard.types.containsObject((NSFilenamesPboardType as ILocalObject).GetObjectID) then begin Arr := TNSArray.Wrap(PBoard.propertyListForType(NSFilenamesPboardType)); SetLength(Result.Files, Arr.count); for I := 0 to Arr.count - 1 do begin Str := TNSString.Wrap(Arr.objectAtIndex(I)); W := UTF8ToString(Str.UTF8String); Result.Files[I] := W; end; end; end; function TFMXWindow.draggingEntered(Sender: Pointer): NSDragOperation; var mp: NSPoint; P: TPointF; DragInfo: NSDraggingInfo; begin DragInfo := TNSDraggingInfo.Wrap(Sender); mp := DragInfo.draggingLocation; mp.y := View.bounds.size.height - mp.y; P := PointF(mp.x, mp.y); try Wnd.DragEnter(GetDataObject(DragInfo), Wnd.ClientToScreen(P)); except Application.HandleException(Self); end; Result := NSDragOperationEvery; end; procedure TFMXWindow.draggingExited(Sender: Pointer {id}); begin try Wnd.DragLeave; except Application.HandleException(Self); end; end; function TFMXWindow.draggingUpdated(Sender: Pointer): NSDragOperation; var mp: NSPoint; P: TPointF; Accept: Boolean; DragInfo: NSDraggingInfo; begin DragInfo := TNSDraggingInfo.Wrap(Sender); mp := DragInfo.draggingLocation; mp.y := View.bounds.size.height - mp.y; P := PointF(mp.x, mp.y); Accept := False; try Wnd.DragOver(GetDataObject(DragInfo), Wnd.ClientToScreen(P), Accept); except Application.HandleException(Self); end; if Accept then Result := NSDragOperationLink else Result := NSDragOperationNone; end; function TFMXWindow.performDragOperation(Sender: Pointer): Boolean; var mp: NSPoint; P: TPointF; DragInfo: NSDraggingInfo; begin DragInfo := TNSDraggingInfo.Wrap(Sender); mp := DragInfo.draggingLocation; mp.y := View.bounds.size.height - mp.y; P := PointF(mp.x, mp.y); try Wnd.DragDrop(GetDataObject(DragInfo), Wnd.ClientToScreen(P)); except Application.HandleException(Self); end; Result := True; end; function TFMXWindow.performKeyEquivalent(event: NSEvent): Boolean; var NSChars: NSString; ShortcutKey: string; Key: Char; VKKeyCode: Word; I: Integer; Shift: TShiftState; begin Result := False; if True then if (FViewObj <> Nil) and FViewObj.hasMarkedText then // IME's conversion window.is active. exit; VKKeyCode := VKeyFromKeyCode(event.keyCode); Shift := ShiftStateFromModFlags(event.modifierFlags); if VKKeyCode <> 0 then begin Key := #0; Wnd.KeyDown(VKKeyCode, Key, Shift); Result := True; end else begin NSChars := event.charactersIgnoringModifiers; if NSChars <> nil then begin ShortcutKey := UTF8ToString(NSChars.UTF8String); for I := 1 to Length(ShortcutKey) do begin Key := ShortcutKey[I]; if (Key = SMenuAppQuitKey) and (Shift = [ssCommand]) then Application.Terminate else begin VKKeyCode := 0; Wnd.KeyDown(Word(Key), Key, Shift); //Wnd.KeyDown(VKKeyCode, Key, Shift); if Key = #0 then Result := True; end; end; end; end; end; function TFMXWindow.acceptsFirstResponder: Boolean; begin Result := True; end; function TFMXWindow.becomeFirstResponder: Boolean; begin Result := True; end; function TFMXWindow.resignFirstResponder: Boolean; begin Result := True; end; function TFMXWindow.canBecomeKeyWindow: Boolean; begin if (Wnd <> nil) and (Wnd.Handle <> 0) then Result := True else Result := False; end; function TFMXWindow.canBecomeMainWindow: Boolean; begin Result := True; end; destructor TFMXWindow.Destroy; begin if FViewObj <> nil then begin FViewObj.NativeView.setHidden(True); NSWindow(Super).setContentView(nil); FViewObj.NativeView.release; if FViewObj is TFMXView3D then begin FViewObj._Release; FViewObj := nil; end else FreeAndNil(FViewObj); end; if FDelegate <> nil then begin FDelegate := nil; NSWindow(Super).setDelegate(nil); end; if Wnd.Handle <> 0 then NSWindow(Super).close; inherited; end; { TFMXWindowDelegate } type TFMXWindowDelegate = class(TOCLocal, NSWindowDelegate) private FWindow: TFMXWindow; public constructor Create(AOwner: TFMXWindow); destructor Destroy; override; function windowShouldClose(Sender: Pointer {id}): Boolean; cdecl; procedure windowWillClose(notification: NSNotification); cdecl; procedure windowDidBecomeKey(notification: NSNotification); cdecl; procedure windowDidResignKey(notification: NSNotification); cdecl; procedure windowDidResize(notification: NSNotification); cdecl; procedure windowDidMove(notification: NSNotification); cdecl; end; constructor TFMXWindowDelegate.Create(AOwner: TFMXWindow); begin inherited Create; FWindow := AOwner; end; destructor TFMXWindowDelegate.Destroy; begin FWindow := nil; inherited; end; procedure TFMXWindowDelegate.windowDidBecomeKey(notification: NSNotification); begin FWindow.windowDidBecomeKey(notification); end; procedure TFMXWindowDelegate.windowDidMove(notification: NSNotification); begin FWindow.windowDidMove(notification); end; procedure TFMXWindowDelegate.windowDidResignKey(notification: NSNotification); begin FWindow.windowDidResignKey(notification); end; procedure TFMXWindowDelegate.windowDidResize(notification: NSNotification); begin FWindow.windowDidResize(notification); end; function TFMXWindowDelegate.windowShouldClose(Sender: Pointer): Boolean; begin Result := FWindow.windowShouldClose(Sender); end; procedure TFMXWindowDelegate.windowWillClose(notification: NSNotification); var NSApp: NSApplication; ModWin: NSWindow; begin NSApp := TNSApplication.Wrap(TNSApplication.OCClass.sharedApplication); ModWin := NSApp.modalWindow; if (ModWin <> nil) and (FWindow <> nil) and ((ModWin as ILocalObject).GetObjectID = (FWindow.Super as ILocalObject).GetObjectID) then begin NSApp.abortModal; end; FWindow.windowWillClose(notification); end; function TPlatformCocoa.FindForm(AHandle: TFmxHandle): TCommonCustomForm; begin Result := TFMXWindow(HandleToObjC(AHandle)).Wnd; end; function TPlatformCocoa.CreateWindow(AForm: TCommonCustomForm): TFmxHandle; var Style: NSUInteger; FMXWin: TFMXWindow; NSWin: NSWindow; NSTitle: NSString; R: NSRect; LocalObj: ILocalObject; DraggedTypes: array[0..3] of Pointer; RegTypes: NSArray; begin if AForm.Owner is TPopup then FMXWin := TFMXPanelWindow.Create else FMXWin := TFMXWindow.Create; NSWin := NSWindow(FMXWin.Super); if AForm.Transparency or (AForm.BorderStyle = TFmxFormBorderStyle.bsNone) then Style := NSBorderlessWindowMask else begin Style := NSTitledWindowMask or NSUnifiedTitleAndToolbarWindowMask; if AForm.BorderStyle <> TFmxFormBorderStyle.bsNone then begin if TBorderIcon.biMinimize in AForm.BorderIcons then Style := Style or NSMiniaturizableWindowMask; if TBorderIcon.biMaximize in AForm.BorderIcons then Style := Style or NSWindowZoomButton; if TBorderIcon.biSystemMenu in AForm.BorderIcons then Style := Style or NSClosableWindowMask; end; if AForm.BorderStyle in [TFmxFormBorderStyle.bsSizeable, TFmxFormBorderStyle.bsSizeToolWin] then Style := Style or NSResizableWindowMask; end; R := TNSWindow.OCClass.contentRectForFrameRect(MakeNSRect(AForm.Left, TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - AForm.Top - AForm.height, AForm.width, AForm.height), Style); NSWin.initWithContentRect(R, Style, NSBackingStoreBuffered, True); NSWin.setAcceptsMouseMovedEvents(True); NSWin.setReleasedWhenClosed(False); NSWin.setBackgroundColor(TNSColor.Wrap(TNSColor.OCClass.clearColor)); NSWin.setShowsToolbarButton(True); if Supports(NSWin, NSPanel) then (NSWin as NSPanel).setWorksWhenModal(True); NSWin.useOptimizedDrawing(True); NSTitle := NSSTR(AForm.Caption); NSWin.setTitle(NSTitle); if AForm.TopMost then NSWin.setLevel(kCGModalPanelWindowLevelKey); FMXWin.Wnd := AForm; if AForm is TCustomForm3D then FMXWin.FViewObj := TFMXView3D.Create(FMXWin, R) else FMXWin.FViewObj := TFMXView.Create(FMXWin, R); if AForm is TCustomForm3D then begin if Supports(FMXWin.FViewObj, ILocalObject, LocalObj) then begin AForm.ContextHandle := THandle(LocalObj.GetObjectID); FMXWin.FViewObj._AddRef; end; end; NSWin.setContentView(FMXWin.View); if AForm.Transparency then NSWin.setOpaque(False) else NSWin.setOpaque(True); NSWin.setHasShadow(True); DraggedTypes[0] := (NSPasteboardTypeString as ILocalObject).GetObjectID; DraggedTypes[1] := (NSFMXPBoardtype as ILocalObject).GetObjectID; DraggedTypes[2] := (NSFilenamesPboardType as ILocalObject).GetObjectID; DraggedTypes[3] := nil; RegTypes := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@DraggedTypes[0], 3)); NSWin.registerForDraggedTypes(RegTypes); FMXWin.FDelegate := TFMXWindowDelegate.Create(FMXWin); NSWin.setDelegate(FMXWin.FDelegate); Result := AllocHandle(FMXWin); end; procedure TPlatformCocoa.DestroyWindow(AForm: TCommonCustomForm); var FMXWin: TFMXWindow; NSWin: NSWindow; begin if AForm.Handle <> 0 then begin FMXWin := TFMXWindow(HandleToObjC(AForm.Handle)); NSWin := NSWindow(FMXWin.Super); if NSWin.isVisible then NSWin.orderOut(nil); DeleteHandle(AForm.Handle); AForm.Handle := 0; if AForm is TCustomForm3D then AForm.ContextHandle := 0; end; end; procedure TPlatformCocoa.ReleaseWindow(AForm: TCommonCustomForm); begin if AForm <> nil then begin if (TFmxFormState.fsModal in AForm.FormState) or ((AForm.Handle <> 0) and (TFMXWindow(HandleToObjC(AForm.Handle)).FDelayRelease)) then AForm.Destroying else DoReleaseWindow(AForm); end; end; procedure TPlatformCocoa.DoReleaseWindow(AForm: TCommonCustomForm); var FMXWin: TFMXWindow; begin if AForm <> nil then begin if AForm.Handle <> 0 then begin FMXWin := TFMXWindow(HandleToObjC(AForm.Handle)); NSWindow(FMXWin.Super).setOneShot(True); NSWindow(FMXWin.Super).orderOut(nil); end; AForm.Free; end; end; procedure TPlatformCocoa.SetWindowRect(AForm: TCommonCustomForm; ARect: TRectF); var NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); NSWin.setFrame(MakeNSRect(ARect.Left, TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - ARect.Bottom, ARect.Right - ARect.Left, ARect.Bottom - ARect.Top), True); end; procedure TPlatformCocoa.InvalidateWindowRect(AForm: TCommonCustomForm; R: TRectF); var FMXWin: TFMXWindow; begin if IntersectRect(R, RectF(0, 0, AForm.width, AForm.height)) then begin FMXWin := TFMXWindow(HandleToObjC(AForm.Handle)); FMXWin.View.setNeedsDisplayInRect(MakeNSRect(R.Left, FMXWin.View.bounds.size.height - R.Bottom, R.Right - R.Left, R.Bottom - R.Top)); end; end; function TPlatformCocoa.AllocHandle(const Objc: IObjectiveC): TFmxHandle; begin Result := NewFmxHandle; TMonitor.Enter(FObjectiveCMap); try FObjectiveCMap.Add(Result, Objc); finally TMonitor.Exit(FObjectiveCMap); end; end; function TPlatformCocoa.NewFmxHandle: TFmxHandle; begin {$IFDEF CPUX64} Result := TInterlocked.Add(Int64(FHandleCounter), 16); {$ENDIF} {$IFDEF CPUX86} Result := TInterlocked.Add(Integer(FHandleCounter), 16); {$ENDIF} end; function TPlatformCocoa.GetWindowRect(AForm: TCommonCustomForm): TRectF; var NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); Result := TRectF(NSWin.frame); end; procedure TPlatformCocoa.SetWindowCaption(AForm: TCommonCustomForm; const ACaption: string); var NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); NSWin.setTitle(NSSTR(ACaption)); end; procedure TPlatformCocoa.SetWindowState(AForm: TCommonCustomForm; const AState: TWindowState); var NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); case AState of TWindowState.wsMinimized: if not NSWin.isMiniaturized then NSWin.performMiniaturize(nil); TWindowState.wsNormal: begin if NSWin.isMiniaturized then NSWin.performMiniaturize(nil); if NSWin.isZoomed then NSWin.performZoom(nil); end; TWindowState.wsMaximized: if not NSWin.isZoomed then NSWin.performZoom(nil); end; end; procedure TPlatformCocoa.ReleaseCapture(AForm: TCommonCustomForm); begin // Windows.ReleaseCapture; end; procedure TPlatformCocoa.SetCapture(AForm: TCommonCustomForm); begin // Windows.SetCapture(AHandle); end; function TPlatformCocoa.GetClientSize(AForm: TCommonCustomForm): TPointF; var LView: NSView; begin LView := TFMXWindow(HandleToObjC(AForm.Handle)).View; Result := PointF(LView.frame.size.width, LView.frame.size.height); end; procedure TPlatformCocoa.HideWindow(AForm: TCommonCustomForm); begin if (AForm <> nil) and (AForm.Handle <> 0) then NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super).orderOut(nil); end; procedure TPlatformCocoa.ShowWindow(AForm: TCommonCustomForm); var FMXWin: TFMXWindow; NSWin: NSWindow; frame: NSRect; begin FMXWin := TFMXWindow(HandleToObjC(AForm.Handle)); NSWin := NSWindow(FMXWin.Super); NSWin.makeKeyAndOrderFront((NSApp as ILocalObject).GetObjectID); if AForm = Application.MainForm then NSWin.makeMainWindow; frame := NSWin.frame; AForm.SetBounds(round(frame.origin.x), round(TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - frame.origin.y - frame.size.height), round(frame.size.width), round(frame.size.height)); // if AForm.Transparency then // TFMXWindowDelegate(Pointer(AForm.Handle)).NeedUpdateShadow := True; end; function TPlatformCocoa.ShowWindowModal(AForm: TCommonCustomForm): TModalResult; var Session: NSModalSession; MR: Integer; NSWin: NSWindow; begin if FModalStack = nil then FModalStack := TStack<TCommonCustomForm>.Create; FRestartModal := False; FModalStack.Push(AForm); try Result := mrNone; NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); NSWin.retain; try AForm.Show; AForm.ModalResult := mrNone; Session := NSApp.beginModalSessionForWindow(NSWin); while True do begin MR := NSApp.runModalSession(Session); if MR <> NSRunContinuesResponse then begin if FRestartModal then begin FRestartModal := False; NSApp.endModalSession(Session); Session := NSApp.beginModalSessionForWindow(NSWin); Continue; end; AForm.CloseModal; if AForm.Visible then AForm.Hide; Result := AForm.ModalResult; if csDestroying in AForm.ComponentState then DoReleaseWindow(AForm); FModalStack.Pop; if FModalStack.Count > 0 then FRestartModal := True; Break; end; if AForm.ModalResult <> 0 then begin NSApp.stopModal; Continue; end; Application.HandleMessage; end; NSApp.endModalSession(Session); finally NSWin.release; end; finally if (FModalStack.Count > 0) and (FModalStack.Peek = AForm) then FModalStack.Pop; end; end; function TPlatformCocoa.ClientToScreen(AForm: TCommonCustomForm; const Point: TPointF): TPointF; var np: NSPoint; NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); np := NSPoint(Point); np.y := TNSView.Wrap(NSWin.contentView).bounds.size.height - np.y; Result := TPointF(NSWin.convertBaseToScreen(np)); Result.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - Result.y; end; function TPlatformCocoa.ScreenToClient(AForm: TCommonCustomForm; const Point: TPointF): TPointF; var np: NSPoint; NSWin: NSWindow; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); np := NSPoint(Point); np.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - np.y; Result := TPointF(NSWin.convertScreenToBase(np)); Result.y := TNSView.Wrap(NSWin.contentView).bounds.size.height - Result.y; end; { Menus } type TOpenMenuItem = class(TMenuItem); procedure TPlatformCocoa.StartMenuLoop(const AView: IMenuView); procedure EndLoop; var View: IMenuView; begin View := AView; while View <> nil do begin View.Loop := False; View.Selected := nil; View := View.ParentView; end; end; function ContinueLoop: Boolean; begin Result := AView.Loop; end; procedure SelectPrev(AView: IMenuView); var i: Integer; begin if AView.GetObject = nil then Exit; if AView.Selected = nil then begin for i := AView.GetObject.ChildrenCount - 1 downto 0 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Break; end; end else begin for i := AView.Selected.Index - 1 downto 0 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Exit; end; { Select from end } for i := AView.GetObject.ChildrenCount - 1 downto 0 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Break; end; end; end; procedure SelectNext(AView: IMenuView); var i: Integer; begin if AView.GetObject = nil then Exit; if AView.Selected = nil then begin for i := 0 to AView.GetObject.ChildrenCount - 1 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Break; end; end else begin for i := AView.Selected.Index + 1 to AView.GetObject.ChildrenCount - 1 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Exit; end; { Select from start } for i := 0 to AView.GetObject.ChildrenCount - 1 do if AView.GetObject.Children[i] is TMenuITem then begin AView.Selected := TMenuItem(AView.GetObject.Children[i]); Break; end; end; end; var WP: NSPoint; P: TPointF; InMenus: Boolean; CurrentView, NewView: IMenuView; Obj: IControl; AutoPopupTime: Integer; TPos, TOldPos: TPointF; event: NSEvent; begin AView.Loop := True; TPos := TOldPos; AutoPopupTime := 0; try event := NSApp.nextEventMatchingMask(NSAnyEventMask, TNSDate.Wrap(TNSDate.OCClass.distantFuture), NSDefaultRunLoopMode, True); while ContinueLoop and (event <> nil) do begin case event.&type of { WM_WINDOWPOSCHANGING: begin EndLoop; Exit; end; WM_QUIT, WM_NCLBUTTONDOWN..WM_NCMBUTTONDBLCLK: begin EndLoop; Continue; end; } NSPeriodic: begin if (AView <> nil) then begin TPos := GetMousePos; AutoPopupTime := AutoPopupTime + 50; // Check auto popup if (TPos.X = TOldPos.X) and (TPos.Y = TOldPos.Y) then begin if (AutoPopupTime >= 500) then begin Obj := AView.ObjectAtPoint(TPos); if (Obj <> nil) and (Obj.GetObject is TMenuItem) and (TOpenMenuItem(Obj.GetObject).HavePopup) then begin TOpenMenuItem(Obj.GetObject).NeedPopup; end; AutoPopupTime := 0; end end else AutoPopupTime := 0; TOldPos := TPos; end; end; NSMouseMoved: begin { Handle MouseOver } WP := event.locationInWindow; if event.window <> nil then WP := event.window.convertBaseToScreen(WP); WP.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - WP.y; P := PointF(WP.X, WP.Y); Obj := AView.ObjectAtPoint(P); { Default } NSApp.sendEvent(event); { Handle menus } AutoPopupTime := 0; { Find top level menu } CurrentView := AView; while CurrentView.ParentView <> nil do CurrentView := CurrentView.ParentView; { Check all items } while CurrentView <> nil do begin Obj := CurrentView.ObjectAtPoint(P); if (Obj <> nil) and (Obj.GetObject is TMenuItem) and not (TMenuItem(Obj.GetObject).IsSelected) then begin if (CurrentView <> AView) then begin NewView := AView; while NewView <> CurrentView do begin NewView.Loop := False; NewView := NewView.ParentView; end; TOpenMenuItem(Obj.GetObject).NeedPopup; Exit; end; end; CurrentView := CurrentView.ChildView; end; end; NSLeftMouseDown: begin { Handle MouseOver if mouse over not menuitem } WP := event.locationInWindow; if event.window <> nil then WP := event.window.convertBaseToScreen(WP); WP.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - WP.y; P := PointF(WP.X, WP.Y); Obj := AView.ObjectAtPoint(P); if (Obj <> nil) and not (Obj is TMenuItem) then begin NSApp.sendEvent(event); end else begin { Menus } if (Obj <> nil) and (Obj.GetObject is TMenuItem) then begin if not (TMenuItem(Obj.GetObject).IsSelected) and TMenuItem(Obj.GetObject).HavePopup then TOpenMenuItem(Obj.GetObject).NeedPopup else begin EndLoop; TOpenMenuItem(Obj.GetObject).Click; end; end else begin CurrentView := AView; InMenus := False; while (CurrentView <> nil) and not InMenus do begin if not (CurrentView.IsMenuBar) and (CurrentView.ObjectAtPoint(P) <> nil) then InMenus := True; CurrentView := CurrentView.ParentView; end; if not InMenus then EndLoop; end; end; end; NSLeftMouseUp: begin { Handle MouseOver if mouse over not menuitem } WP := event.locationInWindow; if event.window <> nil then WP := event.window.convertBaseToScreen(WP); WP.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - WP.y; P := PointF(WP.X, WP.Y); Obj := AView.ObjectAtPoint(P); if (Obj <> nil) and not (Obj is TMenuItem) then begin NSApp.sendEvent(event); end; end; NSKeyDown: begin case event.keyCode of KEY_ENTER: begin if (AView.Selected <> nil) then begin if AView.Selected.HavePopup then AView.Selected.NeedPopup else begin TOpenMenuItem(AView.Selected).Click; EndLoop; end; end; end; KEY_ESC: begin AView.Selected := nil; Exit; end; KEY_LEFT: begin if (AView.ParentView <> nil) then if (AView.ParentView.IsMenuBar) then begin AView.Loop := False; SelectPrev(AView.ParentView); if AView.ParentView.Selected <> nil then AView.ParentView.Selected.NeedPopup; Exit; end else begin AView.Loop := False; end; end; KEY_RIGHT: begin if (AView.ParentView <> nil) then if (AView.ParentView.IsMenuBar) then begin AView.Loop := False; SelectNext(AView.ParentView); if AView.ParentView.Selected <> nil then AView.ParentView.Selected.NeedPopup; Exit; end else begin AView.Loop := False; end; end; KEY_UP: SelectPrev(AView); KEY_DOWN: SelectNext(AView); end; // case event.keyCode of end; // NSKeyDown (* WM_CHAR, WM_SYSCHAR: begin if FItems.FindItemByChar(Char(Msg.wParam)) <> nil then begin FSelItem := FItems.FindItemByChar(Char(Msg.wParam)); if FSelItem <> nil then InvalidateItem(FSelItem); PostMessage(Window.Handle, WM_KEYDOWN, VK_RETURN, 0) end; end; end; *) else begin NSApp.sendEvent(event); end; end; // case event := NSApp.nextEventMatchingMask(NSAnyEventMask, TNSDate.Wrap(TNSDate.OCClass.distantFuture), NSDefaultRunLoopMode, True); end; // while finally AView.Loop := False; end; end; function TPlatformCocoa.HandleToObjC(FmxHandle: TFmxHandle; const IID: TGUID; out Intf): Boolean; begin Result := Supports(HandleToObjC(FmxHandle), IID, Intf); end; procedure TPlatformCocoa.ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); var K: char; KByte: byte; ModifierMask: NSUInteger; begin KByte:= Lo(Shortcut); ModifierMask:= 0; case KByte of Ord('A')..Ord('Z') : K := Chr(KByte+ Ord('a') - Ord('A')) else K:= Chr(KByte); end; Key:= Word(K); if ShortCut and scCommand <> 0 then ModifierMask := ModifierMask or NSCommandKeyMask; if ShortCut and scShift <> 0 then ModifierMask := ModifierMask or NSShiftKeyMask; if ShortCut and scCtrl <> 0 then ModifierMask := ModifierMask or NSControlKeyMask; if ShortCut and scAlt <> 0 then ModifierMask := ModifierMask or NSAlternateKeyMask; Shift:= ShiftStateFromModFlags(ModifierMask); end; function TPlatformCocoa.ShortCutToText(ShortCut: TShortCut): string; var Name: String; key: Byte; begin Key:= Lo(Word(ShortCut)); case Key of Ord('A')..Ord('Z') : Name := Chr(Key); $08 : Name := Chr($2328); //(NSBackspaceCharacter); $09 : Name := Chr($002A); //(NSTabCharacter); $0d : Name := Chr($2305); //(NSEnterCharacter); $21 : Name := Chr($21DE); //(NSPageUpFunctionKey); $22 : Name := Chr($21DF); //(NSPageDownFunctionKey); $23 : Name := Chr($2198); //(NSEndFunctionKey); $24 : Name := Chr($2196); //(NSHomeFunctionKey); $25 : Name := Chr($27F6); //(NSLeftArrowFunctionKey); $26 : Name := Chr($2191); //(NSUpArrowFunctionKey); $27 : Name := Chr($27F5); //(NSRightArrowFunctionKey); $28 : Name := Chr($2193); //(NSDownArrowFunctionKey); $2e : Name := Chr($2326); //(NSDeleteCharacter); $70..$87: Name := 'F' + IntToStr(Key - $6F); //(NSF1FunctionKey+Ord(Key)-$70); end; Result:= ''; if Name <> '' then begin if ShortCut and scCommand <> 0 then Result:= Result + Chr($2318); // Command modifier (place of interest sign) if ShortCut and scCtrl <> 0 then Result:= Result + Chr($2303); // Ctrl modifier (up arrowhead) if ShortCut and scShift <> 0 then Result:= Result + Chr($21E7); // Shift modifier (upwards white arrow) if ShortCut and scAlt <> 0 then Result:= Result + Chr($2325); // option modifier (option key) Result:= Result + Name; end; end; type TMenuMACKeyCap = (mkcBkSp, mkcTab, mkcEsc, mkcEnter, mkcSpace, mkcPgUp, mkcPgDn, mkcEnd, mkcHome, mkcLeft, mkcUp, mkcRight, mkcDown, mkcIns, mkcDel, mkcShift, mkcCtrl, mkcAlt, mkcCmd); var MenuMACKeyCaps: array[TMenuMACKeyCap] of string = ( SmkcBkSp, SmkcTab, SmkcEsc, SmkcEnter, SmkcSpace, SmkcPgUp, SmkcPgDn, SmkcEnd, SmkcHome, SmkcLeft, SmkcUp, SmkcRight, SmkcDown, SmkcIns, SmkcDel, SmkcShift, SmkcCtrl, SmkcAlt, SmkcCmd); function TPlatformCocoa.TextToShortCut(Text: String): integer; { If the front of Text is equal to Front then remove the matching piece from Text and return True, otherwise return False } function CompareFront(var Text: string; const Front: string): Boolean; begin Result := False; if (Length(Text) >= Length(Front)) and (AnsiStrLIComp(PChar(Text), PChar(Front), Length(Front)) = 0) then begin Result := True; Delete(Text, 1, Length(Front)); end; end; var Key: TShortCut; Shift: TShortCut; begin Result := 0; Shift := 0; while True do begin if CompareFront(Text, MenuMACKeyCaps[mkcShift]) then Shift := Shift or scShift else if CompareFront(Text, '^') then Shift := Shift or scCtrl else if CompareFront(Text, MenuMACKeyCaps[mkcCtrl]) then Shift := Shift or scCtrl else if CompareFront(Text, MenuMACKeyCaps[mkcAlt]) then Shift := Shift or scAlt else if CompareFront(Text, MenuMACKeyCaps[mkcCmd]) then Shift:= Shift or scCommand else Break; end; if Text = '' then Exit; for Key := $08 to $255 do { Copy range from table in ShortCutToText } if AnsiCompareText(Text, ShortCutToText(Key)) = 0 then begin Result := Key or Shift; Exit; end; end; { TFMXOSMenuItem } type FMXOSMenuItem = interface(NSMenuItem) ['{A922028A-C1EE-41AF-8345-26671E6879AD}'] procedure DispatchMenuClick(Sender: Pointer); cdecl; end; TFMXOSMenuItem = class(TOCLocal) private FMXMenuItem: TMenuItem; public constructor Create(AFMXMenuItem: TMenuItem); function GetObjectiveCClass: PTypeInfo; override; procedure DispatchMenuClick(Sender: Pointer); cdecl; end; constructor TFMXOSMenuItem.Create(AFMXMenuItem: TMenuItem); var Key: Char; ModMask: NSUInteger; begin inherited Create; FMXMenuItem := AFMXMenuItem; ShortCutToMACKey(FMXMenuItem.ShortCut, Key, ModMask); UpdateObjectID(NSMenuItem(Super).initWithTitle(NSSTR(FMXMenuItem.Text), sel_getUid(PAnsiChar('DispatchMenuClick:')), NSSTR(Key))); NSMenuItem(Super).setKeyEquivalentModifierMask(ModMask); NSMenuItem(Super).setTarget(GetObjectID); end; procedure TFMXOSMenuItem.DispatchMenuClick(Sender: Pointer); begin try if Assigned(FMXMenuItem.OnClick) then FMXMenuItem.OnClick(Self); except Application.HandleException(Self); end; end; function TFMXOSMenuItem.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(FMXOSMenuItem); end; procedure TPlatformCocoa.CreateChildMenuItems(AChildMenu: IItemsContainer; AParentMenu: NSMenu); var J: Integer; LChildMenuItem: TMenuItem; LNSSubMenuItem: TFMXOSMenuItem; LNewSubMenu: NSMenu; begin for J := 0 to AChildMenu.GetItemsCount - 1 do begin LChildMenuItem := TMenuItem(AChildMenu.GetItem(J)); if LChildMenuItem.Visible then if LChildMenuItem.Text = '-' then AParentMenu.addItem(TNSMenuItem.Wrap(TNSMenuItem.OCClass.separatorItem)) else begin LNSSubMenuItem := TFMXOSMenuItem.Create(LChildMenuItem); LChildMenuItem.Handle := AllocHandle(LNSSubMenuItem); if (AChildMenu.GetItem(J) as IItemsContainer).GetItemsCount > 0 then begin LNewSubMenu := TNSMenu.Create; LNewSubMenu := TNSMenu.Wrap(LNewSubMenu.initWithTitle(NSSTR(TMenuItem(AChildMenu.GetItem(J)).Text))); CreateChildMenuItems((AChildMenu.GetItem(J) as IItemsContainer), LNewSubMenu); NSMenuItem(LNSSubMenuItem.Super).setSubmenu(LNewSubMenu); end; AParentMenu.addItem(NSMenuItem(LNSSubMenuItem.Super)); end; end; end; var AppNSMenuItem: NSMenuItem; procedure TPlatformCocoa.CreateApplicationMenu; var LAppMenu: NSMenu; LNSMenuItem: NSMenuItem; LQuitItem: NSMenuItem; MenuBar: NSMenu; AppBundle: NSBundle; AppNameKey: Pointer; NSAppName: NSString; FMXAppName: string; begin MenuBar := NSApp.mainMenu; if MenuBar = nil then begin MenuBar := TNSMenu.Create; MenuBar := TNSMenu.Wrap(MenuBar.initWithTitle(NSSTR(''))); end; LAppMenu := TNSMenu.Create; LAppMenu := TNSMenu.Wrap(LAppMenu.initWithTitle(NSSTR('NSAppleMenu'))); LNSMenuItem := TNSMenuItem.Create; LNSMenuItem := TNSMenuItem.Wrap(LNSMenuItem.initWithTitle(NSSTR(''), nil, NSSTR(''))); LNSMenuItem.setSubmenu(LAppMenu); if Application.ApplicationMenuItems <> nil then begin CreateChildMenuItems(Application.ApplicationMenuItems, LAppMenu); end else begin if Application.Title <> '' then FMXAppName := Application.Title else begin AppNameKey := (NSSTR('CFBundleName') as ILocalObject).GetObjectID; AppBundle := TNSBundle.Wrap(TNSBundle.OCClass.mainBundle); NSAppName := TNSString.Wrap(AppBundle.infoDictionary.objectForKey(AppNameKey)); FMXAppName := UTF8ToString(NSAppName.UTF8String); end; LQuitItem := TNSMenuItem.Create; LQuitItem := TNSMenuItem.Wrap(LQuitItem.initWithTitle(NSSTR(Format(SMenuAppQuit, [FMXAppName])), sel_getUid(PAnsiChar('terminate:')), NSSTR(SMenuAppQuitKey))); LAppMenu.addItem(LQuitItem); end; if MenuBar <> nil then MenuBar.insertItem(LNSMenuItem, 0); AppNSMenuItem:= LNSMenuItem; NSApp.setMainMenu(MenuBar); end; procedure TPlatformCocoa.CreateOSMenu(AForm: TCommonCustomForm; const AMenu: IItemsContainer); var MenuBar: NSMenu; LNSMenuItem: NSMenuItem; LNewMenu: NSMenu; MenuItem: TMenuItem; I: Integer; begin MenuBar := TNSMenu.Create; MenuBar := TNSMenu.Wrap(MenuBar.initWithTitle(NSSTR(''))); if (MenuBar <> nil) and (AppNsMenuItem <> nil) then begin NSApp.mainMenu.removeItem(AppNSMenuItem); MenuBar.insertItem(AppNSMenuItem, 0); end; // TMainMenu items if AMenu <> nil then begin for I := 0 to AMenu.GetItemsCount - 1 do begin MenuItem := TMenuItem(AMenu.GetItem(I)); if MenuItem.Visible then begin LNewMenu := TNSMenu.Create; LNewMenu := TNSMenu.Wrap(LNewMenu.initWithTitle(NSSTR(MenuItem.Text))); LNSMenuItem := TNSMenuItem.Create; LNSMenuItem := TNSMenuItem.Wrap(LNSMenuItem.initWithTitle(NSSTR(''), nil, NSSTR(''))); LNSMenuItem.setSubmenu(LNewMenu); CreateChildMenuItems((MenuItem as IItemsContainer), LNewMenu); MenuItem.Handle := AllocHandle(LNSMenuItem); MenuBar.addItem(LNSMenuItem); end; end; end; NSApp.setMainMenu(MenuBar); end; procedure TPlatformCocoa.UpdateMenuItem(const AItem: TMenuItem); var P: TFMXObject; RootMenu: TFMXObject; Root: IItemsContainer; begin P := AItem; RootMenu := nil; while P.Parent <> nil do begin if P.Parent is TContent then P := P.Parent; if (P is TMenuBar) or (P is TMainMenu) then RootMenu := P; P := P.Parent; end; if (AItem.Root <> nil) and (AItem.Root.GetObject is TCommonCustomForm) and (RootMenu <> nil) and Supports(RootMenu, IItemsContainer, Root) then begin CreateOSMenu(TCommonCustomForm(AItem.Root.GetObject), Root); end; end; procedure TPlatformCocoa.ValidateHandle(FmxHandle: TFmxHandle); begin if (FmxHandle and $F <> 0) then raise EInvalidFmxHandle.CreateResFmt(@SInvalidFmxHandle, [HexDisplayPrefix, SizeOf(TFmxHandle) * 2, FmxHandle]); end; { Drag and Drop ===============================================================} function NSImageFromBitmap(Bmp: TBitmap): NSImage; var mem: TMemoryStream; Data: NSData; begin mem := TMemoryStream.Create; Bmp.SaveToStream(mem); Data := TNSData.Wrap(TNSData.OCClass.dataWithBytes(mem.Memory, mem.Size)); // Data := NSData.dataWithBytes_length(mem.Memory, mem.size); Result := TNSImage.Create; Result := TNSImage.Wrap(Result.initWithData(Data)); mem.Free; end; procedure TPlatformCocoa.BeginDragDrop(AForm: TCommonCustomForm; const Data: TDragObject; ABitmap: TBitmap); var Img: NSImage; Loc: NSPoint; Pboard: NSPasteboard; PBoardTypes: NSArray; FMXPBoardTypePtr: Pointer; LocObj: ILocalObject; FMXWin: TFMXWindow; ViewPtr: Pointer; PboardPtr: Pointer; begin Img := NSImageFromBitmap(ABitmap); Pboard := TNSPasteboard.Wrap(TNSPasteboard.OCClass.pasteboardWithName(NSDragPboard)); if Supports(NSFMXPBoardType, ILocalObject, LocObj) then FMXPBoardTypePtr := LocObj.GetObjectID else FMXPBoardTypePtr := nil; PBoardTypes := TNSArray.Wrap(TNSArray.OCClass.arrayWithObject(FMXPBoardTypePtr)); if Supports(PBoard, ILocalObject, LocObj) then PboardPtr := LocObj.GetObjectID else PboardPtr := nil; Pboard.declareTypes(PBoardTypes, PboardPtr); { if not VarIsObject(Data.Data) and VarIsStr(Data.Data) then pboard.setString_forType(NSStr(PChar(Utf8Encode(Data.Data))), NSStringPBoardtype);} GlobalData := Data; FMXWin := TFMXWindow(HandleToObjC(AForm.Handle)); if FMXWin.LastEvent <> nil then begin loc := FMXWin.LastEvent.locationInWindow; loc.x := loc.x - (ABitmap.width div 2); loc.y := loc.y - (ABitmap.height div 2); if Supports(FMXWin.View, ILocalObject, LocObj) then ViewPtr := LocObj.GetObjectID else ViewPtr := nil; NSWindow(FMXWin.Super).dragImage(img, loc, NSSize(Point(0, 0)), FMXWin.LastEvent, pboard, ViewPtr, True); FMXWin.LastEvent := nil; end; end; procedure TPlatformCocoa.SetClientSize(AForm: TCommonCustomForm; const ASize: TPointF); var NSWin: NSWindow; OldFrame, Frame, R: NSRect; begin NSWin := NSWindow(TFMXWindow(HandleToObjC(AForm.Handle)).Super); if NSWin.isVisible then begin OldFrame := NSWin.frame; R.origin := OldFrame.origin; R.size := NSSize(ASize); Frame := NSWin.frameRectForContentRect(R); Frame.origin.x := OldFrame.origin.x; Frame.origin.y := OldFrame.origin.y + OldFrame.size.height - Frame.size.height; NSWin.setFrame(Frame, True); end else NSWin.setContentSize(NSSize(ASize)); end; { Clipboard ===============================================================} procedure TPlatformCocoa.SetClipboard(Value: Variant); var W: string; pb: NSPasteboard; types: NSArray; begin if VarIsStr(Value) then begin W := Value; pb := TNSPasteboard.Wrap(TNSPasteboard.OCClass.generalPasteboard); types := TNSArray.Wrap(TNSArray.OCClass.arrayWithObject((NSPasteboardTypeString as ILocalObject).GetObjectID)); pb.declareTypes(types, (pb as ILocalObject).GetObjectID); pb.setString(NSSTR(W), NSPasteboardTypeString); end; end; function TPlatformCocoa.GetClipboard: Variant; var W: string; pb: NSPasteboard; str: NSString; begin Result := NULL; pb := TNSPasteboard.Wrap(TNSPasteboard.OCClass.generalPasteboard); str := pb.stringForType(NSPasteboardTypeString); if str <> nil then begin W := UTF8ToString(str.UTF8String); Result := W; end; end; procedure TPlatformCocoa.SetCursor(AForm: TCommonCustomForm; const ACursor: TCursor); const SizeNWSECursor: array [0..192] of byte = ( $89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $88, $49, $44, $41, $54, $78, $9C, $AC, $93, $4B, $0A, $C0, $20, $0C, $44, $45, $8A, $69, $D7, $5D, $7B, $00, $0F, $98, $EB, $6B, $15, $8C, $44, $F1, $1B, $3A, $20, $BA, $D0, $E7, $4C, $A2, $4A, $FD, $A1, $30, $D1, $36, $20, $4D, $69, $00, $40, $59, $8B, $00, $FC, $B0, $08, $60, $8C, $A9, $6E, $BF, $A2, $44, $0E, $08, $82, $88, $EA, $8D, $DA, $02, $78, $EF, $43, $0B, $63, $31, $EE, $29, $80, $67, $26, $88, $D6, $BA, $82, $58, $6B, $97, $69, $CA, $A6, $91, $93, $AD, $16, $3F, $51, $23, $48, $8A, $D9, $44, $EB, $8B, $AA, $3F, $2B, $F0, $3A, $4F, $16, $41, $A8, $C5, $47, $00, $96, $F7, $DC, $81, $73, $AE, $FB, $C8, $44, $0E, $C4, $1F, $6D, $A5, $0F, $00, $00, $FF, $FF, $03, $00, $FD, $DF, $FC, $72, $CD, $04, $2F, $27, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82 ); SizeNESWCursor: array [0..211] of byte = ( $89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $9B, $49, $44, $41, $54, $78, $9C, $9C, $93, $51, $0E, $C0, $10, $0C, $86, $3D, $88, $CC, $F3, $0E, $E3, $2A, $2E, $E2, $04, $6E, $E0, $C5, $5D, $DC, $4D, $4C, $93, $CD, $1A, $46, $AD, $7F, $D2, $14, $49, $3F, $D5, $96, $10, $0B, $95, $52, $48, $23, $55, $D6, $DA, $03, $80, $EB, $ED, $17, $20, $E7, $CC, $06, $1C, $29, $A5, $96, $85, $52, $AA, $79, $12, $A0, $AB, $62, $8C, $BC, $27, $9C, $55, $21, $84, $21, $18, $45, $CD, $01, $52, $4A, $E1, $9C, $FB, $0C, $F6, $DE, $F7, $5D, $79, $0B, $85, $4F, $26, $37, $C3, $42, $0E, $33, $70, $6F, $86, $14, $B7, $AB, $8D, $01, $5F, $85, $32, $C6, $C0, $42, $93, $00, $DC, $A2, $27, $D8, $5A, $0B, $DD, $58, $8F, $EC, $2C, $03, $18, $1E, $54, $13, $FE, $13, $B6, $01, $33, $ED, $02, $78, $5F, $B5, $EA, $02, $00, $00, $FF, $FF, $03, $00, $27, $CE, $7B, $C4, $F5, $A4, $B6, $D6, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82 ); SizeAllCursor: array [0..174] of byte = ( $89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $09, $70, $48, $59, $73, $00, $00, $0B, $13, $00, $00, $0B, $13, $01, $00, $9A, $9C, $18, $00, $00, $00, $61, $49, $44, $41, $54, $78, $9C, $AC, $53, $CB, $0A, $00, $20, $0C, $1A, $F4, $FF, $DF, $6C, $10, $74, $68, $0F, $17, $65, $E0, $A9, $74, $BA, $36, $03, $60, $04, $FB, $94, $6F, $28, $D9, $6C, $2C, $30, $91, $96, $DC, $89, $5C, $91, $99, $48, $95, $19, $49, $84, $E3, $2A, $13, $F0, $55, $B2, $CA, $C1, $49, $D5, $B0, $D2, $81, $17, $A5, $99, $3B, $04, $AB, $AF, $02, $DF, $11, $24, $4D, $94, $7C, $A3, $64, $90, $24, $A3, $2C, $59, $A6, $EB, $75, $9E, $00, $00, $00, $FF, $FF, $03, $00, $3A, $00, $A6, $5B, $CC, $0B, $A4, $58, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82 ); WaitCursor: array [0..124] of byte = ( $89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $10, $00, $00, $00, $10, $08, $06, $00, $00, $00, $1F, $F3, $FF, $61, $00, $00, $00, $44, $49, $44, $41, $54, $78, $9C, $62, $60, $C0, $0E, $FE, $E3, $C0, $44, $83, $21, $6E, $C0, $7F, $5C, $80, $18, $43, $70, $6A, $26, $D6, $10, $BA, $19, $80, $D3, $10, $6C, $0A, $C9, $33, $00, $59, $03, $45, $5E, $C0, $65, $00, $94, $4D, $5A, $38, $10, $B2, $1D, $C5, $10, $1C, $98, $68, $30, $84, $0C, $00, $00, $00, $00, $FF, $FF, $03, $00, $A9, $31, $25, $E9, $C0, $2C, $FB, $9B, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82 ); HelpCursor: array [0..238] of byte = ( $89, $50, $4E, $47, $0D, $0A, $1A, $0A, $00, $00, $00, $0D, $49, $48, $44, $52, $00, $00, $00, $12, $00, $00, $00, $12, $08, $06, $00, $00, $00, $56, $CE, $8E, $57, $00, $00, $00, $B6, $49, $44, $41, $54, $78, $9C, $A4, $94, $3B, $12, $80, $20, $0C, $44, $69, $6C, $6D, $6C, $BC, $83, $8D, $B5, $F7, $E0, $FE, $37, $01, $89, $93, $8C, $61, $F9, $18, $21, $33, $19, $15, $C9, $73, $B3, $46, $9D, $83, $88, $31, $52, $36, $03, $F7, $17, $C5, $1A, $E2, $BD, $0F, $74, $89, $49, $EB, $9F, $30, $06, $05, $81, $70, $51, $D0, $6B, $66, $18, $15, $49, $01, $9F, $9F, $29, $77, $BD, $CE, $F7, $E8, $B8, $98, $40, $1A, $D6, $00, $ED, $05, $4C, $79, $94, $B5, $C1, $80, $0B, $40, $D2, $1A, $A9, $5D, $BB, $AA, $30, $1B, $1E, $5D, $29, $B7, $AE, $57, $FC, $A4, $23, $ED, $CF, $D4, $00, $A4, $AF, $08, $D5, $C1, $5B, $FC, $0F, $11, $D0, $34, $44, $83, $A6, $20, $4E, $08, $EF, $A7, $61, $32, $B7, $0A, $A9, $F8, $53, $CE, $8E, $05, $E4, $CA, $21, $1C, $F2, $A7, $A6, $68, $BC, $3D, $F0, $28, $53, $64, $F9, $11, $48, $3C, $83, $59, $83, $FC, $8D, $85, $8B, $B7, $2F, $C8, $0D, $00, $00, $FF, $FF, $03, $00, $A5, $D1, $28, $C9, $B0, $25, $E3, $01, $00, $00, $00, $00, $49, $45, $4E, $44, $AE, $42, $60, $82 ); var C: NSCursor; Image: NSImage; Data: NSData; begin case ACursor of crCross: C := TNSCursor.Wrap(TNSCursor.OCClass.crosshairCursor); crArrow: C := TNSCursor.Wrap(TNSCursor.OCClass.arrowCursor); crIBeam: C := TNSCursor.Wrap(TNSCursor.OCClass.IBeamCursor); crSizeNS: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpDownCursor); crSizeWE: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeLeftRightCursor); crUpArrow: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpCursor); crDrag, crMultiDrag: C := TNSCursor.Wrap(TNSCursor.OCClass.dragCopyCursor); crHSplit: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeLeftRightCursor); crVSplit: C := TNSCursor.Wrap(TNSCursor.OCClass.resizeUpDownCursor); crNoDrop, crNo: C := TNSCursor.Wrap(TNSCursor.OCClass.operationNotAllowedCursor); crHandPoint: C := TNSCursor.Wrap(TNSCursor.OCClass.pointingHandCursor); crAppStart, crSQLWait, crHourGlass: begin Data := TNSData.Wrap(TNSData.Create.initWithBytes(@WaitCursor[0], Length(WaitCursor))); Image := TNSImage.Wrap(TNSImage.Create.initWithData(Data)); C := TNSCursor.Wrap(TNSCursor.Create.initWithImage(Image, NSPoint(PointF(10, 10)))); end; crHelp: begin Data := TNSData.Wrap(TNSData.Create.initWithBytes(@HelpCursor[0], Length(HelpCursor))); Image := TNSImage.Wrap(TNSImage.Create.initWithData(Data)); C := TNSCursor.Wrap(TNSCursor.Create.initWithImage(Image, NSPoint(PointF(10, 10)))); end; crSizeNWSE: begin Data := TNSData.Wrap(TNSData.Create.initWithBytes(@SizeNWSECursor[0], Length(SizeNWSECursor))); Image := TNSImage.Wrap(TNSImage.Create.initWithData(Data)); C := TNSCursor.Wrap(TNSCursor.Create.initWithImage(Image, NSPoint(PointF(10, 10)))); end; crSizeNESW: begin Data := TNSData.Wrap(TNSData.Create.initWithBytes(@SizeNESWCursor[0], Length(SizeNESWCursor))); Image := TNSImage.Wrap(TNSImage.Create.initWithData(Data)); C := TNSCursor.Wrap(TNSCursor.Create.initWithImage(Image, NSPoint(PointF(10, 10)))); end; crSizeAll: begin Data := TNSData.Wrap(TNSData.Create.initWithBytes(@SizeAllCursor[0], Length(SizeAllCursor))); Image := TNSImage.Wrap(TNSImage.Create.initWithData(Data)); C := TNSCursor.Wrap(TNSCursor.Create.initWithImage(Image, NSPoint(PointF(10, 10)))); end; else C := TNSCursor.Wrap(TNSCursor.OCClass.arrowCursor); end; C.push; end; { Mouse ===============================================================} function TPlatformCocoa.GetMousePos: TPointF; var P: NSPoint; begin P := TNSEvent.OCClass.mouseLocation; Result := TPointF.Create(P.x, P.y); Result.y := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size.height - Result.y; end; function TPlatformCocoa.GetScreenSize: TPointF; begin Result := TPointF(TNSScreen.Wrap(TNSScreen.OCClass.mainScreen).frame.size) end; { International ===============================================================} function TPlatformCocoa.GetCurrentLangID: string; begin Result := UTF8ToString(TNSLocale.Wrap(TNSLocale.OCClass.currentLocale).localeIdentifier.UTF8String); if Length(Result) > 2 then Delete(Result, 3, MaxInt); end; function TPlatformCocoa.GetDefaultFontFamilyName: String; begin Result := 'Helvetica'; end; function TPlatformCocoa.GetLocaleFirstDayOfWeek: string; var cal: NSCalendar; firstDay: NSUInteger; begin cal:= TNSCalendar.Wrap(TNSCalendar.OCClass.currentCalendar); firstDay:= Cal.firstWeekday; Result:= IntToStr(firstDay); end; { Dialogs ===============================================================} function TPlatformCocoa.DialogOpenFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; var OpenFile: NSOpenPanel; DefaultExt: string; Filter: NSArray; InitialDir: NSURL; outcome: NSInteger; I: Integer; function AllocFilterStr(const S: string): NSArray; var input, pattern: string; FileTypes: array of string; outcome, aux: TArray<string>; i, j: Integer; FileTypesNS: array of Pointer; NStr: NSString; LocObj: ILocalObject; begin // First, split the string by using '|' as a separator input := S; pattern := '\|'; outcome := TRegEx.Split(input, pattern); pattern := '\*\.'; SetLength(FileTypes, 0); for i := 0 to length(outcome) - 1 do begin if Odd(i) then if outcome[i] <> '*.*' then if AnsiLeftStr(outcome[i], 2) = '*.' then begin aux := TRegEx.Split(outcome[i], pattern); for j := 0 to length(aux) - 1 do begin aux[j] := Trim(aux[j]); if aux[j] <> '' then begin if AnsiEndsStr(';', aux[j]) then aux[j] := AnsiLeftStr(aux[j], length(aux[j]) - 1); SetLength(FileTypes, length(FileTypes) + 1); FileTypes[length(FileTypes) - 1] := aux[j]; end; end; end; end; // create the NSArray from the FileTypes array SetLength(FileTypesNS, length(FileTypes)); for i := 0 to length(FileTypes) - 1 do begin NStr := NSSTR(FileTypes[i]); if Supports(NStr, ILocalObject, LocObj) then FileTypesNS[i] := LocObj.GetObjectID; end; Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@FileTypesNS[0], length(FileTypes))); end; begin Result := False; DefaultExt := ADefaultExt; OpenFile := TNSOpenPanel.Wrap(TNSOpenPanel.OCClass.openPanel); OpenFile.setAllowsMultipleSelection(TOpenOption.ofAllowMultiSelect in AOptions); OpenFile.setCanChooseFiles(True); OpenFile.setCanChooseDirectories(True); AFiles.Clear; if AInitDir <> '' then begin InitialDir := TNSURL.Create; InitialDir.initFileURLWithPath(NSSTR(AInitDir)); OpenFile.setDirectoryURL(InitialDir); end; if AFileName <> '' then begin OpenFile.setNameFieldStringValue(NSSTR(AFileName)); end; if AFilter <> '' then begin Filter := AllocFilterStr(AFilter); OpenFile.setAllowedFileTypes(Filter); end; if ATitle <> '' then OpenFile.setTitle(NSSTR(ATitle)); OpenFile.retain; try outcome := OpenFile.runModal; if (FModalStack <> nil) and (FModalStack.Count > 0) then FRestartModal := True; if outcome = NSOKButton then begin for I := 0 to OpenFile.URLs.count - 1 do AFiles.Add(UTF8ToString(TNSUrl.Wrap(OpenFile.URLs.objectAtIndex(I)).relativePath.UTF8String)); if AFiles.Count > 0 then AFileName := AFiles[0]; if DefaultExt <> '' then if ExtractFileExt(AFileName) = '' then ChangeFileExt(AFileName, DefaultExt); Result := True; end; finally OpenFile.release; end; end; // Cocoa string constants used for printing const AppKitFwk: string = '/System/Library/Frameworks/AppKit.framework/AppKit'; function NSPrintPrinter: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintPrinter'); end; function NSPrintCopies: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintCopies'); end; function NSPrintAllPages: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintAllPages'); end; function NSPrintFirstPage: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintFirstPage'); end; function NSPrintLastPage: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintLastPage'); end; function NSPrintMustCollate: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintMustCollate'); end; function NSPrintReversePageOrder: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintReversePageOrder'); end; function NSPrintJobDisposition: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintJobDisposition'); end; function NSPrintSavePath: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintSavePath'); end; function NSPrintPagesAcross: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintPagesAcross'); end; function NSPrintPagesDown: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintPagesDown'); end; function NSPrintTime: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintTime'); end; function NSPrintDetailedErrorReporting: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintDetailedErrorReporting'); end; function NSPrintFaxNumber: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintFaxNumber'); end; function NSPrintPrinterName: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintPrinterName'); end; function NSPrintHeaderAndFooter: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintHeaderAndFooter'); end; function NSPrintSelectionOnly: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintSelectionOnly'); end; function NSPrintJobSavingURL: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintJobSavingURL'); end; function NSPrintJobSavingFileNameExtensionHidden: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintJobSavingFileNameExtensionHidden'); end; function NSPrintSpoolJob: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintSpoolJob'); end; function NSPrintPreviewJob: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintPreviewJob'); end; function NSPrintSaveJob: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintSaveJob'); end; function NSPrintCancelJob: NSString; begin Result := CocoaNSStringConst(AppKitFwk, 'NSPrintCancelJob'); end; function TPlatformCocoa.DialogPrint(var ACollate, APrintToFile: Boolean; var AFromPage, AToPage, ACopies: Integer; AMinPage, AMaxPage: Integer; var APrintRange: TPrintRange; AOptions: TPrintDialogOptions): Boolean; var printPanel: NSPrintPanel; printInfo: NSPrintInfo; outcome : NSInteger; dict: NSMutableDictionary; begin Result := False; printInfo := TNSPrintInfo.Wrap(TNSPrintInfo.OCClass.sharedPrintInfo); printPanel := TNSPrintPanel.Wrap(TNSPrintPanel.OCClass.printPanel); dict := printInfo.dictionary; dict.setValue(TNSNumber.OCClass.numberWithBool(ACollate), NSPrintMustCollate); dict.setValue(TNSNumber.OCClass.numberWithInt(AFromPage), NSPrintFirstpage); dict.setValue(TNSNumber.OCClass.numberWithInt(AToPage), NSPrintLastPage); dict.setValue(TNSNumber.OCClass.numberWithInt(ACopies), NSPrintCopies); if APrintrange = TPrintRange.prAllPages then dict.setValue(TNSNumber.OCClass.numberWithBool(True), NSPrintAllPages); if TPrintDialogOption.poPrintToFile in AOptions then printInfo.setJobDisposition(NSPrintSaveJob); printPanel.retain; try outcome := printPanel.runModalWithPrintInfo(printInfo); if outcome = NSOKButton then begin ACollate := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintMustCollate)).boolValue(); ACopies := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintCopies)).integerValue(); if printInfo.jobDisposition = NSPrintSaveJob then APrintToFile := True; if TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintAllPages)).boolValue() = True then APrintRange := TPrintRange.prAllPages else begin APrintRange := TPrintRange.prPageNums; AFromPage := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintFirstpage)).integerValue(); AToPage := TNSNumber.Wrap(printInfo.dictionary.valueForKey(NSPrintLastPage)).integerValue(); end; Result := True; end; finally printPanel.release; end; end; function TPlatformCocoa.PageSetupGetDefaults(var AMargin, AMinMargin: TRect; var APaperSize: TPointF; AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; begin Result := False; end; function TPlatformCocoa.DialogPageSetup(var AMargin, AMinMargin :TRect; var APaperSize: TPointF; var AUnits: TPageMeasureUnits; AOptions: TPageSetupDialogOptions): Boolean; const POINTS_PER_INCHES = 72; MM_PER_INCH = 25.4; var pageSetup: NSPageLayout; printInfo: NSPrintInfo; outcome: Integer; newSize: TPointF; function ToPoints(Value: Single): Single; begin Result := Value /1000; Result := Result * POINTS_PER_INCHES; if AUnits = TPageMeasureUnits.pmMillimeters then begin Result := Result / MM_PER_INCH; end; end; function FromPoints(Value: Single): Single; begin Result := Value * 1000; Result := Result / POINTS_PER_INCHES; if AUnits = TPageMeasureUnits.pmMillimeters then begin Result := Result * MM_PER_INCH; end; end; begin Result := False; printInfo := TNSPrintInfo.Wrap(TNSPrintInfo.OCClass.sharedPrintInfo); pageSetup := TNSPageLayout.Wrap(TNSPageLayout.OCClass.pageLayout); //Calculate paper size for MAC side newSize.X := ToPoints(APaperSize.X); newSize.y := ToPoints(APaperSize.y); printInfo.setPaperSize(NSSize(newSize)); //If psoMargins is set, use the margins specified by the user, //else, let the panel use the defaults. if TPageSetupDialogOption.psoMargins in AOptions then begin printInfo.setLeftMargin(ToPoints(AMargin.Left)); printInfo.setTopMargin(ToPoints(AMargin.Top)); printInfo.setRightMargin(ToPoints(AMargin.Right)); printInfo.setBottomMargin(ToPoints(AMargin.Bottom)); end; printInfo.setHorizontallyCentered(False); printInfo.setVerticallyCentered(False); pageSetup.retain; try outcome := pageSetup.runModalWithPrintInfo(printInfo); if outcome = NSOKButton then begin APaperSize := TPointF(printInfo.paperSize); //transfrom from points into inches APaperSize.X := FromPoints(APaperSize.X); APaperSize.y := FromPoints(APaperSize.Y); // Set the margins to the values from the dialog. AMargin.Left := round(FromPoints(printInfo.LeftMargin)); AMargin.Top := round(FromPoints(printInfo.TopMargin)); AMargin.Right := round(FromPoints(printInfo.RightMargin)); AMargin.Bottom := round(FromPoints(printInfo.BottomMargin)); //if psoMinMargins is set in options, then adjust the margins to fit if TPageSetupDialogOption.psoMinMargins in AOptions then begin if AMargin.Left < AMinMargin.Left then AMargin.Left := AMinMargin.Left; if AMargin.Top < AMinMargin.Top then AMargin.Top := AMinMargin.Top; if AMargin.Right < AMinMargin.Right then AMargin.Right := AMinMargin.Right; if AMargin.Bottom < AMinMargin.Bottom then AMargin.Bottom := AMinMargin.Bottom; end; //SetPrinter(hDevMode, hDevNames) Result := True; end; finally pageSetup.release; end; end; function TPlatformCocoa.DialogPrinterSetup: Boolean; begin Result := False; end; function TPlatformCocoa.DialogSaveFiles(var AFileName: TFileName; const AInitDir, ADefaultExt, AFilter, ATitle: string; var AFilterIndex: Integer; var AFiles: TStrings; var AOptions: TOpenOptions): Boolean; var SaveFile: NSSavePanel; DefaultExt: string; Filter: NSArray; InitialDir: NSURL; outcome : NSInteger; function AllocFilterStr(const S: string): NSArray; var input, pattern: string; FileTypes: array of string; outcome, aux: TArray<string>; i, j: Integer; FileTypesNS: array of Pointer; NStr: NSString; LocObj: ILocalObject; begin // First, split the string by using '|' as a separator input := S; pattern := '\|'; outcome := TRegEx.Split(input, pattern); pattern := '\*\.'; SetLength(FileTypes, 0); for i := 0 to length(outcome) - 1 do begin if Odd(i) then if outcome[i] <> '*.*' then if AnsiLeftStr(outcome[i], 2) = '*.' then begin // Split the string by using '*.' as a separator aux := TRegEx.Split(outcome[i], pattern); for j := 0 to length(aux) - 1 do begin aux[j] := Trim(aux[j]); if aux[j] <> '' then begin //Remove the ';' if necessary if AnsiEndsStr(';', aux[j]) then aux[j] := AnsiLeftStr(aux[j], length(aux[j]) - 1); SetLength(FileTypes, length(FileTypes) + 1); FileTypes[length(FileTypes) - 1] := aux[j]; end; end; end; end; // create the NSArray from the FileTypes array SetLength(FileTypesNS, length(FileTypes)); for i := 0 to Length(FileTypes) - 1 do begin NStr := NSSTR(FileTypes[i]); if Supports(NStr, ILocalObject, LocObj) then FileTypesNS[i] := LocObj.GetObjectID; end; Result := TNSArray.Wrap(TNSArray.OCClass.arrayWithObjects(@FileTypesNS[0], length(FileTypes))); end; begin Result := False; //SaveFile := TNSSavePanel.Create; SaveFile := TNSSavePanel.Wrap(TNSSavePanel.OCClass.savePanel); if AInitDir <> '' then begin InitialDir := TNSURL.Create; InitialDir.initFileURLWithPath(NSSTR(AInitDir)); SaveFile.setDirectoryURL(InitialDir); end; if AFileName <> '' then begin SaveFile.setNameFieldStringValue(NSSTR(AFileName)); end; if AFilter <> '' then begin Filter := AllocFilterStr(AFilter); SaveFile.setAllowedFileTypes(Filter); end; if ATitle <> '' then SaveFile.setTitle(NSSTR(ATitle)); SaveFile.retain; try outcome := SaveFile.runModal; if (FModalStack <> nil) and (FModalStack.Count > 0) then FRestartModal := True; if outcome = NSOKButton then begin AFileName := UTF8ToString(SaveFile.URL.relativePath.UTF8String); if DefaultExt <> '' then if ExtractFileExt(AFileName) = '' then ChangeFileExt(AFileName, DefaultExt); Result := True; end; finally SaveFile.release; end; end; procedure TPlatformCocoa.DeleteHandle(FmxHandle: TFmxHandle); begin ValidateHandle(FmxHandle); TMonitor.Enter(FObjectiveCMap); try FObjectiveCMap.Remove(FmxHandle); finally TMonitor.Exit(FObjectiveCMap); end; end; function FmxHandleToObjC(FmxHandle: TFmxHandle): IObjectiveC; begin Result := (Platform as TPlatformCocoa).HandleToObjC(FmxHandle); end; { TFMXPanelWindow } function TFMXPanelWindow.canBecomeMainWindow: Boolean; begin Result := False; end; function TFMXPanelWindow.GetObjectiveCClass: PTypeInfo; begin Result := TypeInfo(FMXPanelWindow); end; end.
unit pCons; interface const { General constants used by most OAuth2 architectural styles for various purposes. } ExCode = 'code'; ExClientID = 'client_id'; ExClientSecret = 'client_secret'; ExRedirectURI = 'redirect_uri'; ExGrantType = 'grant_type'; ExAuthorizationCode = 'authorization_code'; ExAccessToken = 'access_token'; ExRefreshToken = 'refresh_token'; ExExpiresIn = 'expires_in'; implementation end.
unit GroupBoxImpl1; interface uses Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls, ComServ, StdVCL, AXCtrls, DelCtrls_TLB; type TGroupBoxX = class(TActiveXControl, IGroupBoxX) private { Private declarations } FDelphiControl: TGroupBox; FEvents: IGroupBoxXEvents; procedure ClickEvent(Sender: TObject); procedure DblClickEvent(Sender: TObject); protected { Protected declarations } procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitializeControl; override; function ClassNameIs(const Name: WideString): WordBool; safecall; function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall; function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall; function Get_BiDiMode: TxBiDiMode; safecall; function Get_Caption: WideString; safecall; function Get_Color: OLE_COLOR; safecall; function Get_Ctl3D: WordBool; safecall; function Get_Cursor: Smallint; safecall; function Get_DockSite: WordBool; safecall; function Get_DoubleBuffered: WordBool; safecall; function Get_DragCursor: Smallint; safecall; function Get_DragMode: TxDragMode; safecall; function Get_Enabled: WordBool; safecall; function Get_Font: IFontDisp; safecall; function Get_ParentColor: WordBool; safecall; function Get_ParentCtl3D: WordBool; safecall; function Get_ParentFont: WordBool; safecall; function Get_Visible: WordBool; safecall; function GetControlsAlignment: TxAlignment; safecall; function IsRightToLeft: WordBool; safecall; function UseRightToLeftAlignment: WordBool; safecall; function UseRightToLeftReading: WordBool; safecall; function UseRightToLeftScrollBar: WordBool; safecall; procedure _Set_Font(const Value: IFontDisp); safecall; procedure AboutBox; safecall; procedure FlipChildren(AllLevels: WordBool); safecall; procedure InitiateAction; safecall; procedure Set_BiDiMode(Value: TxBiDiMode); safecall; procedure Set_Caption(const Value: WideString); safecall; procedure Set_Color(Value: OLE_COLOR); safecall; procedure Set_Ctl3D(Value: WordBool); safecall; procedure Set_Cursor(Value: Smallint); safecall; procedure Set_DockSite(Value: WordBool); safecall; procedure Set_DoubleBuffered(Value: WordBool); safecall; procedure Set_DragCursor(Value: Smallint); safecall; procedure Set_DragMode(Value: TxDragMode); safecall; procedure Set_Enabled(Value: WordBool); safecall; procedure Set_Font(const Value: IFontDisp); safecall; procedure Set_ParentColor(Value: WordBool); safecall; procedure Set_ParentCtl3D(Value: WordBool); safecall; procedure Set_ParentFont(Value: WordBool); safecall; procedure Set_Visible(Value: WordBool); safecall; end; implementation uses ComObj, About12; { TGroupBoxX } procedure TGroupBoxX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); begin { Define property pages here. Property pages are defined by calling DefinePropertyPage with the class id of the page. For example, DefinePropertyPage(Class_GroupBoxXPage); } end; procedure TGroupBoxX.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IGroupBoxXEvents; end; procedure TGroupBoxX.InitializeControl; begin FDelphiControl := Control as TGroupBox; FDelphiControl.OnClick := ClickEvent; FDelphiControl.OnDblClick := DblClickEvent; end; function TGroupBoxX.ClassNameIs(const Name: WideString): WordBool; begin Result := FDelphiControl.ClassNameIs(Name); end; function TGroupBoxX.DrawTextBiDiModeFlags(Flags: Integer): Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlags(Flags); end; function TGroupBoxX.DrawTextBiDiModeFlagsReadingOnly: Integer; begin Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly; end; function TGroupBoxX.Get_BiDiMode: TxBiDiMode; begin Result := Ord(FDelphiControl.BiDiMode); end; function TGroupBoxX.Get_Caption: WideString; begin Result := WideString(FDelphiControl.Caption); end; function TGroupBoxX.Get_Color: OLE_COLOR; begin Result := OLE_COLOR(FDelphiControl.Color); end; function TGroupBoxX.Get_Ctl3D: WordBool; begin Result := FDelphiControl.Ctl3D; end; function TGroupBoxX.Get_Cursor: Smallint; begin Result := Smallint(FDelphiControl.Cursor); end; function TGroupBoxX.Get_DockSite: WordBool; begin Result := FDelphiControl.DockSite; end; function TGroupBoxX.Get_DoubleBuffered: WordBool; begin Result := FDelphiControl.DoubleBuffered; end; function TGroupBoxX.Get_DragCursor: Smallint; begin Result := Smallint(FDelphiControl.DragCursor); end; function TGroupBoxX.Get_DragMode: TxDragMode; begin Result := Ord(FDelphiControl.DragMode); end; function TGroupBoxX.Get_Enabled: WordBool; begin Result := FDelphiControl.Enabled; end; function TGroupBoxX.Get_Font: IFontDisp; begin GetOleFont(FDelphiControl.Font, Result); end; function TGroupBoxX.Get_ParentColor: WordBool; begin Result := FDelphiControl.ParentColor; end; function TGroupBoxX.Get_ParentCtl3D: WordBool; begin Result := FDelphiControl.ParentCtl3D; end; function TGroupBoxX.Get_ParentFont: WordBool; begin Result := FDelphiControl.ParentFont; end; function TGroupBoxX.Get_Visible: WordBool; begin Result := FDelphiControl.Visible; end; function TGroupBoxX.GetControlsAlignment: TxAlignment; begin Result := TxAlignment(FDelphiControl.GetControlsAlignment); end; function TGroupBoxX.IsRightToLeft: WordBool; begin Result := FDelphiControl.IsRightToLeft; end; function TGroupBoxX.UseRightToLeftAlignment: WordBool; begin Result := FDelphiControl.UseRightToLeftAlignment; end; function TGroupBoxX.UseRightToLeftReading: WordBool; begin Result := FDelphiControl.UseRightToLeftReading; end; function TGroupBoxX.UseRightToLeftScrollBar: WordBool; begin Result := FDelphiControl.UseRightToLeftScrollBar; end; procedure TGroupBoxX._Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TGroupBoxX.AboutBox; begin ShowGroupBoxXAbout; end; procedure TGroupBoxX.FlipChildren(AllLevels: WordBool); begin FDelphiControl.FlipChildren(AllLevels); end; procedure TGroupBoxX.InitiateAction; begin FDelphiControl.InitiateAction; end; procedure TGroupBoxX.Set_BiDiMode(Value: TxBiDiMode); begin FDelphiControl.BiDiMode := TBiDiMode(Value); end; procedure TGroupBoxX.Set_Caption(const Value: WideString); begin FDelphiControl.Caption := TCaption(Value); end; procedure TGroupBoxX.Set_Color(Value: OLE_COLOR); begin FDelphiControl.Color := TColor(Value); end; procedure TGroupBoxX.Set_Ctl3D(Value: WordBool); begin FDelphiControl.Ctl3D := Value; end; procedure TGroupBoxX.Set_Cursor(Value: Smallint); begin FDelphiControl.Cursor := TCursor(Value); end; procedure TGroupBoxX.Set_DockSite(Value: WordBool); begin FDelphiControl.DockSite := Value; end; procedure TGroupBoxX.Set_DoubleBuffered(Value: WordBool); begin FDelphiControl.DoubleBuffered := Value; end; procedure TGroupBoxX.Set_DragCursor(Value: Smallint); begin FDelphiControl.DragCursor := TCursor(Value); end; procedure TGroupBoxX.Set_DragMode(Value: TxDragMode); begin FDelphiControl.DragMode := TDragMode(Value); end; procedure TGroupBoxX.Set_Enabled(Value: WordBool); begin FDelphiControl.Enabled := Value; end; procedure TGroupBoxX.Set_Font(const Value: IFontDisp); begin SetOleFont(FDelphiControl.Font, Value); end; procedure TGroupBoxX.Set_ParentColor(Value: WordBool); begin FDelphiControl.ParentColor := Value; end; procedure TGroupBoxX.Set_ParentCtl3D(Value: WordBool); begin FDelphiControl.ParentCtl3D := Value; end; procedure TGroupBoxX.Set_ParentFont(Value: WordBool); begin FDelphiControl.ParentFont := Value; end; procedure TGroupBoxX.Set_Visible(Value: WordBool); begin FDelphiControl.Visible := Value; end; procedure TGroupBoxX.ClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnClick; end; procedure TGroupBoxX.DblClickEvent(Sender: TObject); begin if FEvents <> nil then FEvents.OnDblClick; end; initialization TActiveXControlFactory.Create( ComServer, TGroupBoxX, TGroupBox, Class_GroupBoxX, 12, '{695CDB31-02E5-11D2-B20D-00C04FA368D4}', OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL, tmApartment); end.
unit Xml.Internal.UriUtils; // UriUtils 1.0.3 // Delphi 4 to 2009 and Kylix 3 Implementation // September 2008 // // // LICENSE // // 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 Original Code is "UriUtils.pas". // // The Initial Developer of the Original Code is Dieter Köhler (Heidelberg, // Germany, "http://www.philo.de/"). Portions created by the Initial Developer // are Copyright (C) 2003-2008 Dieter Köhler. All Rights Reserved. // // Alternatively, the contents of this file may be used under the terms of the // GNU General Public License Version 2 or later (the "GPL"), in which case the // provisions of the GPL are applicable instead of those above. If you wish to // allow use of your version of this file only under the terms of the GPL, 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 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 or the GPL. // HISTORY // // 2008-09-28 1.0.3 Internal modifications. // 2007-12-03 1.0.2 Made .NET compliant. Minor internal modifications. // 2007-07-05 1.0.1 Support for Linux filenames under Kylix added. // 2003-08-03 1.0.0 interface uses System.SysUtils; // URI Rules (cf. RFC 2396, App. A) {$IFNDEF NEXTGEN} function IsUriURI_referenceWideStr(S: WideString): Boolean; function IsUriAbsoluteURIWideStr(S: WideString): Boolean; function IsUriRelativeURIWideStr(S: WideString): Boolean; function IsUriHier_partWideStr(S: WideString): Boolean; function IsUriOpaque_partWideStr(S: WideString): Boolean; function IsUriNet_pathWideStr(S: WideString): Boolean; function IsUriAbs_pathWideStr(S: WideString): Boolean; function IsUriRel_pathWideStr(S: WideString): Boolean; function IsUriRel_segmentWideStr(S: WideString): Boolean; function IsUriSchemeWideStr(S: WideString): Boolean; function IsUriAuthorityWideStr(S: WideString): Boolean; function IsUriReg_nameWideStr(S: WideString): Boolean; function IsUriServerWideStr(S: WideString): Boolean; function IsUriUserinfoWideStr(S: WideString): Boolean; function IsUriHostPortWideStr(S: WideString): Boolean; function IsUriHostWideStr(S: WideString): Boolean; function IsUriHostnameWideStr(S: WideString): Boolean; function IsUriDomainlabelWideStr(S: WideString): Boolean; function IsUriToplabelWideStr(S: WideString): Boolean; function IsUriIPv4addressWideStr(S: WideString): Boolean; function IsUriPortWideStr(S: WideString): Boolean; function IsUriPathWideStr(S: WideString): Boolean; function IsUriPath_segmentsWideStr(S: WideString): Boolean; function IsUriSegmentWideStr(S: WideString): Boolean; function IsUriParamWideStr(S: WideString): Boolean; function IsUriQueryWideStr(S: WideString): Boolean; function IsUriFragmentWideStr(S: WideString): Boolean; function IsUriUricWideStr(S: WideString): Boolean; function IsUriReservedWideChar(C: WideChar): Boolean; function IsUriUnreservedWideChar(C: WideChar): Boolean; function IsUriMarkWideChar(C: WideChar): Boolean; function IsUriHexWideChar(C: WideChar): Boolean; function IsUriAlphanumWideChar(C: WideChar): Boolean; function IsUriAlphaWideChar(C: WideChar): Boolean; function IsUriDigitWideChar(C: WideChar): Boolean; {$ENDIF NEXTGEN} function IsUriURI_referenceStr(S: string): Boolean; function IsUriAbsoluteURIStr(S: string): Boolean; function IsUriRelativeURIStr(S: string): Boolean; function IsUriHier_partStr(S: string): Boolean; function IsUriOpaque_partStr(S: string): Boolean; function IsUriNet_pathStr(S: string): Boolean; function IsUriAbs_pathStr(S: string): Boolean; function IsUriRel_pathStr(S: string): Boolean; function IsUriRel_segmentStr(S: string): Boolean; function IsUriSchemeStr(S: string): Boolean; function IsUriAuthorityStr(S: string): Boolean; function IsUriReg_nameStr(S: string): Boolean; function IsUriServerStr(S: string): Boolean; function IsUriUserinfoStr(S: string): Boolean; function IsUriHostPortStr(S: string): Boolean; function IsUriHostStr(S: string): Boolean; function IsUriHostnameStr(S: string): Boolean; function IsUriDomainlabelStr(S: string): Boolean; function IsUriToplabelStr(S: string): Boolean; function IsUriIPv4addressStr(S: string): Boolean; function IsUriPortStr(S: string): Boolean; function IsUriPathStr(S: string): Boolean; function IsUriPath_segmentsStr(S: string): Boolean; function IsUriSegmentStr(S: string): Boolean; function IsUriParamStr(S: string): Boolean; function IsUriQueryStr(S: string): Boolean; function IsUriFragmentStr(S: string): Boolean; function IsUriUricStr(S: string): Boolean; function IsUriReservedChar(C: Char): Boolean; function IsUriUnreservedChar(C: Char): Boolean; function IsUriMarkChar(C: Char): Boolean; function IsUriHexChar(C: Char): Boolean; function IsUriAlphanumChar(C: Char): Boolean; function IsUriAlphaChar(C: Char): Boolean; function IsUriDigitChar(C: Char): Boolean; // URI conversion functions type TUtilsFilenameToUriOptions = set of (fuSetLocalhost, fuPlainColon); {$IFNDEF NEXTGEN} function FilenameToUriWideStr(const Path: TFilename; const Opt: TUtilsFilenameToUriOptions): WideString; function ResolveRelativeUriWideStr(const BaseUri, RelUri: WideString; var ResultUri: WideString): Boolean; function UriWideStrToFilename(const Uri: WideString; var Path: TFilename; var Authority, Query, Fragment: WideString): Boolean; {$ENDIF NEXTGEN} function FilenameToUriStr(const Path: TFilename; const Opt: TUtilsFilenameToUriOptions): string; function ResolveRelativeUriStr(const BaseUri, RelUri: string; var ResultUri: string): Boolean; function UriStrToFilename(const Uri: string; var Path: TFilename; var Authority, Query, Fragment: string): Boolean; // URI analysis type TUriStrAnalyzer = class protected FUriAuthority: string; FUriFragment: string; FUriQuery: string; FUriPath: string; FUriScheme: string; FHasUriAuthority: Boolean; FHasUriFragment: Boolean; FHasUriQuery: Boolean; FHasUriScheme: Boolean; function GetUriReference: string; virtual; public constructor Create; function SetUriAuthority(const Value: string; const IsDefined: Boolean): Boolean; virtual; function SetUriFragment(const Value: string; const IsDefined: Boolean): Boolean; virtual; function SetUriPath(const Value: string): Boolean; virtual; function SetUriQuery(const Value: string; const IsDefined: Boolean): Boolean; virtual; function SetUriReference(const Value: string): Boolean; virtual; function SetUriScheme(const Value: string; const IsDefined: Boolean): Boolean; virtual; property HasUriAuthority: Boolean read FHasUriAuthority; property HasUriFragment: Boolean read FHasUriFragment; property HasUriQuery: Boolean read FHasUriQuery; property HasUriScheme: Boolean read FHasUriScheme; property UriAuthority: string read FUriAuthority; property UriFragment: string read FUriFragment; property UriPath: string read FUriPath; property UriQuery: string read FUriQuery; property UriReference: string read GetUriReference; property UriScheme: string read FUriScheme; end; {$IFNDEF NEXTGEN} TUriWideStrAnalyzer = class protected FUriAuthority: WideString; FUriFragment: WideString; FUriQuery: WideString; FUriPath: WideString; FUriScheme: WideString; FHasUriAuthority: Boolean; FHasUriFragment: Boolean; FHasUriQuery: Boolean; FHasUriScheme: Boolean; function GetUriReference: WideString; virtual; public constructor Create; function SetUriAuthority(const Value: WideString; const IsDefined: Boolean): Boolean; virtual; function SetUriFragment(const Value: WideString; const IsDefined: Boolean): Boolean; virtual; function SetUriPath(const Value: WideString): Boolean; virtual; function SetUriQuery(const Value: WideString; const IsDefined: Boolean): Boolean; virtual; function SetUriReference(const Value: WideString): Boolean; virtual; function SetUriScheme(const Value: WideString; const IsDefined: Boolean): Boolean; virtual; property HasUriAuthority: Boolean read FHasUriAuthority; property HasUriFragment: Boolean read FHasUriFragment; property HasUriQuery: Boolean read FHasUriQuery; property HasUriScheme: Boolean read FHasUriScheme; property UriAuthority: WideString read FUriAuthority; property UriFragment: WideString read FUriFragment; property UriPath: WideString read FUriPath; property UriQuery: WideString read FUriQuery; property UriReference: WideString read GetUriReference; property UriScheme: WideString read FUriScheme; end; {$ENDIF NEXTGEN} implementation uses {$IFNDEF NEXTGEN} Xml.Internal.WideStringUtils, {$ENDIF NEXTGEN} Xml.Internal.AbnfUtils, System.Classes; {$IF CompilerVersion >= 24.0} const FirstIndex = Low(string); AdjustIndex = 1-Low(string); {$ELSE} const FirstIndex = 1; AdjustIndex = 0; {$ENDIF} {$IFNDEF NEXTGEN} function IsUriURI_referenceWideStr(S: WideString): Boolean; var DcPos: Integer; S1: string; begin DcPos := Pos('#', S); if DcPos > 0 then begin S1 := Copy(S, 1, DcPos - 1); Result := (IsUriAbsoluteURIWideStr(S1) or IsUriRelativeURIWideStr(S1) or (S1 = '')) and IsUriFragmentWideStr(Copy(S, DcPos + 1, length(S) - DcPos)); end else Result := IsUriAbsoluteURIWideStr(S) or IsUriRelativeURIWideStr(S) or (S = ''); end; function IsUriAbsoluteURIWideStr(S: WideString): Boolean; var ColonPos: Integer; S1: string; begin ColonPos := Pos(':', S); if ColonPos > 0 then begin S1 := Copy(S, ColonPos + 1, Length(S) - ColonPos); Result := IsUriSchemeWideStr(Copy(S, 1, ColonPos - 1)) and (IsUriHier_partWideStr(S1) or IsUriOpaque_partWideStr(S1)); end else Result := False; end; function IsUriRelativeURIWideStr(S: WideString): Boolean; var QmPos: Integer; S1: string; begin QmPos := Pos(#63, S); if QmPos > 0 then begin S1 := Copy(S, 1, QmPos - 1); Result := (IsUriNet_PathWideStr(S1) or IsUriAbs_PathWideStr(S1) or IsUriRel_PathWideStr(S1)) and IsUriQueryWideStr(Copy(S, QmPos + 1, Length(S) - QmPos)); end else Result := IsUriNet_PathWideStr(S) or IsUriAbs_PathWideStr(S) or IsUriRel_PathWideStr(S); end; function IsUriHier_partWideStr(S: WideString): Boolean; var QmPos: Integer; S1: string; begin QmPos := Pos(#63, S); if QmPos > 0 then begin S1 := Copy(S, 1, QmPos - 1); Result := (IsUriNet_PathWideStr(S1) or IsUriAbs_PathWideStr(S1)) and IsUriQueryWideStr(Copy(S, QmPos + 1, Length(S) - QmPos)); end else Result := IsUriNet_PathWideStr(S) or IsUriAbs_PathWideStr(S); end; function IsUriOpaque_partWideStr(S: WideString): Boolean; begin if S = '' then begin Result := False; Exit; end; if S[1] = '/' then begin Result := False; Exit; end; Result := IsUriUricWideStr(S); end; function IsUriNet_PathWideStr(S: WideString): Boolean; var SlashPos: Integer; begin if Copy(S, 1, 2) <> '//' then begin Result := False; Exit; end; S := Copy(S, 3, Length(S) - 2); SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := IsUriAuthorityWideStr(Copy(S, 1, SlashPos - 1)) and IsUriAbs_PathWideStr(Copy(S, SlashPos, Length(S) - SlashPos + 1)); end else Result := IsUriAuthorityWideStr(S); end; function IsUriAbs_PathWideStr(S: WideString): Boolean; begin if S = '' then begin Result := False; Exit; end; if S[1] <> '/' then begin Result := False; Exit; end; Result := IsUriPath_segmentsWideStr(Copy(S, 2, Length(S) - 1)); end; function IsUriRel_PathWideStr(S: WideString): Boolean; var SlashPos: Integer; begin SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := IsUriRel_segmentWideStr(Copy(S, 1, SlashPos - 1)) and IsUriAbs_PathWideStr(Copy(S, SlashPos, Length(S) - SlashPos + 1)); end else Result := IsUriRel_segmentWideStr(S); end; function IsUriRel_segmentWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; Result := True; I := 0; while I < L do begin Inc(I); if S[I-AdjustIndex] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I-AdjustIndex]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I-AdjustIndex]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I-AdjustIndex]) or (S[I-AdjustIndex] = ';') or (S[I-AdjustIndex] = '@') or (S[I-AdjustIndex] = '&') or (S[I-AdjustIndex] = '=') or (S[I-AdjustIndex] = '+') or (S[I-AdjustIndex] = '$') or (S[I-AdjustIndex] = ',')) then begin Result := False; Exit; end; end; end; function IsUriSchemeWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; if not IsAbnfALPHAWideChar(S[FirstIndex]) then begin Result := False; Exit; end; Result := True; for I := 1+FirstIndex to L-AdjustIndex do if not (isAbnfALPHAWideChar(S[I]) or isAbnfDIGITWideChar(S[I]) or (S[I] = '+') or (S[I] = '-') or (S[I] = '.') ) then begin Result := False; Exit; end; end; function IsUriAuthorityWideStr(S: WideString): Boolean; begin Result := IsUriServerWideStr(S) or IsUriReg_nameWideStr(S); end; function IsUriReg_nameWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; Result := True; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I]) or (S[I] = '$') or (S[I] = ',') or (S[I] = ';') or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+')) then begin Result := False; Exit; end; end; end; function IsUriServerWideStr(S: WideString): Boolean; var AtPos, L: Integer; begin L := Length(S); if L = 0 then begin Result := True; Exit; end; AtPos := Pos('@', S); if AtPos > 0 then begin Result := IsUriUserinfoWideStr(Copy(S, 1, AtPos - 1)) and IsUriHostportWideStr(Copy(S, AtPos + 1, L - AtPos)); end else Result := IsUriHostportWideStr(S); end; function IsUriUserinfoWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I]) or (S[I] = ';') or (S[I] = ':') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',')) then begin Result := False; Exit; end; end; end; function IsUriHostPortWideStr(S: WideString): Boolean; var ColonPos: Integer; begin ColonPos := Pos(':', S); if ColonPos > 0 then begin Result := IsUriHostWideStr(Copy(S, 1, ColonPos - 1)) and IsUriPortWideStr(Copy(S, ColonPos + 1, Length(S) - ColonPos)); end else Result := IsUriHostWideStr(S); end; function IsUriHostWideStr(S: WideString): Boolean; begin Result := IsUriHostnameWideStr(S) or IsUriIPv4addressWideStr(S); end; function IsUriHostnameWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; Result := True; if S[L-AdjustIndex] = '.' then Dec(L); I := L; while I > 0 do begin if S[I-AdjustIndex] = '.' then break; Dec(I); end; if not IsUriToplabelWideStr(Copy(S, I + 1, L - I)) then begin Result := False; Exit; end; while I > 0 do begin L := I; if S[L-AdjustIndex] = '.' then Dec(L); I := L; while I > 0 do begin if S[I-AdjustIndex] = '.' then break; Dec(I); end; if not IsUriDomainlabelWideStr(Copy(S, I + 1, L - I)) then begin Result := False; Exit; end; end; end; function IsUriDomainlabelWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; if not (IsUriAlphanumWideChar(S[FirstIndex]) and IsUriAlphanumWideChar(S[L-AdjustIndex])) then begin Result := False; Exit; end; Result := True; I := FirstIndex; while I < L-AdjustIndex do begin Inc(I); if not (isUriAlphanumWideChar(S[I]) or (S[I] = '-')) then begin Result := False; Exit; end; end; end; function IsUriToplabelWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; if not (IsUriAlphaWideChar(S[FirstIndex]) and IsUriAlphanumWideChar(S[L-AdjustIndex])) then begin Result := False; Exit; end; Result := True; I := FirstIndex; while I < L-AdjustIndex do begin Inc(I); if not (isUriAlphanumWideChar(S[I]) or (S[I] = '-')) then begin Result := False; Exit; end; end; end; function IsUriIPv4addressWideStr(S: WideString): Boolean; var digitNo, colonNo, I, L: Integer; digitFound: Boolean; begin Result := False; L := Length(S); I := 0; digitNo := 0; colonNo := 0; digitFound := False; while I < L do begin if IsUriDigitWideChar(S[I]) then begin if not digitFound then begin digitFound := True; Inc(digitNo); end; end else if S[I] = '.' then begin if not digitFound then Exit; digitFound := False; Inc(colonNo); end else Exit; end; if (colonNo = 3) and (digitNo = 4) then Result := True; end; function IsUriPortWideStr(S: WideString): Boolean; var I, L: Integer; begin Result := True; L := Length(S); for I := FirstIndex to L-AdjustIndex do if not IsUriDigitWideChar(S[I]) then begin Result := False; Exit; end; end; function IsUriPathWideStr(S: WideString): Boolean; begin if IsUriAbs_PathWideStr(S) or IsUriOpaque_partWideStr(S) or (S = '') then Result := True else Result := False; end; function IsUriPath_segmentsWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',') or (S[I] = ';') or (S[I] = '/')) then begin Result := False; Exit; end; end; end; function IsUriSegmentWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',') or (S[I] = ';')) then begin Result := False; Exit; end; end; end; function IsUriParamWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedWideChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',')) then begin Result := False; Exit; end; end; end; function IsUriQueryWideStr(S: WideString): Boolean; begin if S = '' then Result := True else Result := IsUriUricWideStr(S); end; function IsUriFragmentWideStr(S: WideString): Boolean; begin if S = '' then Result := True else Result := IsUriUricWideStr(S); end; function IsUriUricWideStr(S: WideString): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end else Result := True; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexWideChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriReservedWideChar(S[I]) or IsUriUnreservedWideChar(S[I])) then begin Result := False; Exit; end; end; end; function IsUriReservedWideChar(C: WideChar): Boolean; begin if (C = ';') or (C = '/') or (C = #63) or (C = ':') or (C = '@') or (C = '&') or (C = '=') or (C = '+') or (C = '$') or (C = ',') then Result := True else Result := False; end; function IsUriUnreservedWideChar(C: WideChar): Boolean; begin if IsUriAlphanumWideChar(C) or IsUriMarkWideChar(C) then Result := True else Result := False; end; function IsUriMarkWideChar(C: WideChar): Boolean; begin if (C = '-') or (C = '_') or (C = '.') or (C = '!') or (C = '~') or (C = '*') or (C = #39) or (C = '(') or (C = ')') then Result := True else Result := False; end; function IsUriHexWideChar(C: WideChar): Boolean; begin case Word(C) of $0030..$0039, $0041..$0046, $0061..$0066: // 0..9 , A..F , a..f Result := True; else Result := False; end; end; function IsUriAlphanumWideChar(C: WideChar): Boolean; begin case Word(C) of $0030..$0039, $0041..$005A, $0061..$007A: Result := True; else Result := False; end; end; function IsUriAlphaWideChar(C: WideChar): Boolean; begin case Word(C) of $0041..$005A, $0061..$007A: Result := True; else Result := False; end; end; function IsUriDigitWideChar(C: WideChar): Boolean; begin case Word(C) of $0030..$0039: Result := True; else Result := False; end; end; {$ENDIF NEXTGEN} function IsUriURI_referenceStr(S: string): Boolean; var DcPos: Integer; S1: string; begin DcPos := Pos('#', S); if DcPos > 0 then begin S1 := Copy(S, 1, DcPos - 1); Result := (IsUriAbsoluteURIStr(S1) or IsUriRelativeURIStr(S1) or (S1 = '')) and IsUriFragmentStr(Copy(S, DcPos + 1, Length(S) - DcPos)); end else Result := IsUriAbsoluteURIStr(S) or IsUriRelativeURIStr(S) or (S = ''); end; function IsUriAbsoluteURIStr(S: string): Boolean; var ColonPos: Integer; S1: string; begin ColonPos := Pos(':', S); if ColonPos > 0 then begin S1 := Copy(S, ColonPos + 1, Length(S) - ColonPos); Result := IsUriSchemeStr(Copy(S, 1, ColonPos - 1)) and (IsUriHier_partStr(S1) or IsUriOpaque_partStr(S1)); end else Result := False; end; function IsUriRelativeURIStr(S: string): Boolean; var QmPos: Integer; S1: string; begin QmPos := Pos('?', S); if QmPos > 0 then begin S1 := Copy(S, 1, QmPos - 1); Result := (IsUriNet_PathStr(S1) or IsUriAbs_PathStr(S1) or IsUriRel_PathStr(S1)) and IsUriQueryStr(Copy(S, QmPos + 1, Length(S) - QmPos)); end else Result := IsUriNet_PathStr(S) or IsUriAbs_PathStr(S) or IsUriRel_PathStr(S); end; function IsUriHier_partStr(S: string): Boolean; var QmPos: Integer; S1: string; begin QmPos := Pos('?', S); if QmPos > 0 then begin S1 := Copy(S, 1, QmPos - 1); Result := (IsUriNet_PathStr(S1) or IsUriAbs_PathStr(S1)) and IsUriQueryStr(Copy(S, QmPos + 1, Length(S) - QmPos)); end else Result := IsUriNet_PathStr(S) or IsUriAbs_PathStr(S); end; function IsUriOpaque_partStr(S: string): Boolean; begin if S = '' then begin Result := False; Exit; end; if S[FirstIndex] = '/' then begin Result := False; Exit; end; Result := IsUriUricStr(S); end; function IsUriNet_PathStr(S: string): Boolean; var SlashPos: Integer; begin if Copy(S, 1, 2) <> '//' then begin Result := False; Exit; end; S := Copy(S, 3, Length(S) - 2); SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := IsUriAuthorityStr(Copy(S, 1, SlashPos - 1)) and IsUriAbs_PathStr(Copy(S, SlashPos, Length(S) - SlashPos + 1)); end else Result := IsUriAuthorityStr(S); end; function IsUriAbs_PathStr(S: string): Boolean; begin if S = '' then begin Result := False; Exit; end; if S[FirstIndex] <> '/' then begin Result := False; Exit; end; Result := IsUriPath_segmentsStr(Copy(S, 2, Length(S) - 1)); end; function IsUriRel_PathStr(S: string): Boolean; var SlashPos: Integer; begin SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := IsUriRel_segmentStr(Copy(S, 1, SlashPos - 1)) and IsUriAbs_PathStr(Copy(S, SlashPos, Length(S) - SlashPos + 1)); end else Result := IsUriRel_segmentStr(S); end; function IsUriRel_segmentStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; Result := True; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = ';') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',')) then begin Result := False; Exit; end; end; end; function IsUriSchemeStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; if not isAbnfALPHAChar(S[FirstIndex]) then begin Result := False; Exit; end; Result := True; for I := 1+FirstIndex to L-AdjustIndex do if not (isAbnfALPHAChar(S[I]) or isAbnfDIGITChar(S[I]) or (S[I] = '+') or (S[I] = '-') or (S[I] = '.') ) then begin Result := False; Exit; end; end; function IsUriAuthorityStr(S: string): Boolean; begin Result := IsUriServerStr(S) or IsUriReg_nameStr(S); end; function IsUriReg_nameStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; Result := True; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = '$') or (S[I] = ',') or (S[I] = ';') or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+')) then begin Result := False; Exit; end; end; end; function IsUriServerStr(S: string): Boolean; var AtPos, L: Integer; begin L := Length(S); if L = 0 then begin Result := True; Exit; end; AtPos := Pos('@', S); if AtPos > 0 then begin Result := IsUriUserinfoStr(Copy(S, 1, AtPos - 1)) and IsUriHostportStr(Copy(S, AtPos + 1, L - AtPos)); end else Result := IsUriHostportStr(S); end; function IsUriUserinfoStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = ';') or (S[I] = ':') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',')) then begin Result := False; Exit; end; end; end; function IsUriHostPortStr(S: string): Boolean; var ColonPos: Integer; begin ColonPos := Pos(':', S); if ColonPos > 0 then begin Result := IsUriHostStr(Copy(S, 1, ColonPos - 1)) and IsUriPortStr(Copy(S, ColonPos + 1, Length(S) - ColonPos)); end else Result := IsUriHostStr(S); end; function IsUriHostStr(S: string): Boolean; begin Result := IsUriHostnameStr(S) or IsUriIPv4addressStr(S); end; function IsUriHostnameStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; L := L-AdjustIndex; Result := True; if S[L] = '.' then Dec(L); I := L; while I >= FirstIndex do begin if S[I] = '.' then break; Dec(I); end; if not IsUriToplabelStr(Copy(S, I + 1+FirstIndex, L - I)) then begin Result := False; Exit; end; while I >= FirstIndex do begin L := I; if S[L] = '.' then Dec(L); I := L; while I >= FirstIndex do begin if S[I] = '.' then break; Dec(I); end; if not IsUriDomainlabelStr(Copy(S, I + 1+FirstIndex, L - I)) then begin Result := False; Exit; end; end; end; function IsUriDomainlabelStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; L := L - AdjustIndex; if not (IsUriAlphanumChar(S[FirstIndex]) and IsUriAlphanumChar(S[L])) then begin Result := False; Exit; end; Result := True; I := FirstIndex; while I < L do begin Inc(I); if not (isUriAlphanumChar(S[I]) or (S[I] = '-')) then begin Result := False; Exit; end; end; end; function IsUriToplabelStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end; L := L - AdjustIndex; if not (IsUriAlphaChar(S[FirstIndex]) and IsUriAlphanumChar(S[L])) then begin Result := False; Exit; end; Result := True; I := FirstIndex; while I < L do begin Inc(I); if not (isUriAlphanumChar(S[I]) or (S[I] = '-')) then begin Result := False; Exit; end; end; end; function IsUriIPv4addressStr(S: string): Boolean; var DigitNo, ColonNo, I, L: Integer; DigitFound: Boolean; begin Result := False; L := Length(S) - AdjustIndex; I := FirstIndex;//0; DigitNo := 0; ColonNo := 0; DigitFound := False; while I < L do begin if IsUriDigitChar(S[I]) then begin if not DigitFound then begin DigitFound := True; Inc(DigitNo); end; end else if S[I] = '.' then begin if not DigitFound then Exit; DigitFound := False; Inc(ColonNo); end else Exit; end; if (ColonNo = 3) and (DigitNo = 4) then Result := True; end; function IsUriPortStr(S: string): Boolean; var I, L: Integer; begin Result := True; L := Length(S) - AdjustIndex; for I := FirstIndex to L do if not IsUriDigitChar(S[I]) then begin Result := False; Exit; end; end; function IsUriPathStr(S: string): Boolean; begin if IsUriAbs_PathStr(S) or IsUriOpaque_partStr(S) or (S = '') then Result := True else Result := False; end; function IsUriPath_segmentsStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',') or (S[I] = ';') or (S[I] = '/')) then begin Result := False; Exit; end; end; end; function IsUriSegmentStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',') or (S[I] = ';')) then begin Result := False; Exit; end; end; end; function IsUriParamStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); Result := True; if L = 0 then Exit; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriUnreservedChar(S[I]) or (S[I] = ':') or (S[I] = '@') or (S[I] = '&') or (S[I] = '=') or (S[I] = '+') or (S[I] = '$') or (S[I] = ',')) then begin Result := False; Exit; end; end; end; function IsUriQueryStr(S: string): Boolean; begin if S = '' then Result := True else Result := IsUriUricStr(S); end; function IsUriFragmentStr(S: string): Boolean; begin if S = '' then Result := True else Result := IsUriUricStr(S); end; function IsUriUricStr(S: string): Boolean; var I, L: Integer; begin L := Length(S); if L = 0 then begin Result := False; Exit; end else Result := True; I := FirstIndex - 1; L := L - AdjustIndex; while I < L do begin Inc(I); if S[I] = '%' then begin if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; if I = L then begin Result := False; Exit; end; Inc(I); if not IsUriHexChar(S[I]) then begin Result := False; Exit; end; end else if not (IsUriReservedChar(S[I]) or IsUriUnreservedChar(S[I])) then begin Result := False; Exit; end; end; end; function IsUriReservedChar(C: Char): Boolean; begin if (C = ';') or (C = '/') or (C = '?') or (C = ':') or (C = '@') or (C = '&') or (C = '=') or (C = '+') or (C = '$') or (C = ',') then Result := True else Result := False; end; function IsUriUnreservedChar(C: Char): Boolean; begin if IsUriAlphanumChar(C) or IsUriMarkChar(C) then Result := True else Result := False; end; function IsUriMarkChar(C: Char): Boolean; begin if (C = '-') or (C = '_') or (C = '.') or (C = '!') or (C = '~') or (C = '*') or (C = #39) or (C = '(') or (C = ')') then Result := True else Result := False; end; function IsUriHexChar(C: Char): Boolean; begin case Byte(C) of $30..$39, $41..$46, $61..$66: // 0..9 , A..F , a..f Result := True; else Result := False; end; end; function IsUriAlphanumChar(C: Char): Boolean; begin case Byte(C) of $30..$39, $41..$5A, $61..$7A: Result := True; else Result := False; end; end; function IsUriAlphaChar(C: Char): Boolean; begin case Byte(C) of $41..$5A, $61..$7A: Result := True; else Result := False; end; end; function IsUriDigitChar(C: Char): Boolean; begin case Byte(C) of $30..$39: Result := True; else Result := False; end; end; function ResolveRelativeUriStr(const BaseUri, RelUri: string; var ResultUri: string): Boolean; var BaseUriAnalyzer, RelUriAnalyzer: TUriStrAnalyzer; I, SlashPos, QueryIndex: Integer; PathBuffer: string; Segments: TStringList; begin ResultUri := ''; BaseUriAnalyzer := TUriStrAnalyzer.Create; RelUriAnalyzer := TUriStrAnalyzer.Create; try Result := BaseUriAnalyzer.SetUriReference(BaseUri); Result := (RelUriAnalyzer.SetUriReference(RelUri) and Result); Result := ((BaseUriAnalyzer.HasUriScheme or RelUriAnalyzer.HasUriScheme) and Result); if not Result then Exit; // BaseUri is not an absolute URI reference, or BaseUri or RelUri is malformed if (RelUriAnalyzer.UriPath = '') and not (RelUriAnalyzer.HasUriScheme or RelUriAnalyzer.HasUriAuthority or RelUriAnalyzer.HasUriQuery) then begin // Same document reference detected BaseUriAnalyzer.SetUriFragment(RelUriAnalyzer.UriFragment, RelUriAnalyzer.HasUriFragment); ResultUri := BaseUriAnalyzer.UriReference; Exit; end; if RelUriAnalyzer.HasUriScheme then begin // RelUri is an absolute URI --> we are done. ResultUri := RelUri; Exit; end; // inherit scheme: RelUriAnalyzer.SetUriScheme(BaseUriAnalyzer.UriScheme, BaseUriAnalyzer.HasUriScheme); if not RelUriAnalyzer.HasUriAuthority then begin // inherit Authority: RelUriAnalyzer.SetUriAuthority(BaseUriAnalyzer.UriAuthority, BaseUriAnalyzer.HasUriAuthority); //if not (Copy(RelUriAnalyzer.UriPath, 1, 1) = '/') then if not RelUriAnalyzer.UriPath.StartsWith('/') then begin // analyze Paths: Segments := TStringList.Create; try //SlashPos := LastDelimiter('/', BaseUriAnalyzer.UriPath); SlashPos := BaseUriAnalyzer.UriPath.LastIndexOf('/'); if SlashPos > 0 then //PathBuffer := Copy(BaseUriAnalyzer.UriPath, 2, SlashPos - 1) PathBuffer := BaseUriAnalyzer.UriPath.Substring( 1, SlashPos) // Copy Path without last segment and first Character which is always '/' else PathBuffer := ''; PathBuffer := Concat(PathBuffer, RelUriAnalyzer.UriPath); // cut PathBuffer into Segments: //SlashPos := Pos('/', PathBuffer); SlashPos := PathBuffer.IndexOf('/'); while SlashPos >= 0 do begin //Segments.Add(Copy(PathBuffer, 1, SlashPos - 1)); Segments.Add(PathBuffer.Substring(0, SlashPos)); //PathBuffer := Copy(PathBuffer, SlashPos + 1, Length(PathBuffer) // - SlashPos); PathBuffer := PathBuffer.Substring(SlashPos); //SlashPos := Pos('/', PathBuffer); SlashPos := PathBuffer.IndexOf('/'); end; {while ...} Segments.Add(PathBuffer); if (PathBuffer = '..') or (PathBuffer = '.') then Segments.Add(''); // Necessary to preserve ending '/' under some circumstances // remove '.' Segments: QueryIndex := Segments.IndexOf('.'); while QueryIndex > -1 do begin Segments.Delete(QueryIndex); QueryIndex := Segments.IndexOf('.'); end; // remove '<segment>/..' Segments: QueryIndex := Segments.IndexOf('..'); while QueryIndex > 0 do begin Segments.Delete(QueryIndex); Segments.Delete(Pred(QueryIndex)); QueryIndex := Segments.IndexOf('..'); end; // test for malformed Path: if Segments.Count > 0 then if Segments.Strings[0] = '..' then begin Result := False; Exit; end; PathBuffer := ''; for I := 0 to Pred(Segments.Count) do PathBuffer := Concat(PathBuffer, '/', Segments.Strings[I]); RelUriAnalyzer.SetUriPath(PathBuffer); finally Segments.Free; end; end; {if not (Copy(UriPath,1,1) = '/') ...} end; {if not HasAuthorityScheme ...} ResultUri := RelUriAnalyzer.UriReference; finally BaseUriAnalyzer.Free; RelUriAnalyzer.Free; end; end; {$IFNDEF NEXTGEN} function ResolveRelativeUriWideStr(const BaseUri, RelUri: WideString; var ResultUri: WideString): Boolean; var BaseUriAnalyzer, RelUriAnalyzer: TUriWideStrAnalyzer; I, SlashPos, QueryIndex: Integer; PathBuffer: WideString; Segments: TUtilsWideStringList; begin ResultUri := ''; BaseUriAnalyzer := TUriWideStrAnalyzer.Create; RelUriAnalyzer := TUriWideStrAnalyzer.Create; try Result := BaseUriAnalyzer.SetUriReference(BaseUri); Result := (RelUriAnalyzer.SetUriReference(RelUri) and Result); Result := ((BaseUriAnalyzer.HasUriScheme or RelUriAnalyzer.HasUriScheme) and Result); if not Result then Exit; // BaseUri is not an absolute URI reference, or BaseUri or RelUri is malformed if (RelUriAnalyzer.UriPath = '') and not (RelUriAnalyzer.HasUriScheme or RelUriAnalyzer.HasUriAuthority or RelUriAnalyzer.HasUriQuery) then begin // Same document reference detected BaseUriAnalyzer.SetUriFragment(RelUriAnalyzer.UriFragment, RelUriAnalyzer.HasUriFragment); ResultUri := BaseUriAnalyzer.UriReference; Exit; end; if RelUriAnalyzer.HasUriScheme then begin // RelUri is an absolute URI --> we are done. ResultUri := RelUri; Exit; end; // Inherit scheme: RelUriAnalyzer.SetUriScheme(BaseUriAnalyzer.UriScheme, BaseUriAnalyzer.HasUriScheme); if not RelUriAnalyzer.HasUriAuthority then begin // Inherit Authority: RelUriAnalyzer.SetUriAuthority(BaseUriAnalyzer.UriAuthority, BaseUriAnalyzer.HasUriAuthority); if not (Copy(RelUriAnalyzer.UriPath, 1, 1) = '/') then begin // Analyze Paths: Segments := TUtilsWideStringList.Create; try SlashPos := LastDelimiter('/', BaseUriAnalyzer.UriPath); if SlashPos > 0 then PathBuffer := Copy(BaseUriAnalyzer.UriPath, 2, SlashPos - 1) // Copy Path without last segment and first Character which is always '/' else PathBuffer := ''; PathBuffer := Concat(PathBuffer, RelUriAnalyzer.UriPath); // Cut PathBuffer into Segments: SlashPos := Pos('/', PathBuffer); while SlashPos > 0 do begin Segments.Add(Copy(PathBuffer, 1, SlashPos - 1)); PathBuffer := Copy(PathBuffer, SlashPos + 1, Length(PathBuffer) - SlashPos); SlashPos := Pos('/', PathBuffer); end; {while ...} Segments.Add(PathBuffer); if (PathBuffer = '..') or (PathBuffer = '.') then Segments.Add(''); // Necessary to preserve ending '/' under some circumstances // Remove '.' Segments: QueryIndex := Segments.IndexOf('.'); while QueryIndex > -1 do begin Segments.Delete(QueryIndex); QueryIndex := Segments.IndexOf('.'); end; // Remove '<segment>/..' Segments: QueryIndex := Segments.IndexOf('..'); while QueryIndex > 0 do begin Segments.Delete(QueryIndex); Segments.Delete(Pred(QueryIndex)); QueryIndex := Segments.IndexOf('..'); end; // Test for malformed Path: if Segments.Count > 0 then if Segments.WideStrings[0] = '..' then begin Result := False; Exit; end; PathBuffer := ''; for I := 0 to Pred(Segments.Count) do PathBuffer := Concat(PathBuffer, '/', Segments.WideStrings[I]); RelUriAnalyzer.SetUriPath(PathBuffer); finally Segments.Free; end; end; {if not (Copy(UriPath,1,1) = '/') ...} end; {if not HasAuthorityScheme ...} ResultUri := RelUriAnalyzer.UriReference; finally BaseUriAnalyzer.Free; RelUriAnalyzer.Free; end; end; {$ENDIF NEXTGEN} function FilenameToUriStr(const Path: TFilename; const Opt: TUtilsFilenameToUriOptions): string; var I, L: Integer; begin if fuSetLocalhost in Opt then Result := 'file://localhost' else Result := 'file://'; L := Length(Path); if L > 0 then begin // Add leading '/': Result := Concat(Result, '/'); I := FirstIndex; L := L - AdjustIndex; while I <= L do begin case Byte(Path[I]) of // A-z a-z 0-9 ! '()* - . _ ~ $41..$5A, $61..$7A, $30..$39, $21, $27..$2A, $2D, $2E, $5F, $7E: Result := Concat(Result, Path[I]); // special treatment for colons (':'): $3A: if fuPlainColon in Opt then Result := Concat(Result, ':') else Result := Concat(Result, '%3a'); {$IFDEF LINUX} // keep '/' in Linux filenames. $2F: Result := Concat(Result, '/'); {$ELSE} // translate '\' to '/' in Windows filenames: $5C: Result := Concat(Result, '/'); {$ENDIF} else // calculate escape sequence: Result := Concat(Result, '%', IntToHex(Byte(Path[I]), 2)); end; Inc(I); end; {while ...} end; {if ...} end; {$IFNDEF NEXTGEN} function FilenameToUriWideStr(const Path: TFilename; const Opt: TUtilsFilenameToUriOptions): WideString; var I, L: Integer; begin if fuSetLocalhost in Opt then Result := 'file://localhost' else Result := 'file://'; L := Length(Path); if L > 0 then begin // Add leading '/': Result := Concat(Result, '/'); I := 1; while I <= L do begin case Byte(Path[I]) of // A-z a-z 0-9 ! '()* - . _ ~ $41..$5A, $61..$7A, $30..$39, $21, $27..$2A, $2D, $2E, $5F, $7E: Result := Concat(Result, WideString(WideChar(Byte(Path[I])))); // special treatment for colons (':'): $3A: if fuPlainColon in Opt then Result := Concat(Result, ':') else Result := Concat(Result, '%3a'); {$IFDEF LINUX} // keep '/' in Linux filenames. $2F: Result := Concat(Result, '/'); {$ELSE} // translate '\' to '/' in Windows filenames: $5C: Result := Concat(Result, '/'); {$ENDIF} else // calculate escape sequence: Result := Concat(Result, '%', IntToHex(Byte(Path[I]), 2)); end; Inc(I); end; {while ...} end; {if ...} end; {$ENDIF NEXTGEN} function UriStrToFilename(const Uri: string; var Path: TFilename; var Authority, Query, Fragment: string): Boolean; var UriAnalyzer: TUriStrAnalyzer; PathBuffer: string; // Used to increase performance I, L: Integer; begin Path := ''; Query := ''; Fragment := ''; Result := False; UriAnalyzer := TUriStrAnalyzer.Create; try if UriAnalyzer.SetUriReference(uri) then begin if CompareText(UriAnalyzer.UriScheme, 'file') = 0 then begin Result := True; PathBuffer := UriAnalyzer.UriPath; L := PathBuffer.Length; if L > 0 then begin // remove leading '/': Dec(L); PathBuffer := PathBuffer.Substring(1, L); I := 0; while I < L do begin if PathBuffer.Chars[I] = '%' then begin // Resolve escape sequence: Path := Concat(Path, Chr(StrToInt(Concat('x', PathBuffer.Chars[I + 1], PathBuffer.Chars[I + 2])))); I := I + 2; end {$IFNDEF LINUX} // translate '/' to '\' for Windows filenames: else if PathBuffer.Chars[I] = '/' then begin Path := Concat(Path, '\'); end {$ENDIF} else Path := Concat(Path, PathBuffer[I]); Inc(I); end; {while ...} end; {if ...} Authority := UriAnalyzer.UriAuthority; if UriAnalyzer.HasUriQuery then Query := Concat('?', UriAnalyzer.UriQuery); if UriAnalyzer.HasUriFragment then Fragment := Concat('#', UriAnalyzer.UriFragment); end; {if ...} end; {if ...} finally UriAnalyzer.Free; end; end; {$IFNDEF NEXTGEN} function UriWideStrToFilename(const Uri: WideString; var Path: TFilename; var Authority, Query, Fragment: WideString): Boolean; var UriAnalyzer: TUriWideStrAnalyzer; PathBuffer: WideString; // Used to increase performance I, L: Integer; begin Path := ''; Query := ''; Fragment := ''; Result := False; UriAnalyzer := TUriWideStrAnalyzer.Create; try if UriAnalyzer.SetUriReference(Uri) then begin if CompareText(UriAnalyzer.UriScheme, 'file') = 0 then begin Result := True; PathBuffer := UriAnalyzer.UriPath; L := Length(PathBuffer); if L > 0 then begin // remove leading '/': Dec(L); PathBuffer := Copy(PathBuffer, 2, L); I := 1; while I <= L do begin if PathBuffer[I] = '%' then begin // Resolve escape sequence: Path := Concat(Path, Chr(StrToInt(Concat(WideString('x'), PathBuffer[I + 1], PathBuffer[I + 2])))); I := I + 2; end {$IFNDEF LINUX} // translate '/' to '\' for Windows filenames: else if PathBuffer[I] = '/' then begin Path := Concat(Path, '\'); end {$ENDIF} else Path := Concat(Path, PathBuffer[I]); Inc(I); end; {while ...} end; {if ...} Authority := UriAnalyzer.UriAuthority; if UriAnalyzer.HasUriQuery then Query := Concat('?', UriAnalyzer.UriQuery); if UriAnalyzer.HasUriFragment then Fragment := Concat('#', UriAnalyzer.UriFragment); end; {if ...} end; {if ...} finally UriAnalyzer.Free; end; end; {$ENDIF NEXTGEN} { TUriStrAnalyzer } constructor TUriStrAnalyzer.Create; begin inherited Create; SetUriReference(''); end; function TUriStrAnalyzer.GetUriReference: string; begin Result := ''; if FHasUriScheme then Result := Concat(Result, FUriScheme, ':'); if FHasUriAuthority then Result := Concat(Result, '//', FUriAuthority); Result := Concat(Result, FUriPath); if FHasUriQuery then Result := Concat(Result, '?', FUriQuery); if FHasUriFragment then Result := Concat(Result, '#', FUriFragment); end; function TUriStrAnalyzer.SetUriAuthority(const Value: string; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriAuthority := IsDefined; if IsDefined then begin if IsUriAuthorityStr(Value) then FUriAuthority := Value else begin FUriAuthority := ''; Result := False; end; end else FUriAuthority := ''; end; function TUriStrAnalyzer.SetUriFragment(const Value: string; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriFragment := IsDefined; if IsDefined then begin if IsUriFragmentStr(Value) then FUriFragment := Value else begin FUriFragment := ''; Result := False; end; end else FUriFragment := ''; end; function TUriStrAnalyzer.SetUriPath(const Value: string): Boolean; begin Result := IsUriPathStr(Value); if Result then FUriPath := Value else FUriPath := ''; end; function TUriStrAnalyzer.SetUriQuery(const Value: string; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriQuery := IsDefined; if IsDefined then begin if IsUriQueryStr(Value) then FUriQuery := Value else begin FUriQuery := ''; Result := False; end; end else FUriQuery := ''; end; function TUriStrAnalyzer.SetUriReference(const Value: string): Boolean; var ColonPos, DcPos, QmPos, SlashPos: Integer; S: string; begin ColonPos := Pos(':', Value); Result := SetUriScheme(Copy(Value, 1, ColonPos - 1), (ColonPos > 0)); S := Copy(Value, ColonPos + 1, Length(Value) - ColonPos); DcPos := Pos('#', S); if DcPos > 0 then begin Result := (SetUriFragment(Copy(S, DcPos + 1, Length(S) - DcPos), True) and Result); S := Copy(S, 1, DcPos - 1); end else SetUriFragment('', False); QmPos := Pos('?', S); if QmPos > 0 then begin Result := (SetUriQuery(Copy(S, QmPos + 1, Length(S) - QmPos), True) and Result); S := Copy(S, 1, QmPos - 1); end else SetUriQuery('', False); // if Copy(S, 1, 2) = '//' then if S.StartsWith('//') then begin S := S.Substring(2); SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := (SetUriAuthority(Copy(S, 1, SlashPos - 1), True) and Result); S := Copy(S, SlashPos, Length(S) - SlashPos + 1); end else begin Result := (SetUriAuthority(S, True) and Result); S := ''; end; end else SetUriAuthority('', False); Result := SetUriPath(S) and Result; if not Result then SetUriReference(''); end; function TUriStrAnalyzer.SetUriScheme(const Value: string; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriScheme := IsDefined; if IsDefined then begin if IsUriSchemeStr(Value) then FUriScheme := Value else begin FUriScheme := ''; Result := False; end; end else FUriScheme := ''; end; {$IFNDEF NEXTGEN} { TUriWideStrAnalyzer } constructor TUriWideStrAnalyzer.Create; begin inherited Create; SetUriReference(''); end; function TUriWideStrAnalyzer.GetUriReference: WideString; begin Result := ''; if FHasUriScheme then Result := Concat(Result, FUriScheme, ':'); if FHasUriAuthority then Result := Concat(Result, '//', FUriAuthority); Result := Concat(Result, FUriPath); if FHasUriQuery then Result := Concat(Result, #63, FUriQuery); if FHasUriFragment then Result := Concat(Result, '#', FUriFragment); end; function TUriWideStrAnalyzer.SetUriAuthority(const Value: WideString; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriAuthority := IsDefined; if IsDefined then begin if IsUriAuthorityWideStr(Value) then FUriAuthority := Value else begin FUriAuthority := ''; Result := False; end; end else FUriAuthority := ''; end; function TUriWideStrAnalyzer.SetUriFragment(const Value: WideString; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriFragment := IsDefined; if IsDefined then begin if IsUriFragmentWideStr(Value) then FUriFragment := Value else begin FUriFragment := ''; Result := False; end; end else FUriFragment := ''; end; function TUriWideStrAnalyzer.SetUriPath(const Value: WideString): Boolean; begin Result := IsUriPathWideStr(Value); if Result then FUriPath := Value else FUriPath := ''; end; function TUriWideStrAnalyzer.SetUriQuery(const Value: WideString; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriQuery := IsDefined; if IsDefined then begin if IsUriQueryWideStr(Value) then FUriQuery := Value else begin FUriQuery := ''; Result := False; end; end else FUriQuery := ''; end; function TUriWideStrAnalyzer.SetUriReference(const Value: WideString): Boolean; var ColonPos, DcPos, QmPos, SlashPos: Integer; S: WideString; begin ColonPos := Pos(':', Value); Result := SetUriScheme(Copy(Value, 1, ColonPos - 1), (ColonPos > 0)); S := Copy(Value, ColonPos + 1, Length(Value) - ColonPos); DcPos := Pos('#', S); if DcPos > 0 then begin Result := (SetUriFragment(Copy(S, DcPos + 1, Length(S) - DcPos), True) and Result); S := Copy(S, 1, DcPos - 1); end else SetUriFragment('', False); QmPos := Pos('?', S); if QmPos > 0 then begin Result := (SetUriQuery(Copy(S, QmPos + 1, Length(S) - QmPos), True) and Result); S := Copy(S, 1, QmPos - 1); end else SetUriQuery('', False); if Copy(S, 1, 2) = '//' then begin S := Copy(S, 3, Length(S) - 2); SlashPos := Pos('/', S); if SlashPos > 0 then begin Result := (SetUriAuthority(Copy(S, 1, SlashPos - 1), True) and Result); S := Copy(S, SlashPos, Length(S) - SlashPos + 1); end else begin Result := (SetUriAuthority(S, True) and Result); S := ''; end; end else SetUriAuthority('', False); Result := SetUriPath(S) and Result; if not Result then SetUriReference(''); end; function TUriWideStrAnalyzer.SetUriScheme(const Value: WideString; const IsDefined: Boolean): Boolean; begin Result := True; FHasUriScheme := IsDefined; if IsDefined then begin if IsUriSchemeWideStr(Value) then FUriScheme := Value else begin FUriScheme := ''; Result := False; end; end else FUriScheme := ''; end; {$ENDIF NEXTGEN} end.
namespace RemObjects.SDK.CodeGen4; interface type ParamFlags = public enum ( &In, &Out, &InOut, &Result ); RodlEntity = public abstract class private fOriginalName: String; method getOriginalName: String; fCustomAttributes: Dictionary<String,String> := new Dictionary<String,String>; fCustomAttributes_lower: Dictionary<String,String> := new Dictionary<String,String>; method getOwnerLibrary: RodlLibrary; protected method FixLegacyTypes(aName: String):String; public constructor(); virtual; constructor(node: XmlElement); method LoadFromXmlNode(node: XmlElement); virtual; method HasCustomAttributes: Boolean; property IsFromUsedRodl: Boolean read assigned(FromUsedRodl); {$region Properties} property EntityID: Guid; property Name: String; property OriginalName: String read getOriginalName write fOriginalName; property Documentation: String; property &Abstract: Boolean; property CustomAttributes: Dictionary<String,String> read fCustomAttributes; property CustomAttributes_lower: Dictionary<String,String> read fCustomAttributes_lower; //property PluginData :XmlDocument; //???? //property HasPluginData: Boolean read getPluginData; property GroupUnder: RodlGroup; property FromUsedRodl: RodlUse; property FromUsedRodlId: Guid; property Owner: RodlEntity; property OwnerLibrary: RodlLibrary read getOwnerLibrary; property DontCodegen: Boolean; {$endregion} end; RodlTypedEntity = public abstract class (RodlEntity) public method LoadFromXmlNode(node: XmlElement); override; property DataType: String; end; RodlEntityWithAncestor = public abstract class (RodlEntity) private method setAncestorEntity(value: RodlEntity); method getAncestorEntity: RodlEntity; public method LoadFromXmlNode(node: XmlElement); override; property AncestorName: String; property AncestorEntity: RodlEntity read getAncestorEntity write setAncestorEntity; end; RodlComplexEntity<T> = public abstract class (RodlEntityWithAncestor) where T is RodlEntity; private fItemsNodeName: String; fItems: EntityCollection<T>; public constructor();abstract; constructor(nodeName:String); method LoadFromXmlNode(node: XmlElement; aActivator: method : T); method GetInheritedItems: List<T>; method GetAllItems: List<T>; property Items: List<T> read fItems.Items; property Count: Int32 read fItems.Count; property Item[index: Integer]: T read fItems[index]; default; end; RodlStructEntity = public abstract class (RodlComplexEntity<RodlField>) public constructor();override; method LoadFromXmlNode(node: XmlElement); override; property AutoCreateProperties: Boolean := False; end; RodlServiceEntity = public abstract class (RodlComplexEntity<RodlInterface>) public constructor();override; property DefaultInterface: RodlInterface read iif(Count>0,Item[0],nil); method LoadFromXmlNode(node: XmlElement); override; end; EntityCollection<T> = public class where T is RodlEntity; private fEntityNodeName: String; fItems: List<T> := new List<T>; public constructor(aOwner: RodlEntity; nodeName: String); method LoadFromXmlNode(node: XmlElement; usedRodl: RodlUse; aActivator: method : T); method AddEntity(entity : T); method RemoveEntity(entity: T); method RemoveEntity(index: Int32); method FindEntity(name: String): T; method SortedByAncestor: List<T>; property Owner : RodlEntity; property Count: Integer read fItems.Count; property Items: List<T> read fItems; property Item[Index: Integer]: T read fItems[Index]; default; end; RodlLibrary = public class (RodlEntity) private fXmlNode: XmlElement; // only for supporting SaveToFile fStructs: EntityCollection<RodlStruct>; fArrays: EntityCollection<RodlArray>; fEnums: EntityCollection<RodlEnum>; fExceptions: EntityCollection<RodlException>; fGroups: EntityCollection<RodlGroup>; fUses: EntityCollection<RodlUse>; fServices: EntityCollection<RodlService>; fEventSinks: EntityCollection<RodlEventSink>; method LoadXML(aFile: String): XmlDocument; method isUsedRODLLoaded(anUse:RodlUse): Boolean; public constructor; override; constructor (aFilename: String); constructor (node: XmlElement); method LoadFromXmlNode(node: XmlElement); override; method LoadFromXmlNode(node: XmlElement; use: RodlUse); method LoadRemoteRodlFromXmlNode(node: XmlElement); method LoadFromUrl(aUrl: String); method LoadFromFile(aFilename: String); method LoadFromXmlString(aString: String); method LoadUsedFibraryFromFile(aFilename: String; use: RodlUse); method SaveToFile(aFilename: String); method ToString: {$IF ECHOES}System.{$ENDIF}String; {$IF ECHOES}override;{$ENDIF} method FindEntity(aName: String):RodlEntity; property Structs: EntityCollection<RodlStruct> read fStructs; property Arrays: EntityCollection<RodlArray> read fArrays; property Enums: EntityCollection<RodlEnum> read fEnums; property Exceptions: EntityCollection<RodlException> read fExceptions; property Groups: EntityCollection<RodlGroup> read fGroups; property &Uses: EntityCollection<RodlUse> read fUses; property Services: EntityCollection<RodlService> read fServices; property EventSinks: EntityCollection<RodlEventSink> read fEventSinks; property Filename: String; property &Namespace: String; property Includes: RodlInclude; property DontApplyCodeGen: Boolean; property DataSnap: Boolean := false; property ScopedEnums: Boolean := false; end; RodlGroup = public class(RodlEntity) end; RodlInclude= public class(RodlEntity) private method LoadAttribute(node:XmlElement; aName:String):String; public method LoadFromXmlNode(node: XmlElement); override; property DelphiModule: String; property JavaModule: String; property JavaScriptModule: String; property NetModule: String; property CocoaModule: String; property ObjCModule: String; end; RodlUse = public class(RodlEntity) public constructor();override; method LoadFromXmlNode(node: XmlElement); override; property FileName: String; property AbsoluteRodl: String; property &Namespace: String; property Includes: RodlInclude; property UsedRodlId: Guid; property IsMerged: Boolean read not UsedRodlId.Equals(Guid.EmptyGuid); property DontApplyCodeGen: Boolean; property Loaded: Boolean; property AbsoluteFileName: String; end; RodlField = public class(RodlTypedEntity) end; RodlStruct= public class(RodlStructEntity) end; RodlException= public class(RodlStructEntity) end; RodlEnumValue = public class(RodlEntity) end; RodlEnum= public class(RodlComplexEntity<RodlEnumValue>) public constructor();override; method LoadFromXmlNode(node: XmlElement); override; property PrefixEnumValues: Boolean; property DefaultValueName: String read if Count > 0 then Item[0].Name; end; RodlArray= public class(RodlEntity) public method LoadFromXmlNode(node: XmlElement); override; property ElementType: String; end; RodlService= public class(RodlServiceEntity) private fRoles: RodlRoles := new RodlRoles(); public method LoadFromXmlNode(node: XmlElement); override; property Roles: RodlRoles read fRoles; property ImplUnit:String; property ImplClass:String; property &Private: Boolean; end; RodlEventSink= public class(RodlServiceEntity) end; RodlInterface= public class(RodlComplexEntity<RodlOperation>) private public constructor();override; method LoadFromXmlNode(node: XmlElement); override; end; RodlRole = public class public constructor; empty; constructor(aRole: String; aNot: Boolean); property Role: String; property &Not: Boolean; end; RodlRoles = public class private fRoles: List<RodlRole> := new List<RodlRole>; public method LoadFromXmlNode(node: XmlElement); method Clear; property Roles:List<RodlRole> read fRoles; property Role[index : Integer]: RodlRole read fRoles[index]; end; RodlOperation = public class(RodlComplexEntity<RodlParameter>) private fRoles: RodlRoles := new RodlRoles(); public constructor();override; method LoadFromXmlNode(node: XmlElement); override; property Roles: RodlRoles read fRoles; property &Result: RodlParameter; property ForceAsyncResponse: Boolean := false; end; RodlParameter = public class(RodlTypedEntity) private public method LoadFromXmlNode(node: XmlElement); override; property ParamFlag: ParamFlags; end; RodlReader = public class private protected public end; extension method XmlElement.ValueOrText: String; assembly; extension method String.GetParentDirectory: String; implementation extension method String.GetParentDirectory: String; begin {$IFDEF FAKESUGAR} exit Path.GetDirectoryName(Self); {$ELSE} exit Path.GetParentDirectory(Self); {$ENDIF} end; extension method XmlElement.ValueOrText: String; begin {$IFDEF FAKESUGAR} exit Self.InnerText; {$ELSE} exit self.Value; {$ENDIF} end; method RodlEntity.HasCustomAttributes: Boolean; begin Result := assigned(CustomAttributes) and (CustomAttributes:Count >0) end; method RodlEntity.getOwnerLibrary: RodlLibrary; begin var lOwner: RodlEntity := self; while ((lOwner <> nil) and (not(lOwner is RodlLibrary))) do lOwner := lOwner.Owner; exit (lOwner as RodlLibrary); end; method RodlEntity.FixLegacyTypes(aName: String):String; begin exit iif(aName.ToLowerInvariant() = "string", "AnsiString", aName); end; method RodlEntity.LoadFromXmlNode(node: XmlElement); begin Name := node.Attribute["Name"]:Value; if (node.Attribute["UID"] <> nil) then EntityID := Guid.TryParse(node.Attribute["UID"].Value); if (node.Attribute["FromUsedRodlUID"] <> nil) then FromUsedRodlId := Guid.TryParse(node.Attribute["FromUsedRodlUID"].Value); &Abstract := node.Attribute["Abstract"]:Value = "1"; DontCodegen := node.Attribute["DontCodeGen"]:Value = "1"; var ldoc := node.FirstElementWithName("Documentation"); if (ldoc ≠ nil) and (ldoc.Elements.FirstOrDefault ≠ nil) then // FirstChild because data should be enclosed within CDATA Documentation := ldoc.Elements.FirstOrDefault.Value; var lSubNode: XmlElement := node.FirstElementWithName("CustomAttributes"); if (lSubNode <> nil) then begin for each childNode: XmlElement in lSubNode.Elements do begin var lValue: XmlAttribute := childNode.Attribute["Value"]; if (lValue <> nil) then begin CustomAttributes[childNode.LocalName] := lValue.Value; CustomAttributes_lower[childNode.LocalName.ToLowerInvariant] := lValue.Value; if childNode.LocalName.ToLowerInvariant = "soapname" then fOriginalName := lValue.Value; end; end; end; end; constructor RodlEntity(); begin EntityID := Guid.NewGuid(); FromUsedRodlId := Guid.EmptyGuid; end; constructor RodlEntity(node: XmlElement); begin constructor(); LoadFromXmlNode(node); end; method RodlEntity.getOriginalName: String; begin exit iif(String.IsNullOrEmpty(fOriginalName), Name, fOriginalName); end; method RodlTypedEntity.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); DataType := FixLegacyTypes(node.Attribute["DataType"].Value); end; method RodlEntityWithAncestor.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); if (node.Attribute["Ancestor"] <> nil) then AncestorName := node.Attribute["Ancestor"].Value; end; method RodlEntityWithAncestor.getAncestorEntity: RodlEntity; begin if (String.IsNullOrEmpty(AncestorName)) then exit nil; var lRodlLibrary: RodlLibrary := OwnerLibrary; exit iif(lRodlLibrary = nil, nil , lRodlLibrary.FindEntity(AncestorName)); end; method RodlEntityWithAncestor.setAncestorEntity(value: RodlEntity); begin value := getAncestorEntity; end; method RodlComplexEntity<T>.LoadFromXmlNode(node: XmlElement; aActivator: method : T); begin inherited LoadFromXmlNode(node); fItems.LoadFromXmlNode(node.FirstElementWithName(fItemsNodeName), nil, aActivator); end; constructor RodlComplexEntity<T>(nodeName: String); begin inherited constructor; fItemsNodeName := nodeName + "s"; fItems := new EntityCollection<T>(self, nodeName); end; method RodlComplexEntity<T>.GetInheritedItems: List<T>; begin var lancestor := AncestorEntity; if assigned(lancestor) and (lancestor is RodlComplexEntity<T>) then begin result := RodlComplexEntity<T>(lancestor).GetInheritedItems; result.Add(RodlComplexEntity<T>(lancestor).fItems.Items); end else begin result := new List<T>; end; end; method RodlComplexEntity<T>.GetAllItems: List<T>; begin result := GetInheritedItems; result.Add(Self.fItems.Items); end; constructor RodlStructEntity; begin inherited constructor("Element"); end; method RodlStructEntity.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node,-> new RodlField); if (node.Attribute["AutoCreateParams"] <> nil) then AutoCreateProperties := (node.Attribute["AutoCreateParams"].Value = "1"); end; constructor RodlServiceEntity; begin inherited constructor("Interface"); end; method RodlServiceEntity.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node,-> new RodlInterface); end; constructor EntityCollection<T>(aOwner: RodlEntity; nodeName: String); begin fEntityNodeName := nodeName; Owner := aOwner; end; method EntityCollection<T>.AddEntity(entity: T); begin fItems.Add(entity); end; method EntityCollection<T>.RemoveEntity(entity: T); begin fItems.Remove(entity); end; method EntityCollection<T>.RemoveEntity(&index: Integer); begin fItems.RemoveAt(index); end; method EntityCollection<T>.FindEntity(name: String): T; begin for lRodlEntity: T in fItems do if not lRodlEntity.IsFromUsedRodl and lRodlEntity.Name.EqualsIgnoringCaseInvariant(name) then exit lRodlEntity; for lRodlEntity: T in fItems do if lRodlEntity.Name.EqualsIgnoringCaseInvariant(name) then exit lRodlEntity; exit nil; end; method EntityCollection<T>.LoadFromXmlNode(node: XmlElement; usedRodl: RodlUse; aActivator: method : T); begin if (node = nil) then exit; for lNode: XmlNode in node.Elements do begin var lr := (lNode.NodeType = XmlNodeType.Element) and (XmlElement(lNode).LocalName = fEntityNodeName); if lr then begin var lEntity := aActivator(); lEntity.FromUsedRodl := usedRodl; lEntity.Owner := Owner; lEntity.LoadFromXmlNode(XmlElement(lNode)); var lIsNew := true; for entity:T in fItems do if entity.EntityID.Equals(lEntity.EntityID) then begin if entity.Name.EqualsIgnoringCaseInvariant(lEntity.Name) then begin lIsNew := false; break; end else begin lEntity.EntityID := Guid.NewGuid; end; end; if lIsNew then AddEntity(lEntity); end; end; end; method EntityCollection<T>.SortedByAncestor: List<T>; begin var lResult := new List<T>; var lAncestors := new List<T>; {if typeOf(T).Equals(typeOf(RodlEntityWithAncestor) then begin lResult.Add(fItems); exit; end;} for each lt in fItems do begin var laname:= RodlEntityWithAncestor(lt):AncestorName; if not String.IsNullOrEmpty(laname) and (fItems.Where(b->b.Name.EqualsIgnoringCaseInvariant(laname)).Count>0) then lAncestors.Add(lt) else lResult.Add(lt); end; var lWorked := false; while lAncestors.Count > 0 do begin lWorked := false; for i: Integer := lAncestors.Count-1 downto 0 do begin var laname:= (lAncestors[i] as RodlEntityWithAncestor).AncestorName; var lst := lResult.Where(b->b.Name.Equals(laname)).ToList; if lst.Count = 1 then begin var lIndex := lResult.IndexOf(lst[0]); lResult.Insert(lIndex+1,lAncestors[i]); lAncestors.RemoveAt(i); lWorked := true; end; if (not lWorked) and (lAncestors.Count > 0) then new Exception("Invalid or recursive inheritance detected"); end; end; exit lResult; end; constructor RodlLibrary; begin Includes := nil; fStructs := new EntityCollection<RodlStruct>(self, "Struct"); fArrays := new EntityCollection<RodlArray>(self, "Array"); fEnums := new EntityCollection<RodlEnum>(self, "Enum"); fExceptions := new EntityCollection<RodlException>(self, "Exception"); fGroups := new EntityCollection<RodlGroup>(self, "Group"); fUses := new EntityCollection<RodlUse>(self, "Use"); fServices := new EntityCollection<RodlService>(self, "Service"); fEventSinks := new EntityCollection<RodlEventSink>(self, "EventSink"); end; constructor RodlLibrary(aFilename: String); begin constructor(); if aFilename.StartsWith('http://') or aFilename.StartsWith('https://') or aFilename.StartsWith('superhttp://') or aFilename.StartsWith('superhttps://') or aFilename.StartsWith('tcp://') or aFilename.StartsWith('tcps://') or aFilename.StartsWith('supertcp://') or aFilename.StartsWith('supertcps://') then LoadFromUrl(aFilename) else LoadFromFile(aFilename); end; constructor RodlLibrary(node: XmlElement); begin constructor(); LoadFromXmlNode(node, nil); end; method RodlLibrary.LoadFromFile(aFilename: String); begin if Path.GetExtension(aFilename):ToLowerInvariant = ".remoterodl" then begin var lRemoteRodl := LoadXML(aFilename); if not assigned(lRemoteRodl)then raise new Exception("Could not read "+aFilename); LoadRemoteRodlFromXmlNode(lRemoteRodl.Root); end else begin Filename := aFilename; var lDocument := LoadXML(aFilename); if not assigned(lDocument)then raise new Exception("Could not read "+aFilename); LoadFromXmlNode(lDocument.Root); end; end; method RodlLibrary.SaveToFile(aFilename: String); begin if assigned(fXmlNode) then fXmlNode.Document.SaveToFile(aFilename); end; method RodlLibrary.ToString: {$IF ECHOES}System.{$ENDIF}String; begin if assigned(fXmlNode) then {$IFDEF FAKESUGAR} result := fXmlNode.OwnerDocument.InnerXml; {$ELSE} result := fXmlNode.ToString(); {$ENDIF} end; method RodlLibrary.LoadFromXmlString(aString: String); begin {$IFDEF FAKESUGAR} var lDocument := new XmlDocument(); lDocument.LoadXml(aString); {$ELSE} var lDocument := XmlDocument.FromString(aString); {$ENDIF} LoadFromXmlNode(lDocument.Root); end; method RodlLibrary.LoadRemoteRodlFromXmlNode(node: XmlElement); begin {$MESSAGE optimize code} var lServers := node.ElementsWithName("Server"); if lServers.Count ≠ 1 then raise new Exception("Server element not found in remoteRODL."); {$IFDEF FAKESUGAR} var lServerUris := (lServers.Item(0)as XmlElement):GetElementsByTagName("ServerUri"); if lServerUris.Count ≠ 1 then raise new Exception("lServerUris element not found in remoteRODL."); LoadFromUrl(lServerUris.Item(0).Value); {$ELSE} var lServerUris := lServers.FirstOrDefault.ElementsWithName("ServerUri"); if lServerUris.Count ≠ 1 then raise new Exception("lServerUris element not found in remoteRODL."); LoadFromUrl(lServerUris.FirstOrDefault.Value); {$ENDIF} end; method RodlLibrary.LoadFromUrl(aUrl: String); begin {$IFDEF FAKESUGAR} var lUrl := new Uri(aUrl); if lUrl.Scheme in ["http", "https"] then begin var allData := new System.IO.MemoryStream(); using webRequest := System.Net.WebRequest.Create(lUrl) as System.Net.HttpWebRequest do begin webRequest.AllowAutoRedirect := true; //webRequest.UserAgent := "RemObjects Sugar/8.0 http://www.elementscompiler.com/elements/sugar"; webRequest.Method := 'GET'; var webResponse := webRequest.GetResponse() as System.Net.HttpWebResponse; webResponse.GetResponseStream().CopyTo(allData); end; var lXml := new XmlDocument; lXml.Load(allData); LoadFromXmlNode(lXml.Root); end else if lUrl.Scheme = "file" then begin var lXml := LoadXML(lUrl.AbsolutePath); LoadFromXmlNode(lXml.Root); end else begin raise new Exception("Unspoorted URL Scheme ("+lUrl.Scheme+") in remoteRODL."); end; {$ELSE} var lUrl := Url.UrlWithString(aUrl); if lUrl.Scheme in ["http", "https"] then begin var lXml := Http.GetXml(new HttpRequest(lUrl));// why is this cast needed, we have operator Implicit from Url to HttpRequest LoadFromXmlNode(lXml.Root); end else if lUrl.Scheme = "file" then begin var lXml := LoadXML(lUrl.Path); LoadFromXmlNode(lXml.Root); end else begin raise new Exception("Unspoorted URL Scheme ("+lUrl.Scheme+") in remoteRODL."); end; {$ENDIF} end; method RodlLibrary.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node, nil); end; method RodlLibrary.LoadFromXmlNode(node: XmlElement; use: RodlUse); begin if use = nil then begin fXmlNode := node; inherited LoadFromXmlNode(node); if (node.Attribute["Namespace"] <> nil) then &Namespace := node.Attribute["Namespace"].Value; if (node.Attribute["DataSnap"] <> nil) then DataSnap := node.Attribute["DataSnap"].Value = "1"; if (node.Attribute["ScopedEnums"] <> nil) then ScopedEnums := node.Attribute["ScopedEnums"].Value = "1"; DontApplyCodeGen := ((node.Attribute["SkipCodeGen"] <> nil) and (node.Attribute["SkipCodeGen"].Value = "1")) or ((node.Attribute["DontCodeGen"] <> nil) and (node.Attribute["DontCodeGen"].Value = "1")); var lInclude := node.FirstElementWithName("Includes"); if (lInclude <> nil) then begin Includes := new RodlInclude(); Includes.LoadFromXmlNode(lInclude); end else begin Includes := nil; end; end else begin use.Name := node.Attribute["Name"]:Value; use.UsedRodlId := Guid.TryParse(node.Attribute["UID"].Value); use.DontApplyCodeGen := use.DontApplyCodeGen or (((node.Attribute["SkipCodeGen"] <> nil) and (node.Attribute["SkipCodeGen"].Value = "1")) or ((node.Attribute["DontCodeGen"] <> nil) and (node.Attribute["DontCodeGen"].Value = "1"))); if (node.Attribute["Namespace"] <> nil) then use.Namespace := node.Attribute["Namespace"].Value; var lInclude := node.FirstElementWithName("Includes"); if (lInclude <> nil) then begin use.Includes := new RodlInclude(); use.Includes.LoadFromXmlNode(lInclude); end; if isUsedRODLLoaded(use) then exit; end; fUses.LoadFromXmlNode(node.FirstElementWithName("Uses"), use, -> new RodlUse); fStructs.LoadFromXmlNode(node.FirstElementWithName("Structs"), use, -> new RodlStruct); fArrays.LoadFromXmlNode(node.FirstElementWithName("Arrays"), use, -> new RodlArray); fEnums.LoadFromXmlNode(node.FirstElementWithName("Enums"), use, -> new RodlEnum); fExceptions.LoadFromXmlNode(node.FirstElementWithName("Exceptions"), use, -> new RodlException); fGroups.LoadFromXmlNode(node.FirstElementWithName("Groups"), use, -> new RodlGroup); fServices.LoadFromXmlNode(node.FirstElementWithName("Services"), use, -> new RodlService); fEventSinks.LoadFromXmlNode(node.FirstElementWithName("EventSinks"), use, -> new RodlEventSink); end; method RodlLibrary.LoadUsedFibraryFromFile(aFilename: String; use: RodlUse); begin var lDocument := LoadXML(aFilename); LoadFromXmlNode(lDocument.Root, use); end; method RodlLibrary.FindEntity(aName: String): RodlEntity; begin var lEntity: RodlEntity; lEntity := fStructs.FindEntity(aName); if (lEntity = nil) then lEntity := fArrays.FindEntity(aName); if (lEntity = nil) then lEntity := fEnums.FindEntity(aName); if (lEntity = nil) then lEntity := fExceptions.FindEntity(aName); if (lEntity = nil) then lEntity := fGroups.FindEntity(aName); if (lEntity = nil) then lEntity := fUses.FindEntity(aName); if (lEntity = nil) then lEntity := fServices.FindEntity(aName); if (lEntity = nil) then lEntity := fEventSinks.FindEntity(aName); exit lEntity; end; method RodlLibrary.LoadXML(aFile: String): XmlDocument; begin {$IFDEF FAKESUGAR} Result := new XmlDocument; result.Load(aFile); {$ELSE} exit XmlDocument.FromFile(aFile); {$ENDIF} end; method RodlLibrary.isUsedRODLLoaded(anUse: RodlUse): Boolean; begin if EntityID.Equals(anUse.UsedRodlId) then exit true; for m in &Uses.Items do begin if m = anUse then continue; if m.UsedRodlId.Equals(anUse.UsedRodlId) then exit true; end; exit false; end; method RodlInclude.LoadAttribute(node: XmlElement; aName: String): String; begin exit iif(node.Attribute[aName] <> nil, node.Attribute[aName].Value, ""); end; method RodlInclude.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); DelphiModule := LoadAttribute(node, "Delphi"); NetModule := LoadAttribute(node, "DotNet"); ObjCModule := LoadAttribute(node, "ObjC"); JavaModule := LoadAttribute(node, "Java"); JavaScriptModule := LoadAttribute(node, "JavaScript"); CocoaModule := LoadAttribute(node, "Cocoa"); //backward compatibility if String.IsNullOrEmpty(CocoaModule) then CocoaModule := LoadAttribute(node, "Nougat"); end; constructor RodlUse; begin inherited constructor; Includes := nil; UsedRodlId := Guid.EmptyGuid; end; method RodlUse.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); var linclude: XmlElement := node.FirstElementWithName("Includes"); if (linclude <> nil) then begin Includes := new RodlInclude(); Includes.LoadFromXmlNode(linclude); end else begin Includes := nil; end; if (node.Attribute["Rodl"] <> nil) then FileName := node.Attribute["Rodl"].Value; if (node.Attribute["AbsoluteRodl"] <> nil) then AbsoluteRodl := node.Attribute["AbsoluteRodl"].Value; if (node.Attribute["UsedRodlID"] <> nil) then UsedRodlId := Guid.TryParse(node.Attribute["UsedRodlID"].Value); DontApplyCodeGen := (node.Attribute["DontCodeGen"] <> nil) and (node.Attribute["DontCodeGen"].Value = "1"); var usedRodlFileName: String := Path.GetFullPath(FileName); if (not usedRodlFileName.FileExists and not FileName.IsAbsolutePath) then begin if (OwnerLibrary.Filename <> nil) then usedRodlFileName := Path.GetFullPath(Path.Combine(Path.GetFullPath(OwnerLibrary.Filename).GetParentDirectory, FileName)); end; if (not usedRodlFileName.FileExists and not FileName.IsAbsolutePath) then begin if (FromUsedRodl:AbsoluteFileName <> nil) then usedRodlFileName := Path.GetFullPath(Path.Combine(FromUsedRodl:AbsoluteFileName:GetParentDirectory, FileName)); end; if (not usedRodlFileName.FileExists) then usedRodlFileName := AbsoluteRodl; if String.IsNullOrEmpty(usedRodlFileName) then Exit; if (not usedRodlFileName.FileExists) then begin usedRodlFileName := usedRodlFileName.Replace("/", Path.DirectorySeparatorChar).Replace("\", Path.DirectorySeparatorChar); var lFilename := Path.GetFileName(usedRodlFileName).ToLowerInvariant; //writeLn("checking for "+lFilename); if RodlCodeGen.KnownRODLPaths.ContainsKey(lFilename) then usedRodlFileName := RodlCodeGen.KnownRODLPaths[lFilename]; end; //writeLn("using rodl: "+usedRodlFileName); if (usedRodlFileName.FileExists) then begin AbsoluteFileName := usedRodlFileName; OwnerLibrary.LoadUsedFibraryFromFile(usedRodlFileName, self); Loaded := true; end; end; constructor RodlEnum; begin inherited constructor("EnumValue"); end; method RodlEnum.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node, -> new RodlEnumValue); PrefixEnumValues := node.Attribute["Prefix"]:Value <> '0'; end; method RodlArray.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); for lElementType in node.Elements do begin if (lElementType.LocalName = "ElementType") then begin if (XmlElement(lElementType).Attribute["DataType"] <> nil) then ElementType := FixLegacyTypes(XmlElement(lElementType).Attribute["DataType"].Value); break; end; end; end; method RodlService.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); fRoles.Clear; fRoles.LoadFromXmlNode(node); &Private := node.Attribute["Private"]:Value = "1"; ImplClass := node.Attribute["ImplClass"]:Value; ImplUnit := node.Attribute["ImplUnit"]:Value; end; constructor RodlInterface; begin inherited constructor("Operation"); end; method RodlInterface.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node, ->new RodlOperation); end; constructor RodlRole(aRole: String; aNot: Boolean); begin Role := aRole; &Not := aNot; end; constructor RodlOperation; begin inherited constructor("Parameter"); end; method RodlOperation.LoadFromXmlNode(node: XmlElement); begin LoadFromXmlNode(node,->new RodlParameter); fRoles.Clear; fRoles.LoadFromXmlNode(node); if (node.Attribute["ForceAsyncResponse"] <> nil) then ForceAsyncResponse := node.Attribute["ForceAsyncResponse"].Value = "1"; for parameter: RodlParameter in Items do if parameter.ParamFlag = ParamFlags.Result then self.Result := parameter; Items.Remove(self.Result); end; method RodlRoles.LoadFromXmlNode(node: XmlElement); begin var el := node.FirstElementWithName("Roles") as XmlElement; if (el = nil) or (el.Elements.Count = 0) then exit; for each lItem in el.Elements do begin if (lItem.LocalName = "DenyRole") then fRoles.Add(new RodlRole(lItem.ValueOrText, true)) else if (lItem.LocalName = "AllowRole") then fRoles.Add(new RodlRole(lItem.ValueOrText, false)); end; end; method RodlRoles.Clear; begin fRoles.RemoveAll; end; method RodlParameter.LoadFromXmlNode(node: XmlElement); begin inherited LoadFromXmlNode(node); var ln := node.Attribute["Flag"].Value.ToLowerInvariant; case ln of 'in': ParamFlag:= ParamFlags.In; 'out': ParamFlag:= ParamFlags.Out; 'inout': ParamFlag:= ParamFlags.InOut; 'result': ParamFlag:= ParamFlags.Result; else ParamFlag := ParamFlags.In; end; end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_ChunkyTriMesh; interface uses Math, RN_Helper; type TrcChunkyTriMeshNode = record bmin, bmax: array [0..1] of Single; i, n: Integer; end; PrcChunkyTriMeshNode = ^TrcChunkyTriMeshNode; TrcChunkyTriMesh = record nodes: array of TrcChunkyTriMeshNode; nnodes: Integer; tris: PInteger; ntris: Integer; maxTrisPerChunk: Integer; end; PrcChunkyTriMesh = ^TrcChunkyTriMesh; /// Creates partitioned triangle mesh (AABB tree), /// where each node contains at max trisPerChunk triangles. function rcCreateChunkyTriMesh(const verts: PSingle; const tris: PInteger; ntris: Integer; trisPerChunk: Integer; cm: PrcChunkyTriMesh): Boolean; /// Returns the chunk indices which overlap the input rectable. function rcGetChunksOverlappingRect(const cm: PrcChunkyTriMesh; bmin, bmax: PSingle; ids: PInteger; const maxIds: Integer): Integer; /// Returns the chunk indices which overlap the input segment. function rcGetChunksOverlappingSegment(const cm: PrcChunkyTriMesh; p, q: PSingle; ids: PInteger; const maxIds: Integer): Integer; implementation type TBoundsItem = record bmin: array [0..1] of Single; bmax: array [0..1] of Single; i: Integer; end; PBoundsItem = ^TBoundsItem; function compareItemX(const va,vb: Pointer): Integer; var a,b: PBoundsItem; begin a := va; b := vb; if (a.bmin[0] < b.bmin[0]) then Result := -1 else if (a.bmin[0] > b.bmin[0]) then Result := 1 else Result := 0; end; function compareItemY(const va,vb: Pointer): Integer; var a,b: PBoundsItem; begin a := va; b := vb; if (a.bmin[1] < b.bmin[1]) then Result := -1 else if (a.bmin[1] > b.bmin[1]) then Result := 1 else Result := 0; end; procedure calcExtends(const items: PBoundsItem; const nitems: Integer; const imin, imax: Integer; bmin, bmax: PSingle); var i: Integer; it: PBoundsItem; begin bmin[0] := items[imin].bmin[0]; bmin[1] := items[imin].bmin[1]; bmax[0] := items[imin].bmax[0]; bmax[1] := items[imin].bmax[1]; for i := imin+1 to imax - 1 do begin it := @items[i]; if (it.bmin[0] < bmin[0]) then bmin[0] := it.bmin[0]; if (it.bmin[1] < bmin[1]) then bmin[1] := it.bmin[1]; if (it.bmax[0] > bmax[0]) then bmax[0] := it.bmax[0]; if (it.bmax[1] > bmax[1]) then bmax[1] := it.bmax[1]; end; end; function longestAxis(x, y: Single): Integer; begin Result := Byte(y > x); end; procedure subdivide(items: PBoundsItem; nitems, imin, imax, trisPerChunk: Integer; curNode: PInteger; nodes: PrcChunkyTriMeshNode; const maxNodes: Integer; curTri: PInteger; outTris: PInteger; const inTris: PInteger); var inum,icur,i: Integer; node: PrcChunkyTriMeshNode; src,dst: PInteger; axis,isplit,iescape: Integer; begin inum := imax - imin; icur := curNode^; if (curNode^ > maxNodes) then Exit; node := @nodes[curNode^]; Inc(curNode^); if (inum <= trisPerChunk) then begin // Leaf calcExtends(items, nitems, imin, imax, @node.bmin[0], @node.bmax[0]); // Copy triangles. node.i := curTri^; node.n := inum; for i := imin to imax -1 do begin src := @inTris[items[i].i*3]; dst := @outTris[curTri^*3]; Inc(curTri^); dst[0] := src[0]; dst[1] := src[1]; dst[2] := src[2]; end; end else begin // Split calcExtends(items, nitems, imin, imax, @node.bmin[0], @node.bmax[0]); axis := longestAxis(node.bmax[0] - node.bmin[0], node.bmax[1] - node.bmin[1]); if (axis = 0) then begin // Sort along x-axis qsort(@items[imin], inum, sizeof(TBoundsItem), compareItemX); end else if (axis = 1) then begin // Sort along y-axis qsort(@items[imin], inum, sizeof(TBoundsItem), compareItemY); end; isplit := imin+inum div 2; // Left subdivide(items, nitems, imin, isplit, trisPerChunk, curNode, nodes, maxNodes, curTri, outTris, inTris); // Right subdivide(items, nitems, isplit, imax, trisPerChunk, curNode, nodes, maxNodes, curTri, outTris, inTris); iescape := curNode^ - icur; // Negative index means escape. node.i := -iescape; end; end; function rcCreateChunkyTriMesh(const verts: PSingle; const tris: PInteger; ntris: Integer; trisPerChunk: Integer; cm: PrcChunkyTriMesh): Boolean; var nchunks,i,j: Integer; items: array of TBoundsItem; t: PInteger; it: PBoundsItem; v: PSingle; curTri,curNode: Integer; node: PrcChunkyTriMeshNode; isLeaf: Boolean; begin nchunks := (ntris + trisPerChunk-1) div trisPerChunk; SetLength(cm.nodes, nchunks*4); GetMem(cm.tris, SizeOf(Integer)*ntris*3); cm.ntris := ntris; // Build tree SetLength(items, ntris); for i := 0 to ntris -1 do begin t := @tris[i*3]; it := @items[i]; it.i := i; // Calc triangle XZ bounds. it.bmin[0] := verts[t[0]*3+0]; it.bmax[0] := verts[t[0]*3+0]; it.bmin[1] := verts[t[0]*3+2]; it.bmax[1] := verts[t[0]*3+2]; for j := 1 to 2 do begin v := @verts[t[j]*3]; if (v[0] < it.bmin[0]) then it.bmin[0] := v[0]; if (v[2] < it.bmin[1]) then it.bmin[1] := v[2]; if (v[0] > it.bmax[0]) then it.bmax[0] := v[0]; if (v[2] > it.bmax[1]) then it.bmax[1] := v[2]; end; end; curTri := 0; curNode := 0; subdivide(@items[0], ntris, 0, ntris, trisPerChunk, @curNode, @cm.nodes[0], nchunks*4, @curTri, cm.tris, tris); cm.nnodes := curNode; // Calc max tris per node. cm.maxTrisPerChunk := 0; for i := 0 to cm.nnodes -1 do begin node := @cm.nodes[i]; isLeaf := node.i >= 0; if (not isLeaf) then continue; if (node.n > cm.maxTrisPerChunk) then cm.maxTrisPerChunk := node.n; end; Result := true; end; function checkOverlapRect(amin, amax, bmin, bmax: PSingle): Boolean; var overlap: Boolean; begin overlap := true; if (amin[0] > bmax[0]) or (amax[0] < bmin[0]) then overlap := false; if (amin[1] > bmax[1]) or (amax[1] < bmin[1]) then overlap := false; Result := overlap; end; function rcGetChunksOverlappingRect(const cm: PrcChunkyTriMesh; bmin, bmax: PSingle; ids: PInteger; const maxIds: Integer): Integer; var i,n,escapeIndex: Integer; node: PrcChunkyTriMeshNode; overlap,isLeafNode: Boolean; begin // Traverse tree i := 0; n := 0; while (i < cm.nnodes) do begin node := @cm.nodes[i]; overlap := checkOverlapRect(bmin, bmax, @node.bmin[0], @node.bmax[0]); isLeafNode := node.i >= 0; if (isLeafNode and overlap) then begin if (n < maxIds) then begin ids[n] := i; Inc(n); end; end; if (overlap or isLeafNode) then Inc(i) else begin escapeIndex := -node.i; i := i + escapeIndex; end; end; Result := n; end; function checkOverlapSegment(const p,q,bmin,bmax: PSingle): Boolean; const EPSILON = 0.000001; var tmin,tmax,ood,t1,t2,tmp: Single; d: array [0..1] of Single; i: Integer; begin tmin := 0; tmax := 1; d[0] := q[0] - p[0]; d[1] := q[1] - p[1]; for i := 0 to 1 do begin if (Abs(d[i]) < EPSILON) then begin // Ray is parallel to slab. No hit if origin not within slab if (p[i] < bmin[i]) or (p[i] > bmax[i]) then Exit(false); end else begin // Compute intersection t value of ray with near and far plane of slab ood := 1.0 / d[i]; t1 := (bmin[i] - p[i]) * ood; t2 := (bmax[i] - p[i]) * ood; if (t1 > t2) then begin tmp := t1; t1 := t2; t2 := tmp; end; if (t1 > tmin) then tmin := t1; if (t2 < tmax) then tmax := t2; if (tmin > tmax) then Exit(false); end; end; Result := true; end; function rcGetChunksOverlappingSegment(const cm: PrcChunkyTriMesh; p, q: PSingle; ids: PInteger; const maxIds: Integer): Integer; var i,n: Integer; node: PrcChunkyTriMeshNode; overlap,isLeafNode: Boolean; escapeIndex: Integer; begin // Traverse tree i := 0; n := 0; while (i < cm.nnodes) do begin node := @cm.nodes[i]; overlap := checkOverlapSegment(p, q, @node.bmin[0], @node.bmax[0]); isLeafNode := node.i >= 0; if (isLeafNode and overlap) then begin if (n < maxIds) then begin ids[n] := i; Inc(n); end; end; if (overlap or isLeafNode) then Inc(i) else begin escapeIndex := -node.i; Inc(i, escapeIndex); end; end; Result := n; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 112 O(N2) Greedy Method } program RoadsDirection; var N : Integer; I, J : Integer; procedure ReadInput; begin Readln(N); end; procedure WriteEdge (I, J : Integer); begin Writeln('From ', I, ' to ', J); end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); if (N = 2) or (N = 4) then Writeln('NO SOLUTION') else begin if N > 1 then if Odd(N) then begin WriteEdge(1, 2); WriteEdge(2, 3); WriteEdge(3, 1); I := 3; end else begin {this part may be incorrect} WriteEdge(1, 2); WriteEdge(2, 3); WriteEdge(3, 4); WriteEdge(4, 1); WriteEdge(1, 3); WriteEdge(2, 4); WriteEdge(1, 5); WriteEdge(4, 5); WriteEdge(5, 2); WriteEdge(5, 3); WriteEdge(6, 1); WriteEdge(6, 4); WriteEdge(2, 6); WriteEdge(3, 6); I := 6; end; for I := I + 1 to N do if Odd(I) then for J := 1 to I - 2 do WriteEdge(I, J) else begin for J := 1 to I - 1 do WriteEdge(J, I); WriteEdge(I, I + 1); end; end; Close(Output); end; begin ReadInput; WriteOutput; end.
unit World; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Voxel, Economy, GL, Entities; type spatial = longword; { tWorld } tWorld = class RootVoxel: tVoxel; VoxelCount: longword; Hubs: tEconomicHub; WorldSeed: longword; Wireframe: boolean; j: longword; CameraPosition, CameraDirection: rVec3; constructor Load(FileName: string); constructor CreateNew(Seed: longword); function Generate(Voxel: tVoxel): longint; procedure ListVoxel(Voxel: tVoxel; cx, cy, cz: single); procedure PassVoxels; procedure RenderVoxel(Voxel: tVoxel); procedure Render; procedure Save(FileName: string); destructor Destroy; override; end; implementation uses math, Utility; { tWorld } constructor tWorld.Load(FileName: string); begin end; constructor tWorld.CreateNew(Seed: longword); begin j:= 0; WorldSeed:= Seed; VoxelFidelity:= 8; RootVoxel:= tVoxel.Create(nil); RootVoxel.Order:= 0; VoxelCount:= Generate(RootVoxel); WriteLog('Voxels Generated: ' + strf(VoxelCount)); end; function tWorld.Generate(Voxel: tVoxel): longint; var //ChildHeight: spatial; i: eVoxelPos; begin //writeln('gen'); with Voxel do begin //WriteLog('Order ' + strf(Order)); if Order = VoxelFidelity then begin Result:= 1; exit; end; Result:= 0; for i:= BNW to BSW do //change to iterative begin //WriteLog('i ' + strf(longint(i))); //ChildHeight:= power(2, VoxelFidelity - Voxel.Order); if srand(2, WorldSeed + j) = 0 then begin Child[longint(i)]:= tVoxel.Create(Voxel); Result+= Generate(Child[longint(i)]); end else begin Child[longint(i) + 4]:= tVoxel.Create(Voxel); Result+= Generate(Child[longint(i) + 4]); end; inc(j); end; end; Result+= j; end; procedure tWorld.ListVoxel(Voxel: tVoxel; cx, cy, cz: single); var i: eVoxelPos; d: single; x, y, z: single; begin with Voxel do begin d:= MinVoxelDim * power(2, VoxelFidelity - Order) / 2; for i:= BNW to TSW do begin x:= cx; y:= cy; z:= cz; if Child[integer(i)] <> nil then begin with Child[integer(i)] do begin case i of BNW: begin x+= 0; y+= 0; z+= 0; j:= integer(i); end; BNE: begin x+= d; j:= integer(i); end; BSE: begin x+= d; z-= d; j:= integer(i); end; BSW: begin z-= d; j:= integer(i); end; TNW: begin y+= d; j:= integer(i); end; TNE: begin x+= d; y+= d; j:= integer(i); end; TSE: begin x+= d; y+= d; z-= d; j:= integer(i); end; TSW: begin y+= d; z-= d; j:= integer(i); end; end; inc(j); ListID:= glGenLists(1); glNewList(ListID, GL_COMPILE); glBegin(GL_QUADS{_STRIP}); glShadeModel(gl_Flat); glColor3f(Order * 1 / VoxelFidelity, random, j * 1 / VoxelCount); glVertex3f(x - d, y - d, z + d); //n glVertex3f(x - d, y, z + d); glVertex3f(x, y, z + d); glVertex3f(x, y - d, z + d); glVertex3f(x, y - d, z + d); //e glVertex3f(x, y, z + d); glVertex3f(x, y, z ); glVertex3f(x, y - d, z ); glVertex3f(x, y - d, z ); //s glVertex3f(x, y, z ); glVertex3f(x - d, y, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y - d, z ); //w glVertex3f(x - d, y, z ); glVertex3f(x - d, y, z + d); glVertex3f(x - d, y - d, z + d); glVertex3f(x - d, y - d, z + d); //b glVertex3f(x, y - d, z + d); glVertex3f(x , y - d, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y, z + d); //t glVertex3f(x - d, y, z ); glVertex3f(x , y, z ); glVertex3f(x , y, z + d); glEnd; glEndList; end; ListVoxel(Child[integer(i)], x - d / 2, y - d / 2, z + d / 2); end; end; end; end; procedure tWorld.PassVoxels; var d: single; x, y, z: single; begin d:= MinVoxelDim * power(2, VoxelFidelity); x:= d/2; y:= d/2; z:= - d/2; RootVoxel.ListID:= glGenLists(1); glNewList(RootVoxel.ListID, GL_COMPILE); glBegin(GL_QUADS{_STRIP}); glShadeModel(gl_Smooth); glColor3f(1, 1, 1); glVertex3f(x - d, y - d, z + d); //n glVertex3f(x - d, y, z + d); glVertex3f(x, y, z + d); glVertex3f(x, y - d, z + d); glVertex3f(x, y - d, z + d); //e glVertex3f(x, y, z + d); glVertex3f(x, y, z ); glVertex3f(x, y - d, z ); glVertex3f(x, y - d, z ); //s glVertex3f(x, y, z ); glVertex3f(x - d, y, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y - d, z ); //w glVertex3f(x - d, y, z ); glVertex3f(x - d, y, z + d); glVertex3f(x - d, y - d, z + d); glVertex3f(x - d, y - d, z + d); //b glVertex3f(x, y - d, z + d); glVertex3f(x , y - d, z ); glVertex3f(x - d, y - d, z ); glVertex3f(x - d, y, z + d); //t glVertex3f(x - d, y, z ); glVertex3f(x , y, z ); glVertex3f(x , y, z + d); glEnd; glEndList; ListVoxel(RootVoxel, 0, 0, 0); end; procedure tWorld.RenderVoxel(Voxel: tVoxel); var i: eVoxelPos; begin with Voxel do begin if Wireframe then begin if order <> VoxelFidelity then glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ) else glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); glCallList(ListID); end else if order = VoxelFidelity then glCallList(ListID); for i:= BNW to TSW do if Child[integer(i)] <> nil then RenderVoxel(Child[integer(i)]) end; end; procedure tWorld.Render; begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity; with CameraDirection do begin glRotatef(x,1,0,0); glRotatef(y,0,1,0); glRotatef(z,0,0,1); end; glMatrixMode(GL_PROJECTION); glLoadIdentity; with CameraPosition do glTranslatef(x, y, z); RenderVoxel(RootVoxel); {with Voxel do begin for i:= BNW to TSW do if Child[integer(i)] <> nil then with Child[integer(i)], CameraPosition do begin glLoadIdentity; glTranslatef(x, y, z); glCallList(ListID); WriteLog('LID ' + strf(ListID)); // glLoadIdentity; end; } { glBegin( GL_QUADS ); glVertex2f( -0.5, -0.5 ); glVertex2f( 0.5, -0.5 ); glVertex2f( 0.5, 0.5 ); glVertex2f( -0.5, 0.5 ); glEnd();} glFlush; end; procedure tWorld.Save(FileName: string); begin end; destructor tWorld.Destroy; begin if RootVoxel <> nil then RootVoxel.DestroyRoot; Hubs.Free; end; end.
unit UFrmGoodsInfoEdit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uFrmModal, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, ActnList, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit, cxMemo, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCurrencyEdit, cxMaskEdit, cxSpinEdit, cxCheckBox, DBClient, DB; type TFrmGoodsInfoEdit = class(TFrmModal) lbl1: TLabel; lbl2: TLabel; lbl3: TLabel; lbl4: TLabel; lbl5: TLabel; lbl7: TLabel; lbl8: TLabel; lbl10: TLabel; edtGoodsID: TcxTextEdit; edtGoodsName: TcxTextEdit; edtGoodsPYM: TcxTextEdit; edtGoodsType: TcxTextEdit; edtGoodsUnit: TcxTextEdit; edtGoodsPrice: TcxCurrencyEdit; cbbClassGuid: TcxLookupComboBox; edtNew: TcxCheckBox; edtRemark: TcxTextEdit; lbl6: TLabel; edtGoodsBarCode: TcxTextEdit; procedure FormShow(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure edtGoodsNamePropertiesChange(Sender: TObject); private FAction: string; FGuid: string; FDataSet: TClientDataSet; //FDsGoodsClass: TDataSource; procedure ClearControls; function BeforeExecute: Boolean; function DoExecute: Boolean; public class function ShowGoodsInfoEdit(DataSet: TClientDataSet; AAction: string): Boolean; end; var FrmGoodsInfoEdit: TFrmGoodsInfoEdit; implementation uses UDBAccess, UMsgBox, UPubFunLib; {$R *.dfm} { TFrmGoodsInfoEdit } function TFrmGoodsInfoEdit.BeforeExecute: Boolean; const cGetGoodsExists = 'select * from GoodsInfo where %s=''%s'''; cGetGoodsExists2 = cGetGoodsExists + ' and (Guid <> ''%s'')'; var lStrSql: string; iResult: Integer; begin Result := False; if Trim(edtGoodsID.Text) = '' then begin edtGoodsID.SetFocus; ShowMsg('商品编码不能为空!'); Exit; end; if Trim(edtGoodsName.Text) = '' then begin edtGoodsName.SetFocus; ShowMsg('商品名称不能为空!'); Exit; end; if Trim(edtGoodsPYM.Text) = '' then begin edtGoodsPYM.SetFocus; ShowMsg('助记码不能为空!'); Exit; end; // 需要判断商品编码、商品条码、商品名称不能为空 // 通过SQL上后台进行比对 if FAction = 'Append' then lStrSql := Format(cGetGoodsExists, ['GoodsID', Trim(edtGoodsID.Text)]) else lStrSql := Format(cGetGoodsExists2, ['GoodsID', Trim(edtGoodsID.Text), FGuid]); iResult := DBAccess.DataSetIsEmpty(lStrSql); if iResult = -1 then begin ShowMsg('判断商品编码是否重复失败!'); Exit; end; if iResult = 0 then begin ShowMsg('当前商品编码已经存在,请重新输入!'); Exit; end; if FAction = 'Append' then lStrSql := Format(cGetGoodsExists, ['GoodsName', Trim(edtGoodsName.Text)]) else lStrSql := Format(cGetGoodsExists2, ['GoodsName', Trim(edtGoodsName.Text), FGuid]); iResult := DBAccess.DataSetIsEmpty(lStrSql); if iResult = -1 then begin ShowMsg('判断商品名称是否重复失败!'); Exit; end; if iResult = 0 then begin ShowMsg('当前商品名称已经存在,请重新输入!'); Exit; end; if Trim(edtGoodsBarCode.Text) <> '' then begin if FAction = 'Append' then lStrSql := Format(cGetGoodsExists, ['GoodsBarCode', Trim(edtGoodsBarCode.Text)]) else lStrSql := Format(cGetGoodsExists2, ['GoodsBarCode', Trim(edtGoodsBarCode.Text), FGuid]); iResult := DBAccess.DataSetIsEmpty(lStrSql); if iResult = -1 then begin ShowMsg('判断商品条码是否重复失败!'); Exit; end; if iResult = 0 then begin ShowMsg('当前商品条码已经存在,请重新输入!'); Exit; end; end; Result := True; end; procedure TFrmGoodsInfoEdit.btnOkClick(Sender: TObject); begin if not BeforeExecute then Exit; if not DoExecute then Exit; if (FAction = 'Append') and (edtNew.Checked) then begin ClearControls; edtGoodsID.SetFocus; Exit; end; ModalResult := mrOk; end; procedure TFrmGoodsInfoEdit.ClearControls; begin edtGoodsID.Text := ''; edtGoodsName.Text := ''; edtGoodsBarCode.Text := ''; edtGoodsPYM.Text := ''; edtGoodsType.Text := ''; edtGoodsUnit.Text := ''; edtGoodsPrice.Value := 0; cbbClassGuid.ItemIndex := -1; edtRemark.Text := ''; end; function TFrmGoodsInfoEdit.DoExecute: Boolean; begin Result := False; with FDataSet do begin if FAction = 'Append' then begin Append; FindField('Guid').AsString := CreateGuid; end else Edit; FindField('GoodsID').AsString := Trim(edtGoodsID.Text); FindField('GoodsName').AsString := Trim(edtGoodsName.Text); FindField('GoodsBarCode').AsString := Trim(edtGoodsBarCode.Text); FindField('GoodsPYM').AsString := Trim(edtGoodsPYM.Text); FindField('GoodsType').AsString := Trim(edtGoodsType.Text); FindField('GoodsUnit').AsString := Trim(edtGoodsUnit.Text); FindField('GoodsPrice').AsCurrency := edtGoodsPrice.Value; //FindField('ClassGuid').AsString := cbbClassGuid.EditValue; FindField('Remark').AsString := Trim(edtRemark.Text); Post; if not DBAccess.ApplyUpdates('GoodsInfo', FDataSet) then begin FDataSet.CancelUpdates; ShowMsg('商品信息保存失败!'); Exit; end; MergeChangeLog; end; Result := True; end; procedure TFrmGoodsInfoEdit.edtGoodsNamePropertiesChange(Sender: TObject); begin inherited; edtGoodsPYM.Text := GetPYM(Trim(edtGoodsName.Text)); end; procedure TFrmGoodsInfoEdit.FormShow(Sender: TObject); begin inherited; edtNew.Visible := FAction = 'Append'; ClearControls; if FAction = 'Edit' then begin with FDataSet do begin FGuid := FindField('Guid').AsString; edtGoodsID.Text := FindField('GoodsID').AsString; edtGoodsName.Text := FindField('GoodsName').AsString; edtGoodsBarCode.Text := FindField('GoodsBarCode').AsString; edtGoodsPYM.Text := FindField('GoodsPYM').AsString; edtGoodsType.Text := FindField('GoodsType').AsString; edtGoodsUnit.Text := FindField('GoodsUnit').AsString; edtGoodsPrice.Value := FindField('GoodsPrice').AsCurrency; //cbbClassGuid.EditValue := FindField('ClassGuid').AsString; edtRemark.Text := FindField('Remark').AsString; end; end; end; class function TFrmGoodsInfoEdit.ShowGoodsInfoEdit(DataSet: TClientDataSet; AAction: string): Boolean; begin with TFrmGoodsInfoEdit.Create(nil) do begin try FDataSet := DataSet; FAction := AAction; Result := ShowModal = mrOk; finally Free; end; end; end; end.
unit TAudioInputDemo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AudioIO, ExtCtrls, Buttons, ComCtrls, MMSYSTEM, FFTReal, Math; type TForm1 = class(TForm) StartButton: TButton; Timer1: TTimer; StopButton: TButton; RunStatusLabel: TLabel; BufferStatusLabel: TLabel; TimeStatusLabel: TLabel; Panel1: TPanel; RecordSpeedButton: TSpeedButton; ProgressBar1: TProgressBar; MaxLabel: TLabel; AudioIn1: TAudioIn; Button1: TButton; Image1: TImage; Timer2: TTimer; TbVol: TTrackBar; Image2: TImage; procedure StartButtonClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure AudioIn1Stop(Sender: TObject); procedure UpdateStatus; procedure StopButtonClick(Sender: TObject); procedure RecordSpeedButtonClick(Sender: TObject); function AudioIn1BufferFilled(Buffer: PAnsiChar; var Size: Integer): Boolean; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure Button1Click(Sender: TObject); procedure Timer2Timer(Sender: TObject); private { Private declarations } public { Public declarations } Min, Max : Integer; TempMax : Integer; end; const RecBuffSize = 4096; var Form1: TForm1; AudioBuffer: array[0..RecBuffSize] of Integer; Audio_pflt: pflt_array; FFT_L,FFT_R: pflt_array; FFTOutput: pflt_array; FFT: TFFTReal; {obiekt FFT} FFT_Out: array[0..RecBuffSize div 2] of Double; Osc_Out: array[0..RecBuffSize div 2] of Double; implementation {$R *.DFM} procedure TForm1.StartButtonClick(Sender: TObject); begin If (Not AudioIn1.Start(AudioIn1)) Then ShowMessage(AudioIn1.ErrorMessage) Else Begin Min := 0; Max := 0; RecordSpeedButton.Down := TRUE; End; end; function TForm1.AudioIn1BufferFilled(Buffer: PAnsiChar; var Size: Integer): Boolean; Var SP : ^SmallInt; i, N, v : Integer; xMin, xMax : Integer; var a : Integer; VolDiv, c: Double; var DataP: Pointer; {wskaźnik do tablicy zawierającej sygnał} TmpSI: SmallInt; {zmienna do przepisywania sygnału na tablicę} LC: Word; dd: Ansichar; begin N := Size Div 2; SP := Pointer(Buffer); xMin := SP^; xMax := xMin; For i := 0 to N-1 Do Begin v := SP^; Audio_pflt[i] := SP^; Inc(SP); If (xMin > v) Then xMin := v; If (xMax < v) Then xMax := v; End; If (Min > xMin) Then Min := xMin; If (Max < xMax) Then Max := xMax; TempMax := xMax; If (Abs(xMin) > xMax) Then TempMax := Abs(xMin); //for n := 0 to 2048 do //Audio_pflt[n] := AudioBuffer[n]; FFT.do_fft(FFTOutput,Audio_pflt); //obliczenie FFT for LC:=0 to (RecBuffSize div 2)-1 do //obliczenie ABS(FFT) FFT_L[LC]:=Sqrt( Sqr(FFTOutput^[ LC ]) + Sqr(FFTOutput^[ LC+(RecBuffSize div 2) ]) ); VolDiv := 25+400*power(2-log10(100-TbVol.Position/10),3); // VolR := 0; VolR := 0; //Audio_R, Audio_L - tablice zmiennych z probkami dla oscylatora (512 probek) for a := 0 to RecBuffSize div 2 do begin Osc_Out[a] := Audio_pflt[a] / VolDiv; end; VolDiv := 3000+110000*power(2-log10(100-TbVol.Position/10),3); // ustalenie dzielnika glosnosci for a:=0 to RecBuffSize div 2 do begin // a (BUFOR_SIZE div 2)-1 c := FFT_L[a] - 10; c := 3*(c/VolDiv)*(1+(a/10)); // liniowy if c < 0 then c := 0; FFT_Out[a] := c; end; Result := TRUE; end; Procedure TForm1.UpdateStatus; begin With AudioIn1 Do If (AudioIn1.Active) Then Begin RunStatusLabel.Caption := 'Started'; BufferStatusLabel.Caption := Format('Queued: %3d; Processed: %3d',[QueuedBuffers, ProcessedBuffers]); TimeStatusLabel.Caption := Format('Seconds %.3n',[ElapsedTime]); End Else Begin RunStatusLabel.Caption := 'Stopped'; BufferStatusLabel.Caption := ''; TimeStatusLabel.Caption := ''; End; { Update the progress bar } If (AudioIn1.Active) Then Begin ProgressBar1.Position := Round(100*TempMax/36768.0); If (Abs(Min) > Max) Then Max := Abs(Min); MaxLabel.Caption := Format('Max %5d; Peak %5d',[Max,TempMax]); End Else Begin ProgressBar1.Position := 0; MaxLabel.Caption := ''; End; End; procedure TForm1.Timer1Timer(Sender: TObject); begin UpdateStatus; end; procedure TForm1.AudioIn1Stop(Sender: TObject); begin RecordSpeedButton.Down := FALSE; end; procedure TForm1.StopButtonClick(Sender: TObject); begin AudioIn1.StopAtOnce; end; procedure TForm1.RecordSpeedButtonClick(Sender: TObject); begin If (RecordSpeedButton.Down) Then StartButtonClick(Sender) Else AudioIn1.StopAtOnce; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caNone; AudioIn1.StopAtOnce; Application.ProcessMessages; //Sleep(300); Application.Terminate; end; procedure TForm1.FormCreate(Sender: TObject); begin GetMem(Audio_pflt,RecBuffSize*sizeof_flt); //GetMem(Audio_R,RecBuffSize*sizeof_flt); GetMem(FFT_L,RecBuffSize*sizeof_flt); GetMem(FFT_R,RecBuffSize*sizeof_flt); GetMem(FFTOutput,RecBuffSize*sizeof_flt); FFT:=TFFTReal.Create(RecBuffSize); end; Procedure CzyscTablice(PTablica: pflt_array; PTablicaLen: Cardinal); var LC: Cardinal; begin for LC:=0 to PTablicaLen-1 do PTablica^[LC]:=0; end; procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin Timer2.Enabled := False; FFT.Free; // Dispose(Audio_L); // Dispose(Audio_R); Dispose(FFT_L); Dispose(FFT_R); Dispose(FFTOutput); end; procedure TForm1.Button1Click(Sender: TObject); Var s: String; n: Integer; begin //for n := 1 to 30 do // s := s + Inttostr(Tablica[n]) + #13; //Showmessage(s); end; procedure TForm1.Timer2Timer(Sender: TObject); var y, tn: Integer; sd: array of TPoint; begin Image2.Canvas.Brush.Color := clGreen; Image1.Canvas.Rectangle(0,0,Image1.Width,Image1.Height); Image2.Canvas.Rectangle(0,0,Image2.Width,Image2.Height); Image1.Canvas.Pen.Color:=clLime; setLength(sd,Image1.Width + 2); // pierwszy punkt tablicy (lewy dolny rog) sd[0].X := 0; sd[0].Y := Image1.Height-1; // ostatni punkt tablicy (prawy dolny rog) sd[Image1.Width + 1].X := Image1.Width-1; sd[Image1.Width + 1].Y := Image1.Height-1; for tn := 0 to Image1.Width - 1 do begin sd[tn+1].X := tn; // 928 - wartosc dla 20kHz // 1023 - wartosc dla 22,05kHz sd[tn+1].Y := Image1.Height - Round((Image1.Height/30000)* FFT_Out[Round((tn/Image1.Width)*2048 )]); if sd[tn+1].Y < 0 then sd[tn+1].Y := 0; end; Image1.Canvas.Pen.Color := clLime; Image1.Canvas.Brush.Color := clGreen; // Brush.Style := bsDiagCross; // Brush.Bitmap := ImgDisplayTloAlfa; Image1.Canvas.Polygon(sd); Image2.Canvas.Pen.Color:=clYellow; y := Round(Osc_Out[0]); Image2.Canvas.MoveTo(0, Image2.Height div 2 + y); // rozpocznij od punktu Y for tn := 0 to Image2.Width do begin y := Round(Osc_Out[Round((tn/(Image2.Width))*(RecBuffSize div 2))] * (Image2.Height div 150)); y := Round(y / 10); y := Image2.Height div 2 + y; // przesun do polowy if y < 0 then y := 0; if y > Image2.Height -1 then y := Image2.Height - 1; Image2.Canvas.LineTo(tn, y ); end; end; end.
unit AProspects; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, BotaoCadastro, StdCtrls, Buttons, Grids, DBGrids, Tabela, DBKeyViolation, Componentes1, ExtCtrls, PainelGradiente, Db, DBTables, ComCtrls, Graficos, Localizacao, Mask, numericos, Menus, Constantes, DBClient; type TFProspects = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; GridIndice1: TGridIndice; Prospect: TSQL; DataProspect: TDataSource; ProspectCODPROSPECT: TFMTBCDField; ProspectNOMPROSPECT: TWideStringField; ProspectNOMFANTASIA: TWideStringField; ProspectTIPPESSOA: TWideStringField; ProspectDESENDERECO: TWideStringField; ProspectDESCIDADE: TWideStringField; ProspectDESFONE1: TWideStringField; ProspectDATCADASTRO: TSQLTimeStampField; ProspectDESMEIODIVULGACAO: TWideStringField; CPeriodo: TCheckBox; EDatInicio: TCalendario; EDatFim: TCalendario; Label2: TLabel; PGraficos: TCorPainelGra; BitBtn4: TBitBtn; PanelColor5: TPanelColor; Label17: TLabel; Label18: TLabel; BMeioDivulgacao: TBitBtn; BFechaGrafico: TBitBtn; BVendedor: TBitBtn; BProduto: TBitBtn; BData: TBitBtn; BFlag: TBitBtn; BCondicao: TBitBtn; BEstado: TBitBtn; GraficosTrio: TGraficosTrio; Label11: TLabel; EVendedor: TEditLocaliza; SpeedButton4: TSpeedButton; LNomVendedor: TLabel; Localiza: TConsultaPadrao; ENome: TEditColor; Label1: TLabel; ENomeFantasia: TEditColor; Label3: TLabel; CContatovendedor: TCheckBox; PopupMenu1: TPopupMenu; BMes: TBitBtn; NovaAgenda1: TMenuItem; PanelColor4: TPanelColor; N2: TMenuItem; TelemarketingReceptivo1: TMenuItem; Label5: TLabel; SpeedButton1: TSpeedButton; LMeioDivulgacao: TLabel; EMeioDivulgacao: TEditLocaliza; ECidade: TEditColor; Label7: TLabel; Label6: TLabel; ERamoAtividade: TEditLocaliza; SpeedButton2: TSpeedButton; Label8: TLabel; BotaoCadastrar1: TBotaoCadastrar; BotaoAlterar1: TBotaoAlterar; BotaoConsultar1: TBotaoConsultar; BotaoExcluir1: TBotaoExcluir; BGraficos: TBitBtn; BProdutos: TBitBtn; BContatos: TBitBtn; BFechar: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BotaoCadastrar1AntesAtividade(Sender: TObject); procedure BotaoCadastrar1DepoisAtividade(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure CPeriodoClick(Sender: TObject); procedure BotaoAlterar1Atividade(Sender: TObject); procedure BotaoExcluir1DepoisAtividade(Sender: TObject); procedure BotaoExcluir1DestroiFormulario(Sender: TObject); procedure BGraficosClick(Sender: TObject); procedure BFechaGraficoClick(Sender: TObject); procedure BMeioDivulgacaoClick(Sender: TObject); procedure BVendedorClick(Sender: TObject); procedure BProdutoClick(Sender: TObject); procedure BDataClick(Sender: TObject); procedure BFlagClick(Sender: TObject); procedure BCondicaoClick(Sender: TObject); procedure BEstadoClick(Sender: TObject); procedure ENomeExit(Sender: TObject); procedure ENomeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ENomeFantasiaExit(Sender: TObject); procedure ENomeFantasiaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BMesClick(Sender: TObject); procedure NovaAgenda1Click(Sender: TObject); procedure GridIndice1Ordem(Ordem: String); procedure BProdutosClick(Sender: TObject); procedure BContatosClick(Sender: TObject); procedure TelemarketingReceptivo1Click(Sender: TObject); procedure ECidadeExit(Sender: TObject); procedure ECidadeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } VprOrdem, VprNome, VprNomFantasia, VprCidade : String; procedure AtualizaConsulta; procedure AdicionaFiltros(VpaSelect : TStrings); function RRodapeGrafico : String; procedure GraficoMeioDivulgacao; procedure GraficoVendedor; procedure GraficoCidade; procedure GraficoRamoAtividade; procedure GraficoProfissao; procedure GraficoData; procedure GraficoMes; procedure GraficoUF; public { Public declarations } end; var FProspects: TFProspects; implementation uses APrincipal, ANovoProspect, Funsql,fundata, ANovaProposta, ANovaAgendaProspect, AProdutosProspect, AContatosProspect, ANovoTelemarketingProspect; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFProspects.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } EDatInicio.dateTime :=PrimeiroDiaMes(date) ; EDatFim.DateTime := UltimoDiaMes(date); VprOrdem := 'order by PRO.CODPROSPECT '; AtualizaConsulta; end; { ******************* Quando o formulario e fechado ************************** } procedure TFProspects.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFProspects.AtualizaConsulta; var VpfPosicao : TBookmark; begin VpfPosicao := Prospect.GetBookmark; Prospect.close; Prospect.sql.clear; Prospect.sql.add('select CODPROSPECT, NOMPROSPECT, NOMFANTASIA, TIPPESSOA, DESENDERECO, DESCIDADE, DESFONE1, DATCADASTRO, MEI.DESMEIODIVULGACAO '+ ' from PROSPECT PRO, MEIODIVULGACAO MEI ' + ' Where ' +SQLTextoRightJoin('PRO.CODMEIODIVULGACAO','MEI.CODMEIODIVULGACAO')); AdicionaFiltros(Prospect.sql); Prospect.SQL.add(VprOrdem); GridIndice1.ALinhaSQLOrderBy := Prospect.sql.count - 1; Prospect.open; try Prospect.GotoBookmark(VpfPosicao); except end; Prospect.FreeBookmark(VpfPosicao); VprNome := ENome.Text; VprNomFantasia := ENomeFantasia.text; VprCidade := ECidade.Text; end; {******************************************************************************} procedure TFProspects.AdicionaFiltros(VpaSelect : TStrings); begin if CPeriodo.Checked then VpaSelect.add('and ('+ SQLTextoDataEntreAAAAMMDD('PRO.DATCADASTRO',EDatInicio.DAtetime,incdia(EDatFim.datetime,1),false)+ ' OR EXISTS (SELECT CON.CODPROSPECT FROM CONTATOPROSPECT CON '+ ' Where CON.CODPROSPECT = PRO.CODPROSPECT '+ SQLTextoDataEntreAAAAMMDD('CON.DATCADASTRO',EDatInicio.DateTime,EDatFim.Datetime,true)+'))'); if EVendedor.AInteiro <> 0 then VpaSelect.add('AND PRO.CODVENDEDOR = '+ EVendedor.Text); if ENome.Text <> '' then VpaSelect.Add('AND PRO.NOMPROSPECT LIKE '''+ENome.Text +'%'''); if ENomeFantasia.Text <> '' then VpaSelect.Add('AND PRO.NOMFANTASIA LIKE '''+ENomeFantasia.Text+'%'''); if CContatovendedor.Checked then VpaSelect.Add('AND PRO.INDCONTATOVENDEDOR = ''N'''); if (puCRSomenteSuspectDoVendedor in varia.PermissoesUsuario) then VpaSelect.Add('and PRO.CODVENDEDOR in '+Varia.CodigosVendedores); if EMeioDivulgacao.AInteiro <> 0 then VpaSelect.add('and PRO.CODMEIODIVULGACAO = ' +EMeioDivulgacao.Text); if ECidade.Text <> '' then VpaSelect.add('and PRO.DESCIDADE LIKE '''+ECidade.Text+'%'''); if ERamoAtividade.AInteiro <> 0 then VpaSelect.Add('AND PRO.CODRAMOATIVIDADE = '+ERamoAtividade.Text); end; {******************************************************************************} procedure TFProspects.GraficoMeioDivulgacao; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, MEI.DESMEIODIVULGACAO '+ ' from PROSPECT PRO, MEIODIVULGACAO MEI '+ ' Where PRO.CODMEIODIVULGACAO = MEI.CODMEIODIVULGACAO'); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY MEI.DESMEIODIVULGACAO'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'DESMEIODIVULGACAO'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Meio Divulgação'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Meio Divulgação'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoVendedor; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, VEN.C_NOM_VEN VENDEDOR '+ ' from PROSPECT PRO, CADVENDEDORES VEN '+ ' Where PRO.CODVENDEDOR = VEN.I_COD_VEN'); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY VEN.C_NOM_VEN'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'VENDEDOR'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Vendedores'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Vendedor'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoCidade; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, PRO.DESCIDADE CIDADE '+ ' from PROSPECT PRO '+ ' Where PRO.CODPROSPECT = PRO.CODPROSPECT '); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY PRO.DESCIDADE'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'CIDADE'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Cidades'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Cidade'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoRamoAtividade; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, RAM.NOM_RAMO_ATIVIDADE CAMPO '+ ' from PROSPECT PRO, RAMO_ATIVIDADE RAM '+ ' Where '+SQLTextoRightJoin('PRO.CODRAMOATIVIDADE','RAM.COD_RAMO_ATIVIDADE')); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY RAM.NOM_RAMO_ATIVIDADE'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'CAMPO'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Ramo Atividades'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Ramo Atividade'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoProfissao; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, PRF.C_NOM_PRF CAMPO '+ ' from PROSPECT PRO, CADPROFISSOES PRF '+ ' Where '+SQLTextoRightJoin('PRO.CODPROFISSAOCONTATO','PRF.I_COD_PRF ')); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY PRF.C_NOM_PRF'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'CAMPO'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Profissão Contato'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Profissão Contato'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoData; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, PRO.DATCADASTRO CAMPO '+ ' from PROSPECT PRO '+ ' Where PRO.CODPROSPECT = PRO.CODPROSPECT '); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY PRO.DATCADASTRO'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'CAMPO'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Data'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Data'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoMes; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, (YEAR(PRO.DATCADASTRO) *100)+month(PRO.DATCADASTRO) DATA1, month(PRO.DATCADASTRO)||''/''|| year(PRO.DATCADASTRO) DATA'+ ' from PROSPECT PRO '+ ' Where PRO.CODPROSPECT = PRO.CODPROSPECT '); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.Add(' group by DATA1, DATA ' + ' order by 2'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'DATA'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - Mês'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'Mes'; graficostrio.execute; end; {******************************************************************************} procedure TFProspects.GraficoUF; var VpfComandoSql : TStringList; begin VpfComandoSql := TStringList.Create; VpfComandoSql.add('Select count(*) Qtd, DESUF CAMPO '+ ' from PROSPECT PRO '+ ' Where PRO.CODPROSPECT = PRO.CODPROSPECT '); graficostrio.info.CampoValor := 'Qtd'; graficostrio.info.TituloY := 'Quantidade'; AdicionaFiltros(VpfComandosql); VpfComandosql.add(' GROUP BY DESUF'); graficostrio.info.ComandoSQL := VpfComandoSql.text; graficostrio.info.CampoRotulo := 'CAMPO'; graficostrio.info.TituloGrafico := 'Gráfico Suspect´s - UF'; graficostrio.info.RodapeGrafico := RRodapeGrafico; graficostrio.info.TituloFormulario := 'Gráfico de Suspect´s'; graficostrio.info.TituloX := 'UF'; graficostrio.execute; end; {******************************************************************************} function TFProspects.RRodapeGrafico : String; begin result := ''; if CPeriodo.Checked then result := 'Período de :'+ FormatDateTime('DD/MM/YYYY',EDatInicio.DateTime)+ ' até : '+FormatDateTime('DD/MM/YYYY',EDatFim.DateTime); if EVendedor.AInteiro <> 0 then result := result + ' - Vendedor : '+ LNomVendedor.Caption; if EMeioDivulgacao.AInteiro <> 0 then result := result + ' - Meio Div. : '+LMeioDivulgacao.caption; if ECidade.text <> '' then Result := result + ' - Cidade : '+ECidade.Text; end; {******************************************************************************} procedure TFProspects.BotaoCadastrar1AntesAtividade(Sender: TObject); begin FNovoProspect := TFNovoProspect.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoProspect')); end; procedure TFProspects.BotaoCadastrar1DepoisAtividade(Sender: TObject); begin FNovoProspect.ShowModal; AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFProspects.CPeriodoClick(Sender: TObject); begin AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.BotaoAlterar1Atividade(Sender: TObject); begin FNovoProspect.LocalizaProspect(ProspectCODPROSPECT.AsInteger); end; {******************************************************************************} procedure TFProspects.BotaoExcluir1DepoisAtividade(Sender: TObject); begin FNovoProspect.Show; end; {******************************************************************************} procedure TFProspects.BotaoExcluir1DestroiFormulario(Sender: TObject); begin FNovoProspect.close; AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.BGraficosClick(Sender: TObject); begin PanelColor1.Enabled := false; GridIndice1 .Enabled := false; PGraficos.Top := 50; PGraficos.Visible := true; end; {******************************************************************************} procedure TFProspects.BFechaGraficoClick(Sender: TObject); begin PanelColor1.Enabled := true; GridIndice1 .Enabled := true; PGraficos.Visible := false; end; {******************************************************************************} procedure TFProspects.BMeioDivulgacaoClick(Sender: TObject); begin GraficoMeioDivulgacao; end; {******************************************************************************} procedure TFProspects.BVendedorClick(Sender: TObject); begin GraficoVendedor; end; {******************************************************************************} procedure TFProspects.BProdutoClick(Sender: TObject); begin GraficoCidade; end; {******************************************************************************} procedure TFProspects.BDataClick(Sender: TObject); begin GraficoRamoAtividade; end; {******************************************************************************} procedure TFProspects.BFlagClick(Sender: TObject); begin GraficoProfissao; end; {******************************************************************************} procedure TFProspects.BCondicaoClick(Sender: TObject); begin GraficoData; end; {******************************************************************************} procedure TFProspects.BEstadoClick(Sender: TObject); begin GraficoUF; end; {******************************************************************************} procedure TFProspects.ENomeExit(Sender: TObject); begin if VprNome <> ENome.Text then AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.ENomeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then ENomeExit(ENome); end; {******************************************************************************} procedure TFProspects.ENomeFantasiaExit(Sender: TObject); begin if ENomeFantasia.Text <> VprNomFantasia then AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.ENomeFantasiaKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then ENomeFantasiaExit(ENomeFantasia); end; {******************************************************************************} procedure TFProspects.BMesClick(Sender: TObject); begin GraficoMes; end; {******************************************************************************} procedure TFProspects.NovaAgenda1Click(Sender: TObject); begin if ProspectCODPROSPECT.AsInteger <> 0 then begin FNovaAgendaProspect:= TFNovaAgendaProspect.CriarSDI(Self,'',True); FNovaAgendaProspect.NovaAgendaProspect(ProspectCODPROSPECT.AsInteger); FNovaAgendaProspect.Free; end; end; {******************************************************************************} procedure TFProspects.GridIndice1Ordem(Ordem: String); begin VprOrdem := Ordem; end; {******************************************************************************} procedure TFProspects.BProdutosClick(Sender: TObject); begin if ProspectCODPROSPECT.AsInteger <> 0 then begin FProdutosProspect:= TFProdutosProspect.CriarSDI(Self,'',True); FProdutosProspect.CadastraProdutos(ProspectCODPROSPECT.AsInteger); FProdutosProspect.Free; end; end; procedure TFProspects.BContatosClick(Sender: TObject); begin if ProspectCODPROSPECT.AsInteger <> 0 then begin FContatosProspect:= TFContatosProspect.CriarSDI(Application,'',True); FContatosProspect.CadastraContatos(ProspectCODPROSPECT.AsInteger); FContatosProspect.Free; end; end; {******************************************************************************} procedure TFProspects.TelemarketingReceptivo1Click(Sender: TObject); begin if not Prospect.Eof then begin FNovoTeleMarketingProspect:= TFNovoTeleMarketingProspect.CriarSDI(Application,'',True); FNovoTeleMarketingProspect.TeleMarketingProspect(ProspectCODPROSPECT.AsInteger); FNovoTeleMarketingProspect.Free; end; end; procedure TFProspects.ECidadeExit(Sender: TObject); begin if ECidade.Text <> VprCidade then AtualizaConsulta; end; {******************************************************************************} procedure TFProspects.ECidadeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then ECidadeExit(ECidade); end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFProspects]); end.
program Julia; {from: THE BEAUTY OF FRACTALS by Peitgen & Richter } { pp 189,190. Experiment 1: Basins of Attraction and Julia Sets } { Turbo Pascal 4.0 implementation by Art Steinmetz } (* {$DEFINE MATH} *) {$IFDEF MATH} {$N+} {$ELSE} {$N-} {$ENDIF} {$S-} {no stack checking} {$R-} {no range checking} uses CRT, { KeyPressed, ReadKey } Graph, { CloseGraph, DetectGraph, InitGraph, GetMaxColor, GetBkColor, GetMaxX, GetMaxY, GetModeRange, PutPixel, SetFillStyle, FillPoly, SetColor } Drivers, { All available graphics drivers } Windows, { OpenWindow, CloseWindow } GetField, { AddExitKey, Field_Str, Do_Fields, ReleaseFields, NOBOX, LEFT } KeyCodes, { ESC, Break, F10 } SaveScrn, {SaveScreen, RestoreScreen} StopWtch {StartWatch, SplitTime} ; (* CONST { suggested values } Xmin = -1.25; Xmax = 1.25; Ymin = -1.25; Ymax = 1.25; M = 100; { assume infinite attractor if (x^2)(y^2) > M} K = 200; { iterations } p = 0.32; { c = p + qi } q = 0.04; *) TYPE {$IFDEF Math} FLOAT = EXTENDED; {$ELSE} FLOAT = REAL; {$ENDIF} InputParamRec = RECORD Xmin, Xmax, Ymin, Ymax : FLOAT; M, { assume infinite attractor if (x^2)(y^2) > M} K { iterations } : INTEGER; p, q { c = p + qi } : FLOAT; Hpoints, Vpoints {points to render} : INTEGER; END; StrArray = ARRAY[0..9] OF String; VAR VRes, Hres, XWidth, YWidth : INTEGER; dx, dy : FLOAT; { parameter change per pixel } ColorRange : INTEGER; done, Symmetry : BOOLEAN; Prm : InputParamRec; PrmStr : StrArray; { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} FUNCTION Abort : BOOLEAN; BEGIN IF KeyPressed THEN Abort := ((ReadKey = CHAR(Break)) OR (ReadKey = CHAR(ESC))) ELSE Abort := FALSE; END; { Abort } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE WaitForExit; VAR ch : CHAR; t : String; BEGIN Str(SplitTime:5:2,t); OutText('Elapsed Time '+t+' PRESS ANY KEY TO EXIT'); ch := ReadKey; END; {Wait for Exit} {++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++} procedure ErrorMsg(msg : string); CONST HalfCols = 40; top = 12; bottom = 14; VAR Spaces,i, left, right, len : INTEGER; Error : BYTE; procedure Beep; BEGIN Sound(500); Delay(500); NoSound; END; begin len := length(msg); right := HalfCols + len + 2; left := HalfCols - Len + 2; IF left < 1 THEN BEGIN left := 1; right := HalfCols * 2 - 1; END; OpenWindow(left,top,right,bottom,White,Red,Error); IF Error = 0 THEN begin {do text centering} spaces := ( right-left-2-len ) div 2; if spaces > 0 then for i := 1 to spaces do write(' '); Write(msg); Beep; Delay(500); CloseWindow; end; done := FALSE; end; { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE InitFields; BEGIN TextBackground(White); ClrScr; TextColor(Red); GotoXY(2,1); Writeln('JULIA SET GENERATOR'); GotoXY(10,3); Write('X,Y Range of -1.5 to 1.5 is plenty'); GotoXY(10,4); Write('If Min`s and Max`s are not equal rendering time will double.'); GotoXY(20,10); Write('Plot points will not exceed screen resolution Use "MAX".'); GotoXY(20,16); Write('c := p + qi. Choose p and q between -1.0 and 1.0.'); GotoXY(2,22); Write('<Esc> to quit. <F10> to draw. <Ctrl>C quits drawing.'); TextColor(Blue); SetUp_Field(White,White,Blue,Black,' '); AddExitKey(F10); Field_Str(10, 6,6,3,'Min X',PrmStr[0],'N',NOBOX,LEFT); Field_Str(10, 8,6,3,'Max X',PrmStr[1],'N',NOBOX,LEFT); Field_Str(10,10,6,3,'Min Y',PrmStr[2],'N',NOBOX,LEFT); Field_Str(10,12,6,3,'Max Y',PrmStr[3],'N',NOBOX,LEFT); Field_Str(50, 6,6,3,'Threshold (use 100)',PrmStr[4],'N',NOBOX,LEFT); Field_Str(50, 8,6,3,'Iterations (use 200)',PrmStr[5],'N',NOBOX,LEFT); Field_Str(50,12,6,3,'Plot points in X direction',PrmStr[6],'L',NOBOX,LEFT); Field_Str(50,14,6,3,'Plot points in Y direction',PrmStr[7],'L',NOBOX,LEFT); Field_Str(35,18,6,3,'p:', PrmStr[8],'N',NOBOX,LEFT); Field_Str(45,18,6,3,'q:',PrmStr[9],'N',NOBOX,LEFT); END; {InitFields} FUNCTION GetInput(VAR Inp : InputParamRec) : BOOLEAN; CONST SillyRes = 2000; { number sure to exceed device resolution } VAR errcode, ExitKey : INTEGER; BEGIN REPEAT Do_Fields(ExitKey); IF ExitKey = ESC THEN done := FALSE ELSE WITH Prm DO BEGIN done := TRUE; Val(PrmStr[0],Xmin,errcode); IF errcode > 0 then ErrorMsg('Bad Xmin'); Val(PrmStr[1],Xmax,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad Xmax'); Val(PrmStr[2],Ymin,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad Ymin'); Val(PrmStr[3],Ymax,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad Ymax'); Val(PrmStr[4],K,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad Threshold'); Val(PrmStr[5],M,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad Iterations'); Val(PrmStr[6],Hpoints,errcode); IF done THEN IF errcode > 0 then IF (PrmStr[6] = 'MAX') or (PrmStr[6] = 'max') THEN Hpoints := SillyRes ELSE ErrorMsg('X Points'); Val(PrmStr[7],Vpoints,errcode); IF done THEN IF errcode > 0 then IF (PrmStr[7] = 'MAX') or (PrmStr[7] = 'max') THEN Vpoints := SillyRes ELSE ErrorMsg('Y Points'); Val(PrmStr[8],p,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad p'); Val(PrmStr[9],q,errcode); IF done THEN IF errcode > 0 then ErrorMsg('Bad q'); END; {with} UNTIL (done = TRUE) or (ExitKey = ESC); GetInput := done; END; {GetInput } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE Initialize; BEGIN { set scaling } XWidth := 1; YWidth := 1; WITH Prm DO BEGIN IF Hpoints < Hres THEN BEGIN XWidth := Hres div Hpoints; Hres := Hpoints * XWidth; { rescale } END ELSE Hpoints := Hres; IF Vpoints < Vres THEN BEGIN YWidth := Vres div Vpoints; Vres := Vpoints * YWidth; { rescale } END ELSE Vpoints := Vres; dx := (Xmax-Xmin)/(Hpoints-1); dy := (Ymax-Ymin)/(Vpoints-1); Symmetry := (abs(Xmax+Xmin)<0.0001) AND (abs(Ymax+Ymin)<0.0001); END; {WITH} END; { Initialize } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE OpenGraph; VAR GraphDriver, LoMode, HiMode, GraphMode : INTEGER; BEGIN (* { Register all the drivers } if RegisterBGIdriver(@CGADriverProc) < 0 then ErrorMsg('CGA driver not found'); if RegisterBGIdriver(@EGAVGADriverProc) < 0 then ErrorMsg('EGA/VGAdriver not found'); if RegisterBGIdriver(@HercDriverProc) < 0 then ErrorMsg('Hercdriver not found'); if RegisterBGIdriver(@ATTDriverProc) < 0 then ErrorMsg('AT&Tdriver not found'); if RegisterBGIdriver(@PC3270DriverProc) < 0 then ErrorMsg('PC 3270driver not found'); *) { set graph mode to max res of device (does not support ATT) } DetectGraph(GraphDriver,HiMode); GetModeRange(GraphDriver,LoMode,HiMode); IF GraphDriver < VGA THEN GraphMode := HiMode ELSE GraphMode := LoMode; InitGraph(GraphDriver,GraphMode,''); { set color Range to reserve color 0 for boundary } { (i mod ColorRange + 1) will be choice of Colors } { excluding black } ColorRange := GetMaxColor - 1; Vres := GetMaxY; Hres := GetMaxX; END; { OpenGraph } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE NextPoint(VAR x : FLOAT; VAR y : FLOAT; p,q :FLOAT); { Here's the actual formula } VAR tempX : FLOAT; BEGIN tempX := x; x := (x-y) * (x+y) + p; { FLOAT part } y := (tempX + tempX) * y + q; { imaginary part } END; { NextPoint } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE PutRectangle(x1,y1,x2,y2 : INTEGER; Color : WORD); VAR rect : ARRAY[0..3] OF PointType; BEGIN rect[0].x := x1; rect[0].y := y1; rect[1].x := x1; rect[1].y := y2; rect[2].x := x2; rect[2].y := y2; rect[3].x := x2; rect[3].y := y1; SetColor(GetBkColor); SetFillStyle(SolidFill, Color); FillPoly(4 , rect); END; { PutRectangle } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE DrawCompPoints(x,y : INTEGER; Color : WORD); { plot image symmetric to the origin } BEGIN PutPixel(x,y,color); PutPixel(Prm.Hpoints-x, Prm.Vpoints-y,color); END; { DrawCompPoints } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE DrawCompRect(x1,y1,x2,y2 : INTEGER; Color : WORD); { plot image symmetric to the origin } BEGIN PutRectangle( x1,y1,x2,y2,color); PutRectangle( Hres-x1, Vres-y1, Hres-x2, Vres-y2, color); END; { DrawCompPoints } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE DoPixel(nx,ny : INTEGER); VAR i, Color : INTEGER; r, X, Y : FLOAT; done : BOOLEAN; BEGIN X := Prm.Xmin + nx * dx; Y := Prm.YMin + ny * dy; i := 0; done := FALSE; REPEAT NextPoint(X,Y,Prm.p,Prm.q); r := sqr(X) + sqr(Y); IF (r > Prm.M) or (i = Prm.K) THEN done := TRUE ELSE inc(i); UNTIL done; IF i = Prm.K THEN Color := Black ELSE Color := (i mod ColorRange) + 1; IF Symmetry THEN DrawCompPoints(nx,ny,Color) ELSE PutPixel(nx,ny,Color); END; { DoPixel } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE DoRectangle(nx,ny : INTEGER); VAR i, xpos, ypos, Color : INTEGER; r, X, Y : FLOAT; done : BOOLEAN; BEGIN X := Prm.Xmin + nx * dx; Y := Prm.YMin + ny * dy; i := 0; done := FALSE; REPEAT NextPoint(X,Y,Prm.p,Prm.q); r := sqr(X) + sqr(Y); IF (r > Prm.M) or (i = Prm.K) THEN done := TRUE ELSE inc(i); UNTIL done; IF i = Prm.K THEN Color := Black ELSE Color := (i mod ColorRange) + 1; xpos := nx * Xwidth; ypos := nx * Ywidth; IF Symmetry THEN DrawCompRect(xpos,ypos,xpos+Xwidth,ypos+Ywidth,Color) ELSE PutRectangle(xpos,ypos,xpos+Xwidth,ypos+Ywidth,Color); END; { DoRectangle } { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} PROCEDURE RenderSet; VAR x, y, VHigh, Hhigh : INTEGER; StopRender : BOOLEAN; BEGIN Hhigh := Prm.Hpoints; IF Symmetry THEN Vhigh := Prm.Vpoints DIV 2 ELSE Vhigh := Prm.Vpoints; y := 0; REPEAT BEGIN StopRender := Abort; { Check for ^C once each scan line } IF NOT StopRender THEN FOR x := 0 to Hhigh DO (* this ain't workin yet IF (XWidth > 1) OR (YWidth > 1) THEN DoRectangle(x,y) ELSE *) DoPixel(x,y); INC(y); END; UNTIL (y > Vhigh) OR StopRender; END; {RenderSet} { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} BEGIN {MAIN} InitFields; REPEAT IF GetInput(Prm) THEN BEGIN SaveScreen; OpenGraph; Initialize; StartWatch; RenderSet; WaitForExit; CloseGraph; RestoreScreen; END; UNTIL NOT Done; Release_Fields; END. {Julia} 
Unit myIntegerList; Interface Type oList = record info:integer; next:^oList; end; oPoint = ^oList; nonNegativeNumber = 0..Integer.MaxValue;//множество неотрицательных целых чисел Var pHead,pTail:oPoint;//глобальные переменные - указатели начала и конца i:integer; x:integer; Procedure add(x:integer); Procedure init; Function getOList(count:integer):oPoint; Function getLength(oHead:oPoint):integer; Procedure getUnion(headOne:oPoint;headTwo:oPoint); Function getPHead:oPoint; Procedure printList; Implementation Procedure add(x:integer);//добавление элемента в конец списка var y:oPoint; begin new(y); y^.info:=x; if pHead = nil then begin pHead:=y; pTail:=y; end else begin pTail^.next:=y; pTail:=y; end; end; Procedure init();//иницализация - обнуление указателей начала и конца begin pHead:=nil; pTail:=nil; end; Function getOList(count:integer):oPoint;//получение данных об односвязном списке var newPoint:oPoint; i:nonNegativeNumber; x:integer; begin new(newPoint); init();//иницализация - обнуление указателей начала и конца for i:=1 to count do begin WriteLn('Введите ',i,' - ый элемент'); ReadLn(x); add(x);//добавление элемента в конец списка end; newPoint:=pHead; getOList:=newPoint; end; Function getLength(oHead:oPoint):integer;//возвращает количество элементов в списке var count:integer; begin count:=0; while oHead<>nil do begin count+=1; oHead:=oHead^.next; end; getLength:=count; end; Procedure getUnion(headOne:oPoint;headTwo:oPoint);//упорядоченное объединение двух списков в списке (по факту создание одного списка var isNull:boolean; //и удаление двух прежних) metk:oPoint; begin init(); isNull:=(headOne = nil) or (headTwo = nil); while not isNull do begin if headOne^.info>headTwo^.info then begin add(headTwo^.info);//добавление элемента в конец списка metk:=headTwo; headTwo:=headTwo^.next; dispose(metk); end else begin add(headOne^.info);//добавление элемента в конец списка metk:=headOne; headOne:=headOne^.next; dispose(metk); end; isNull:=(headOne = nil) or (headTwo = nil); end; while headOne<>nil do begin add(headOne^.info);//добавление элемента в конец списка metk:=headOne; headOne:=headOne^.next; dispose(metk); end; while headTwo<>nil do begin add(headTwo^.info);//добавление элемента в конец списка metk:=headTwo; headTwo:=headTwo^.next; dispose(metk); end; end; Function getPHead():oPoint;//возвращает указатель начала списка begin getPHead:=pHead; end; Procedure printList();//вывод элементов однонаправленного списка var metk:oPoint; begin metk:=pHead; while metk<>nil do begin Write(metk^.info,' '); metk:=metk^.next; end; end; Initialization end.
{*******************************************************} { } { Delphi Visual Component Library } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit ActionEditors; // In this module, are editors for action. Code moved from VCLEditors interface uses System.Types, System.SysUtils, System.Classes, System.Actions, System.Generics.Collections, DesignIntf, DesignEditors, Vcl.Graphics, Vcl.ImgList, Vcl.Menus, Vcl.ComCtrls, Vcl.Controls; type {$REGION 'The interaction of action with an IDE. This new code'} /// <summary> /// This class is designed to interact actions and surface of form in IDE. /// The implementation of the methods implemented in inheritors /// </summary> TIDEActions = class public /// <summary> /// This procedure should give some specific properties, such as: ImageIndex. /// </summary> class procedure AssignAction(Source, Destination: TBasicAction); virtual; class function CreateImageLink(const OnChanged: TNotifyEvent): TObject; virtual; /// <summary> /// This procedure create and retrive ImageList with a symbolic image of action to show in the IDE. /// </summary> class function CreateImageList(ActionList: TContainedActionList): TCustomImageList; virtual; /// <summary> /// Class action created by default when you select menu item "New Action" /// </summary> class function DefaultActionClass: TContainedActionClass; virtual; /// <summary> /// The base class of actions that are added to the combobox of available actions in the IDE. /// </summary> class function BaseActionClass: TContainedActionClass; virtual; /// <summary> /// The base class of actions that are added to the combobox of available actions lists in the IDE. /// </summary> class function BaseActionListClass: TContainedActionListClass; virtual; /// <summary> /// This procedure is to create and fill bitmaps with a symbolic image of new action to add in TImageList /// </summary> class procedure CopyImageIfAvailable(const NewAction: TContainedAction; const ActionList: TContainedActionList); virtual; /// <summary> /// This procedure registered changes in TImageList /// </summary> class procedure RegisterImageLink(const ActionList: TContainedActionList; const ImageLink: TObject); virtual; /// <summary> /// This procedure unregistered changes in TImageList /// </summary> class procedure UnregisterImageLink(const ActionList: TContainedActionList; const ImageLink: TObject); virtual; end; TIDEActionsClass = class of TIDEActions; /// <summary> /// You can edit the module is not currently of selected project. The function returns the framework of the current module being edited. /// </summary> function GetFrameworkType: string; /// <summary> /// Adds a class to communicate with the IDE, for a specified framework. /// If a specified framework has already been registered class, then raised an exception. /// To cancel this registration, use the procedure <see cref="UnregisterActionsInFramework"/> /// </summary> /// <param name="FrameworkType"> /// The name of the framework. For example <c>'VCL'</c>, <c>'FMX'</c> /// </param> /// <param name="AIDEActions"> /// The class that is implemented for each platform, it provides /// the interaction of action with an IDE. /// </param> procedure RegisterActionsInFramework(const FrameworkType: string; const AIDEActions: TIDEActionsClass); /// <summary> /// This procedure unregisters a class, performed by the procedure of <see cref="RegisterActionsInFramework"/>. /// </summary> /// <param name="FrameworkType"> /// Name of framework (<c>FMX</c>, <c>VCL</c>) /// </param> procedure UnregisterActionsInFramework(const FrameworkType: string); /// <summary> /// Search a class for interacting action with the IDE, by name of framework. /// <param name="FrameworkType"> /// Name of framework /// </param> /// </summary> /// <returns> /// The registered class for framework. /// If neither of class is not registered, or the name is not specified, /// returns <see cref="vOldIDEActions"/>. If among the registered classes /// is not appropriate, it returns <c>nil</c>. /// </returns> function GetIDEActions(const FrameworkType: string): TIDEActionsClass; overload; /// <summary> /// Search a class for interacting action with the IDE, by list of actions /// </summary> /// <param name="ActionList"> /// The list of actions for which is determined by the framework. /// If <c>nil</c>, is used function <see cref="GetFrameworkType"/> to determine the framework /// and <see cref="GetIDEActions"/> for sherch by FrameworkType /// </param> /// <param name="FrameworkType"> /// Name of framework /// </param> /// <returns> /// The registered class for framework /// </returns> function GetIDEActions(const ActionList: TContainedActionList; var FrameworkType: string): TIDEActionsClass; overload; function GetIDEActionsList(List: TStringList): integer; var /// <summary> /// This global variable that contains a class of TIDEActions in VCL. /// if trimed input param <c>FrameworkType</c> is empty, then used this value /// for compatibility with older applications. /// <para>see <see cref = "CreateAction"/>, <see cref = "EnumRegisteredActions"/>, <see cref = "GetIDEActions"/></para> /// </summary> vOldIDEActions: TIDEActionsClass; {$ENDREGION} {$REGION 'TActionListView. This code moved from VclEditors'} type { TActionListView } TNewActionEvent = procedure(Sender: TObject; const Category: string; ActionClass: TContainedActionClass; ActionList: TContainedActionList) of object; TSelectActionEvent = procedure(Sender: TObject; Action: TContainedAction) of object; TActionListView = class(TCustomListView) private const FDefItemHeight = 17; private FActionList: TContainedActionList; FDesigner: IDesigner; FImageList: TImageList; FNewActnPopupMenu: TPopupMenu; FNewStdActnPopupMenu: TPopupMenu; FStdActionList: TStrings; FTempStringList: TStrings; FIDEActions: TIDEActionsClass; FFrameworkType: string; FOnNewAction: TNewActionEvent; FOnSelectAction: TSelectActionEvent; FMsg: string; procedure AddStdAction(const Category: string; ActionClass: TBasicActionClass; Info: Pointer); procedure AddTempString(const S: string); function CreateMenuItem(const Caption: string; Event: TNotifyEvent; CustomData: Pointer) : TMenuItem; procedure DoNewActionClick(Sender: TObject); procedure DoNewStdActionClick(Sender: TObject); procedure RebuildListView; procedure RebuildPopupMenus; procedure SetDesigner(const Value: IDesigner); procedure ShowPopupMenu(Item: TListItem; PopupMenu: TPopupMenu); procedure DoShowMsg(Sender: TObject); protected procedure CreateWnd; override; function CustomDrawItem(Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage) : Boolean; override; function IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Click; override; property Designer: IDesigner read FDesigner write SetDesigner; property OnNewAction: TNewActionEvent read FOnNewAction write FOnNewAction; property OnSelectAction: TSelectActionEvent read FOnSelectAction write FOnSelectAction; end; {$ENDREGION} {$REGION 'TActionProperty. This code moved from VclEditors'} { TActionProperty } TActionProperty = class(TComponentProperty, IProperty80) private type TRegisteredAction = record Category: string; ActionClass: TBasicActionClass end; private FActionListView: TActionListView; FHost: IPropertyHost; FRegisteredActionList: TList<TRegisteredAction>; procedure CreateNewAction(Sender: TObject; const Category: string; ActionClass: TContainedActionClass; ActionList: TContainedActionList); procedure SelectAction(Sender: TObject; Action: TContainedAction); procedure AddAction(const Category: string; ActionClass: TBasicActionClass; Info: Pointer); public destructor Destroy; override; // IProperty80 procedure Edit(const Host: IPropertyHost; DblClick: Boolean); reintroduce; overload; function GetAttributes: TPropertyAttributes; override; end; {$ENDREGION} {$REGION 'Action Registration. This code moved from VclEditors'} type TNotifyActionListChange = procedure; var NotifyActionListChange: TNotifyActionListChange = nil; procedure RegActions(const ACategory: string; const AClasses: array of TBasicActionClass; AResource: TComponentClass); procedure UnRegActions(const Classes: array of TBasicActionClass); procedure EnumActions(Proc: TEnumActionProc; Info: Pointer; const FrameworkType: string); function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass; const FrameworkType: string): TBasicAction; {$ENDREGION} function GetNewActionName(const Action: TBasicAction; const FrameworkType: string): string; implementation uses System.RTLConsts, System.Math, System.TypInfo, ToolsAPI, DsnConst, DesignConst, ComponentDesigner, Winapi.Windows, Winapi.UxTheme, Vcl.GraphUtil, Vcl.Themes, Vcl.Forms, Vcl.Dialogs; var vGetIDEActions: TStringList; {$REGION 'TActionListView. This code moved from VclEditors'} { TActionListView } constructor TActionListView.Create(AOwner: TComponent); begin inherited; FFrameworkType := GetFrameworkType; FIDEActions := GetIDEActions(FFrameworkType); FImageList := TImageList.Create(nil); FNewActnPopupMenu := TPopupMenu.Create(nil); FNewStdActnPopupMenu := TPopupMenu.Create(nil); FTempStringList := TStringList.Create; BorderStyle := bsNone; Columns.Add; Height := FDefItemHeight; ReadOnly := True; RowSelect := True; ShowColumnHeaders := False; SmallImages := FImageList; ViewStyle := vsReport; Width := 200; end; destructor TActionListView.Destroy; begin FreeAndNil(FImageList); FreeAndNil(FNewActnPopupMenu); FreeAndNil(FNewStdActnPopupMenu); FreeAndNil(FTempStringList); inherited; end; procedure TActionListView.AddStdAction(const Category: string; ActionClass: TBasicActionClass; Info: Pointer); var I: integer; LCategory: string; List: TList<TBasicActionClass>; begin if Category <> '' then LCategory := Category else LCategory := SActionCategoryNone; I := FStdActionList.IndexOf(LCategory); if I = -1 then begin List := TList<TBasicActionClass>.Create; List.Add(ActionClass); FStdActionList.AddObject(LCategory, List); end else begin List := TList<TBasicActionClass>(FStdActionList.Objects[I]); List.Add(ActionClass); end; end; procedure TActionListView.AddTempString(const S: string); begin FTempStringList.Add(S); end; procedure TActionListView.Click; var P: TPoint; Item: TListItem; DefaultActionClass: TContainedActionClass; begin GetCursorPos(P); P := ScreenToClient(P); Item := GetItemAt(P.X, P.Y); if FIDEActions <> nil then DefaultActionClass := FIDEActions.DefaultActionClass else DefaultActionClass := nil; if Item <> nil then begin if Item.Index <= 1 then begin if (FMsg = '') and (Item.Index = 0) and (FNewActnPopupMenu.Items.Count = 0) then begin if Assigned(FOnNewAction) and (DefaultActionClass <> nil) then FOnNewAction(Self, '', DefaultActionClass, FActionList); end else begin if Item.Index = 0 then begin if FMsg <> '' then DoShowMsg(self) else ShowPopupMenu(Item, FNewActnPopupMenu) end else ShowPopupMenu(Item, FNewStdActnPopupMenu); end; end else if (Item.Index <> 2) and Assigned(FOnSelectAction) then begin if (Item.Data <> nil) and (not(TObject(Item.Data) is TContainedAction)) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); FOnSelectAction(Self, TContainedAction(Item.Data)); end; end else if Assigned(FOnSelectAction) then FOnSelectAction(Self, nil); end; function TActionListView.CreateMenuItem(const Caption: string; Event: TNotifyEvent; CustomData: Pointer): TMenuItem; begin Result := NewItem(Caption, 0, False, True, Event, 0, ''); Result.Tag := NativeInt(CustomData); end; procedure TActionListView.CreateWnd; begin inherited; if Designer.Root <> nil then RebuildListView; end; function TActionListView.CustomDrawItem(Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; var LRect: TRect; begin Result := True; Canvas.Brush.Style := bsClear; LRect := Item.DisplayRect(drLabel); case Stage of cdPrePaint: // Draw separator if Item.Index = 2 then begin Canvas.Pen.Color := clSilver; Canvas.MoveTo(LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); Canvas.LineTo(LRect.Right - LRect.Left, LRect.Top + (LRect.Bottom - LRect.Top) div 2); Result := False; // Prevent default drawing of highlight bar end; cdPostPaint: // Draw arrow for New Action and New Standard Action items if ((Item.Index <= 1) and (FNewStdActnPopupMenu.Items.Count > 1)) and (((Item.Index = 0) and (FNewActnPopupMenu.Items.Count > 1)) or ((Item.Index = 1) and (FNewStdActnPopupMenu.Items.Count > 1))) then begin LRect.Left := LRect.Right - 20; if ThemeServices.ThemesEnabled and (Win32MajorVersion >= 6) then DrawThemeBackground(ThemeServices.Theme[teMenu], Canvas.Handle, MENU_POPUPSUBMENU, MSM_NORMAL, LRect, nil) else DrawArrow(Canvas, sdRight, Point(LRect.Right - 15, LRect.Top + ((LRect.Bottom - LRect.Top - 8) div 2)), 4); end; end; end; procedure TActionListView.DoNewActionClick(Sender: TObject); var DefaultActionClass: TContainedActionClass; begin if Assigned(FOnNewAction) and (Sender is TMenuItem) and (FIDEActions <> nil) then begin DefaultActionClass := FIDEActions.DefaultActionClass; if DefaultActionClass <> nil then FOnNewAction(Self, '', DefaultActionClass, TContainedActionList(TMenuItem(Sender).Tag)); end; end; procedure TActionListView.DoShowMsg(Sender: TObject); var Form: TForm; begin if (FMsg <> '') then begin Form := CreateMessageDialog(FMsg, mtInformation, [mbOK]); try Form.Caption := SNoSetProp; Form.ShowModal; finally Form.Free; end; end; end; procedure TActionListView.DoNewStdActionClick(Sender: TObject); begin if Assigned(FOnNewAction) and (Sender is TMenuItem) then FOnNewAction(Self, '', TContainedActionClass(TMenuItem(Sender).Tag), TContainedActionList(TMenuItem(Sender).Parent.Tag)); end; function TActionListView.IsCustomDrawn(Target: TCustomDrawTarget; Stage: TCustomDrawStage): Boolean; begin Result := (Stage = cdPrePaint) or (Stage = cdPostPaint); end; procedure TActionListView.KeyDown(var Key: Word; Shift: TShiftState); var DefaultActionClass: TContainedActionClass; begin case Key of VK_RETURN: if Assigned(FOnSelectAction) and (Selected <> nil) then begin if FIDEActions <> nil then DefaultActionClass := FIDEActions.DefaultActionClass else DefaultActionClass := nil; if (DefaultActionClass <> nil) and (Selected.Index = 0) and (FActionList <> nil) and Assigned(FOnNewAction) then FOnNewAction(Self, '', DefaultActionClass, FActionList) else if Selected.Index = 0 then ShowPopupMenu(Selected, FNewActnPopupMenu) else if Selected.Index = 1 then ShowPopupMenu(Selected, FNewStdActnPopupMenu) else if Selected.Index <> 2 then begin if (Selected.Data <> nil) and (not(TObject(Selected.Data) is TContainedAction)) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); FOnSelectAction(Self, TContainedAction(Selected.Data)); end; end; VK_RIGHT: if Selected <> nil then begin if Selected.Index = 0 then ShowPopupMenu(Selected, FNewActnPopupMenu) else ShowPopupMenu(Selected, FNewStdActnPopupMenu); end; else inherited; end; end; procedure TActionListView.RebuildListView; var LRect: TRect; LImages: TCustomImageList; LLastActionList: TContainedActionList; ListItem: TListItem; LComp: TComponent; LAction: TContainedAction; I, LWidth, MinWidth: integer; BaseActionClass: TContainedActionClass; procedure AddActionIcon(ListItem: TListItem; Action: TContainedAction); var LIcon: TIcon; begin if (FIDEActions <> nil) and (Action <> nil) and (Action.ActionList <> nil) then begin if Action.ActionList <> LLastActionList then begin FreeAndNil(LImages); LLastActionList := Action.ActionList; if LLastActionList <> nil then LImages := FIDEActions.CreateImageList(LLastActionList); end; if LImages <> nil then begin LIcon := TIcon.Create; try LImages.GetIcon(Action.ImageIndex, LIcon); ListItem.ImageIndex := FImageList.AddIcon(LIcon); finally LIcon.Free; end; end; end; end; begin // Add actions to listview if FNewStdActnPopupMenu.Items.Count > 0 then begin if FIDEActions <> nil then BaseActionClass := FIDEActions.BaseActionClass else BaseActionClass := nil; Items.BeginUpdate; try Items.Clear; FImageList.Clear; if FMsg = '' then begin // Set initial max width MinWidth := Max(Width, Canvas.TextWidth(SNoSetProp) + 25); // Find all actions FTempStringList.Clear; if (BaseActionClass <> nil) then begin LImages := nil; LLastActionList := nil; try Designer.GetComponentNames(GetTypeData(TypeInfo(TContainedAction)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin LComp := Designer.GetComponent(FTempStringList[I]); if (not(LComp is TContainedAction)) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); LAction := TContainedAction(LComp); if LAction is BaseActionClass then begin ListItem := Items.Add; ListItem.Caption := FTempStringList[I]; ListItem.Data := LAction; ListItem.ImageIndex := -1; LWidth := Canvas.TextWidth(ListItem.Caption); if (LWidth + 40) > MinWidth then MinWidth := LWidth + 40; AddActionIcon(ListItem, LAction); end; end; finally FreeAndNil(LImages); end; end; // Sort list items before adding "special" items CustomSort(nil, 0); // Add "New Action" item ListItem := Items.Insert(0); ListItem.Caption := SCreateNewAction; ListItem.ImageIndex := -1; // Add "New Standard Action" item ListItem := Items.Insert(1); ListItem.Caption := SCreateNewStdAction; ListItem.ImageIndex := -1; // Add dummy item for divider line if Items.Count > 2 then begin ListItem := Items.Insert(2); ListItem.ImageIndex := -1; end; end else begin MinWidth := Max(Width, Canvas.TextWidth(SNoSetProp) + 25); ListItem := Items.Insert(0); ListItem.Caption := ' ' + SNoSetProp; ListItem.ImageIndex := -1; end; finally Items.EndUpdate; end; // Set Height to fit 14 items LWidth := 0; if Items.Count > 14 then begin I := 14; LWidth := GetSystemMetrics(SM_CXVSCROLL); end else I := Items.Count; LRect := Items[0].DisplayRect(drBounds); Height := LRect.Bottom * I; // Set width to widest + space for icon and gutters (20 pixels each side) Width := MinWidth + LWidth + FImageList.Width; Columns[0].Width := Width - LWidth; end else Height := FDefItemHeight; end; procedure TActionListView.RebuildPopupMenus; var LName: string; J, I, K: integer; LComp: TComponent; MenuItem, SubItem: TMenuItem; LActionList: TContainedActionList; LActionLists: TList<TContainedActionList>; ActionClassList: TList<TBasicActionClass>; LImages: TCustomImageList; BaseActionListClass: TContainedActionListClass; begin SmallImages := nil; MenuItem := nil; if FIDEActions <> nil then BaseActionListClass := FIDEActions.BaseActionListClass else BaseActionListClass := nil; // Build popup menus FMsg := ''; FNewActnPopupMenu.Items.Clear; FNewStdActnPopupMenu.Items.Clear; FStdActionList := TStringList.Create; try // Gather list of registered action classes if Assigned(EnumRegisteredActionsProc) then System.Actions.EnumRegisteredActions(AddStdAction, nil, FFrameworkType); LActionLists := TList<TContainedActionList>.Create; try // Build list of ActionLists FTempStringList.Clear; if BaseActionListClass = nil then begin FActionList := nil; if FIDEActions = nil then FMsg := Format(SNoActionsImpl, [FFrameworkType]) else FMsg := SNoDefineBase; end else begin Designer.GetComponentNames(GetTypeData(TypeInfo(TContainedActionList)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin LComp := Designer.GetComponent(FTempStringList[I]); if (not(LComp is TContainedActionList)) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); if LComp is BaseActionListClass then LActionLists.Add(TContainedActionList(LComp)); end; if LActionLists.Count = 0 then FMsg := Format(SNoActionLists, [BaseActionListClass.ClassName]); // If there's just one, save it in FActionList if LActionLists.Count = 1 then FActionList := LActionLists[0] else FActionList := nil; end; if FMsg <> '' then begin MenuItem := CreateMenuItem(SNoSetProp, DoShowMsg, nil); FNewStdActnPopupMenu.Items.Add(MenuItem); end else // Build popupmenus for actionlists and standard actions for LActionList in LActionLists do begin // Build a popup menu for each ActionList if (FIDEActions <> nil) and (SmallImages = nil) then begin LImages := FIDEActions.CreateImageList(LActionList); try if LImages <> nil then SmallImages := FImageList; finally FreeAndNil(LImages); end; end; // If more than 1 actionlist, add a popupmenu to select // where the create the action if LActionLists.Count > 1 then begin if LActionList.Owner = Designer.Root then LName := LActionList.Name else LName := LActionList.Owner.Name + DotSep + LActionList.Name; MenuItem := CreateMenuItem(LName, DoNewActionClick, LActionList); FNewActnPopupMenu.Items.Add(MenuItem); MenuItem := CreateMenuItem(LName, nil, nil); FNewStdActnPopupMenu.Items.Add(MenuItem); end; // For standard actions popup, add each standard action category for J := 0 to FStdActionList.Count - 1 do begin SubItem := CreateMenuItem(FStdActionList[J], nil, LActionList); if LActionLists.Count > 1 then MenuItem.Add(SubItem) else FNewStdActnPopupMenu.Items.Add(SubItem); // For each category, add each registered action class ActionClassList := TList<TBasicActionClass>(FStdActionList.Objects[J]); for K := 0 to ActionClassList.Count - 1 do SubItem.Add(CreateMenuItem(ActionClassList[K].ClassName, DoNewStdActionClick, ActionClassList[K])); end; end; finally LActionLists.Free; end; // Free lists of registered action classes for I := 0 to FStdActionList.Count - 1 do FStdActionList.Objects[I].Free; finally FreeAndNil(FStdActionList); end; end; procedure TActionListView.SetDesigner(const Value: IDesigner); var N, I: integer; LComp: TComponent; BaseActionClass: TContainedActionClass; begin FMsg := ''; if Value <> FDesigner then begin FDesigner := Value; if FIDEActions <> nil then BaseActionClass := FIDEActions.BaseActionClass else BaseActionClass := nil; // Set initial height based on default item height FTempStringList.Clear; N := 0; if BaseActionClass <> nil then begin Designer.GetComponentNames(GetTypeData(TypeInfo(TContainedAction)), AddTempString); for I := 0 to FTempStringList.Count - 1 do begin LComp := Designer.GetComponent(FTempStringList[I]); if (not(LComp is TContainedAction)) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); if LComp is BaseActionClass then inc(N); end; end; if N > 0 then Height := (Min(N, 11) + 3) * FDefItemHeight else Height := FDefItemHeight; // Rebuild popup menus and listview RebuildPopupMenus; if HandleAllocated then RebuildListView; end; end; procedure TActionListView.ShowPopupMenu(Item: TListItem; PopupMenu: TPopupMenu); var P: TPoint; LRect: TRect; begin LRect := Item.DisplayRect(drBounds); P := Item.Owner.Owner.ClientToScreen(Point(LRect.Right, LRect.Top)); PopupMenu.Tag := NativeInt(Item.Data); PopupMenu.Popup(P.X, P.Y); end; {$ENDREGION} {$REGION 'TActionProperty. This code moved from VclEditors'} { TActionProperty } procedure TActionProperty.AddAction(const Category: string; ActionClass: TBasicActionClass; Info: Pointer); var R: TRegisteredAction; begin if not Category.IsEmpty then begin R.Category := Category; R.ActionClass := ActionClass; if FRegisteredActionList = nil then FRegisteredActionList := TList<TRegisteredAction>.Create; FRegisteredActionList.Add(R); end; end; procedure TActionProperty.CreateNewAction(Sender: TObject; const Category: string; ActionClass: TContainedActionClass; ActionList: TContainedActionList); var LRoot: IRoot; LCategory, LFramework, LName: string; NewAction: TContainedAction; LIDEActions: TIDEActionsClass; I: Integer; begin LCategory := Category; if AnsiCompareText(LCategory, SActionCategoryNone) = 0 then LCategory := ''; // Create new action LFramework := GetFrameworkType; LIDEActions := GetIDEActions(LFramework); NewAction := CreateAction(ActionList.Owner, ActionClass, LFramework) as TContainedAction; try LName := GetNewActionName(NewAction, LFramework); if ActionList.Owner = Designer.Root then NewAction.Name := Designer.UniqueName(LName) else begin LRoot := ActiveDesigner.FindRoot(ActionList.Owner); if LRoot <> nil then NewAction.Name := LRoot.GetDesigner.UniqueName(LName) else raise Exception.CreateResFmt(@SUnableToFindComponent, [ActionList.Owner.Name]); end; if Category.IsEmpty then begin if (NewAction.Category.IsEmpty) and Assigned(EnumRegisteredActionsProc) then begin if FRegisteredActionList = nil then System.Actions.EnumRegisteredActions(AddAction, nil, LFramework); if FRegisteredActionList <> nil then for I := 0 to FRegisteredActionList.Count - 1 do if FRegisteredActionList[I].ActionClass = NewAction.ClassType then begin NewAction.Category := FRegisteredActionList[I].Category; Break; end; end; end else NewAction.Category := LCategory; NewAction.ActionList := ActionList; if (LIDEActions <> nil) then LIDEActions.CopyImageIfAvailable(NewAction, ActionList); // Update property SelectAction(Sender, NewAction); except NewAction.Free; raise; end; end; destructor TActionProperty.Destroy; begin FActionListView.Free; FRegisteredActionList.Free; inherited; end; procedure TActionProperty.Edit(const Host: IPropertyHost; DblClick: Boolean); var LHost20: IPropertyHost20; begin FHost := Host; if FActionListView <> nil then FActionListView.Free; FActionListView := TActionListView.Create(nil); if Supports(FHost, IPropertyHost20, LHost20) then FActionListView.Width := LHost20.GetDropDownWidth; FActionListView.OnNewAction := CreateNewAction; FActionListView.OnSelectAction := SelectAction; FActionListView.Designer := Designer; FActionListView.Visible := True; FHost.DropDownControl(FActionListView); end; function TActionProperty.GetAttributes: TPropertyAttributes; begin Result := inherited + [paCustomDropDown, paVolatileSubProperties] - [paValueList, paSortList]; end; procedure TActionProperty.SelectAction(Sender: TObject; Action: TContainedAction); begin FHost.CloseDropDown; if Action <> nil then SetValue(Action.Owner.Name + DotSep + Action.Name) else SetValue(''); end; {$ENDREGION} {$REGION 'The interaction of action with an IDE. This new code'} function GetFrameworkType: string; var Proj: IOTAProject; function GetCurrentProject: IOTAProject; var Services: IOTAModuleServices; Module: IOTAModule; Project: IOTAProject; ProjectGroup: IOTAProjectGroup; MultipleProjects: boolean; I: integer; begin Result := nil; MultipleProjects := False; Services := BorlandIDEServices as IOTAModuleServices; Module := Services.CurrentModule; if (Module = nil) or (Module.OwnerModuleCount <> 1) then begin for I := 0 to Services.ModuleCount - 1 do begin Module := Services.Modules[I]; if Module.QueryInterface(IOTAProjectGroup, ProjectGroup) = S_OK then begin Result := ProjectGroup.ActiveProject; Exit; end else if Module.QueryInterface(IOTAProject, Project) = S_OK then begin if Result = nil then Result := Project else MultipleProjects := True; end; end; if MultipleProjects then Result := nil; end else Result := Module.Owners[0]; end; begin Result := ''; Proj := GetCurrentProject; //GetActiveProject; if Proj <> nil then Result := Proj.FrameworkType; end; procedure RegisterActionsInFramework(const FrameworkType: string; const AIDEActions: TIDEActionsClass); var S: string; I: integer; begin S := AnsiUppercase(Trim(FrameworkType)); if S = '' then raise EActionError.Create(SInvalidString); if AIDEActions = nil then raise EActionError.CreateFmt(SParamIsNil, ['AIDEActions']); if vGetIDEActions = nil then begin vGetIDEActions := TStringList.Create; vGetIDEActions.Sorted := True; vGetIDEActions.Duplicates := dupError; end; if (vGetIDEActions.Find(S, I)) then begin if (TObject(AIDEActions) <> vGetIDEActions.Objects[I]) then raise EActionError.CreateFmt(StrEFalreadyReg, [S]) end else vGetIDEActions.AddObject(S, TObject(AIDEActions)); end; procedure UnregisterActionsInFramework(const FrameworkType: string); var S: string; I: integer; begin if (vGetIDEActions <> nil) then begin if (vGetIDEActions.Count > 0) then begin S := AnsiUppercase(Trim(FrameworkType)); if S <> '' then begin I := vGetIDEActions.IndexOf(S); if I >= 0 then vGetIDEActions.Delete(I); end; end; if vGetIDEActions.Count = 0 then FreeAndNil(vGetIDEActions); end; end; function GetIDEActions(const FrameworkType: string): TIDEActionsClass; var S: string; I: integer; begin Result := vOldIDEActions; if (vGetIDEActions <> nil) then begin S := AnsiUppercase(Trim(FrameworkType)); if S <> '' then begin I := vGetIDEActions.IndexOf(S); if I >= 0 then Result := TIDEActionsClass(vGetIDEActions.Objects[I]) else Result := nil; end; end; end; function GetIDEActions(const ActionList: TContainedActionList; var FrameworkType: string): TIDEActionsClass; overload; var I: Integer; IDEActions: TIDEActionsClass; ActionListClass: TContainedActionListClass; begin if (ActionList = nil) or (vGetIDEActions = nil) then begin FrameworkType := GetFrameworkType; Result := GetIDEActions(FrameworkType); end else begin FrameworkType := ''; Result := nil; for I := 0 to vGetIDEActions.Count - 1 do begin IDEActions := TIDEActionsClass(vGetIDEActions.Objects[I]); if (IDEActions <> nil) then begin ActionListClass := IDEActions.BaseActionListClass; if (ActionListClass <> nil) and (ActionList.InheritsFrom(ActionListClass)) then begin FrameworkType := vGetIDEActions[I]; Result := IDEActions; end; end; end; end; end; function GetIDEActionsList(List: TStringList): integer; var I: integer; begin Result := 0; if List <> nil then begin List.Clear; if vGetIDEActions <> nil then for I := 0 to vGetIDEActions.Count - 1 do begin List.AddObject(vGetIDEActions[I], vGetIDEActions.Objects[I]); inc(Result); end; end else raise EActionError.CreateFMT(SParamIsNil, ['List']); end; { TIDEActions } class function TIDEActions.CreateImageLink(const OnChanged: TNotifyEvent): TObject; begin Result := nil; end; class function TIDEActions.CreateImageList(ActionList: TContainedActionList): TCustomImageList; begin Result := nil; end; class procedure TIDEActions.AssignAction(Source, Destination: TBasicAction); begin if (Source is TContainedAction) and (Destination is TContainedAction) then TContainedAction(Destination).Category := TContainedAction(Source).Category; end; class function TIDEActions.BaseActionClass: TContainedActionClass; begin Result := nil; end; class function TIDEActions.BaseActionListClass: TContainedActionListClass; begin Result := nil; end; class function TIDEActions.DefaultActionClass: TContainedActionClass; begin Result := nil; end; class procedure TIDEActions.CopyImageIfAvailable(const NewAction: TContainedAction; const ActionList: TContainedActionList); begin end; class procedure TIDEActions.RegisterImageLink(const ActionList: TContainedActionList; const ImageLink: TObject); begin end; class procedure TIDEActions.UnregisterImageLink(const ActionList: TContainedActionList; const ImageLink: TObject); begin end; {$ENDREGION} {$REGION 'Registry Information. This code moved from VclEditors'} type TBasicActionRecord = record ActionClass: TBasicActionClass; GroupId: integer; Resource: TComponentClass; end; TActionClassArray = array of TBasicActionRecord; TActionClassesEntry = record Category: string; Actions: TActionClassArray; end; TActionClassesArray = array of TActionClassesEntry; TActionResourceCache = class type TResourceCache = TDictionary<TComponentClass, TComponent>; private FCache: TResourceCache; function GetCache: TResourceCache; public destructor Destroy; override; procedure Add(ComponentClass: TComponentClass; Instance: TComponent); procedure Clear; function GetInstance(ComponentClass: TComponentClass): TComponent; procedure Remove(ComponentClass: TComponentClass); property Cache: TResourceCache read GetCache; end; var DesignersList: TList = nil; ActionClasses: TActionClassesArray = nil; vActionResourceCache: TActionResourceCache = nil; { TActionResourceCache } function ActionResourceCache: TActionResourceCache; begin if vActionResourceCache = nil then vActionResourceCache := TActionResourceCache.Create; Result := vActionResourceCache; end; destructor TActionResourceCache.Destroy; begin Clear; // Free stored items FreeAndNil(FCache); end; procedure TActionResourceCache.Add(ComponentClass: TComponentClass; Instance: TComponent); begin Cache.Add(ComponentClass, Instance); end; procedure TActionResourceCache.Clear; var P: TPair<TComponentClass, TComponent>; begin if FCache <> nil then begin for P in FCache do if P.Value <> nil then P.Value.Free; FCache.Clear; end; end; function TActionResourceCache.GetCache: TResourceCache; begin if FCache = nil then FCache := TResourceCache.Create; Result := FCache; end; function TActionResourceCache.GetInstance(ComponentClass: TComponentClass): TComponent; begin if (FCache <> nil) and (FCache.ContainsKey(ComponentClass)) then Result := FCache.Items[ComponentClass] else Result := nil; end; procedure TActionResourceCache.Remove(ComponentClass: TComponentClass); begin if (FCache <> nil) and (FCache.ContainsKey(ComponentClass)) then begin if FCache.Items[ComponentClass] <> nil then FCache.Items[ComponentClass].Free; FCache.Remove(ComponentClass); end; end; {$ENDREGION} {$REGION 'Action Registration. This code moved from VclEditors'} procedure RegActions(const ACategory: string; const AClasses: array of TBasicActionClass; AResource: TComponentClass); var CategoryIndex, Len, I, J, NewClassCount: integer; NewClasses: array of TBasicActionClass; Skip: Boolean; S: string; lClasses: array of TContainedActionClass; begin for I := Low(AClasses) to High(AClasses) do if (AClasses[I] <> nil) and (AClasses[I].InheritsFrom(TContainedAction)) then begin SetLength(lClasses, Length(lClasses) + 1); lClasses[Length(lClasses) - 1] := TContainedActionClass(AClasses[I]); end; // Remove resource from cache if it's there if ActionResourceCache.GetInstance(AResource) <> nil then ActionResourceCache.Remove(AResource); { Determine whether we're adding a new category, or adding to an existing one } CategoryIndex := -1; for I := Low(ActionClasses) to High(ActionClasses) do if CompareText(ActionClasses[I].Category, ACategory) = 0 then begin CategoryIndex := I; Break; end; { Adding a new category } if CategoryIndex = -1 then begin CategoryIndex := Length(ActionClasses); SetLength(ActionClasses, CategoryIndex + 1); end; with ActionClasses[CategoryIndex] do begin SetLength(NewClasses, Length(AClasses)); { Remove duplicate classes } NewClassCount := 0; for I := Low(AClasses) to High(AClasses) do begin Skip := False; for J := Low(Actions) to High(Actions) do if AClasses[I] = Actions[J].ActionClass then begin Skip := True; Break; end; if not Skip then begin NewClasses[Low(NewClasses) + NewClassCount] := AClasses[I]; inc(NewClassCount); end; end; { Pack NewClasses } SetLength(NewClasses, NewClassCount); SetString(S, PChar(ACategory), Length(ACategory)); Category := S; Len := Length(Actions); SetLength(Actions, Len + Length(NewClasses)); for I := Low(NewClasses) to High(NewClasses) do begin RegisterNoIcon([NewClasses[I]]); System.Classes.RegisterClass(NewClasses[I]); with Actions[Len + I] do begin ActionClass := NewClasses[I]; GroupId := CurrentGroup; Resource := AResource; end; end; end; { Notify all available designers of new TAction class } if (DesignersList <> nil) and Assigned(NotifyActionListChange) then NotifyActionListChange; end; procedure UnRegActions(const Classes: array of TBasicActionClass); var I, J, K: integer; LActionClass: TBasicActionClass; lClasses: array of TContainedActionClass; begin for I := Low(Classes) to High(Classes) do if (Classes[I] <> nil) and (Classes[I].InheritsFrom(TContainedAction)) then begin SetLength(lClasses, Length(lClasses) + 1); lClasses[Length(lClasses) - 1] := TContainedActionClass(Classes[I]); end; // Clear the resource cache ActionResourceCache.Clear; for I := Low(Classes) to High(Classes) do begin LActionClass := Classes[I]; for J := Low(ActionClasses) to High(ActionClasses) do for K := Low(ActionClasses[J].Actions) to High(ActionClasses[J].Actions) do with ActionClasses[J].Actions[K] do if LActionClass = ActionClass then begin ActionClass := nil; GroupId := -1; end; end; if Assigned(NotifyActionListChange) then NotifyActionListChange; end; procedure UnregisterActionGroup(AGroupId: integer); var I, J: integer; begin for I := Low(ActionClasses) to High(ActionClasses) do for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do with ActionClasses[I].Actions[J] do if GroupId = AGroupId then begin ActionClass := nil; GroupId := -1; end; if Assigned(NotifyActionListChange) then NotifyActionListChange; end; procedure EnumActions(Proc: TEnumActionProc; Info: Pointer; const FrameworkType: string); var I, J, Count: integer; ActionClass: TBasicActionClass; BaseActionClass: TContainedActionClass; CurrClass: TClass; IDEActions: TIDEActionsClass; begin IDEActions := GetIDEActions(FrameworkType); if (ActionClasses <> nil) and (IDEActions <> nil) and (IDEActions.BaseActionClass <> nil) then begin BaseActionClass := IDEActions.BaseActionClass; for I := Low(ActionClasses) to High(ActionClasses) do begin Count := 0; for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do begin ActionClass := ActionClasses[I].Actions[J].ActionClass; if ActionClass <> nil then begin CurrClass := ActionClass; while (CurrClass <> nil) and (CurrClass <> BaseActionClass) do CurrClass := CurrClass.ClassParent; if CurrClass <> nil then Proc(ActionClasses[I].Category, ActionClass, Info); inc(Count); end; end; if Count = 0 then SetLength(ActionClasses[I].Actions, 0); end; end; end; function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass; const FrameworkType: string): TBasicAction; var I, J: integer; Res: TComponentClass; Instance: TComponent; Action: TBasicAction; IDEActions: TIDEActionsClass; function FindComponentByClass(AOwner: TComponent; const AClassName: string): TComponent; var I: integer; begin if (AClassName <> '') and (AOwner.ComponentCount > 0) then for I := 0 to AOwner.ComponentCount - 1 do begin Result := AOwner.Components[I]; if CompareText(Result.ClassName, AClassName) = 0 then Exit; end; Result := nil; end; begin if not ActionClass.InheritsFrom(TContainedAction) then raise EActionError.CreateFMT(StrEClassAction, [TContainedAction.ClassName]); Result := ActionClass.Create(AOwner); { Attempt to find the first action with the same class Type as ActionClass in the Resource component's resource stream, and use its property values as our defaults. } Res := nil; for I := Low(ActionClasses) to High(ActionClasses) do begin for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do begin if ActionClasses[I].Actions[J].ActionClass = ActionClass then begin Res := ActionClasses[I].Actions[J].Resource; Break; end; end; if Res <> nil then Break; end; if Res <> nil then begin // Look for this resource in the cache Instance := ActionResourceCache.GetInstance(Res); if Instance = nil then begin // Not found, create it and add it Instance := Res.Create(nil); ActionResourceCache.Add(Res, Instance); end; Action := FindComponentByClass(Instance, ActionClass.ClassName) as TBasicAction; if Action <> nil then begin IDEActions := GetIDEActions(FrameworkType); if (IDEActions <> nil) then IDEActions.AssignAction(Action, Result) else with Action as TContainedAction do begin // Old code TContainedAction(Result).Caption := Caption; TContainedAction(Result).Checked := Checked; TContainedAction(Result).Enabled := Enabled; TContainedAction(Result).HelpContext := HelpContext; TContainedAction(Result).Hint := Hint; TContainedAction(Result).ImageIndex := ImageIndex; TContainedAction(Result).ShortCut := ShortCut; TContainedAction(Result).Visible := Visible; end; end; end; end; {$ENDREGION} function GetNewActionName(const Action: TBasicAction; const FrameworkType: string): string; var Cat: string; procedure DropPart(var S: string; Part: string); begin Part := StringReplace(Part, ' ', '', [rfReplaceAll]); if (Length(S) > (Length(Part) + 2)) and (WideSameText(System.Copy(S, 1, Length(Part)), Part)) then Delete(S, 1, Length(Part)); end; begin Result := Action.ClassName; if Action is TContainedAction then begin DropPart(Result, 't'); DropPart(Result, FrameworkType); Cat := StringReplace(TContainedAction(Action).Category, ' ', '', [rfReplaceAll]); DropPart(Result, Cat); Result := 'T' + Cat + Result; end; end; initialization vGetIDEActions := nil; vOldIDEActions := nil; RegisterActionsProc := nil; //RegActions; UnRegisterActionsProc := nil; //UnRegActions; EnumRegisteredActionsProc := nil; //EnumActions; CreateActionProc := nil; //CreateAction; NotifyGroupChange(UnregisterActionGroup); finalization UnNotifyGroupChange(UnregisterActionGroup); FreeAndNil(vActionResourceCache); FreeAndNil(vGetIDEActions); end.
unit TestDelphiNetOperatorOverload; { This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility test operator overloads in Delphi.NET } interface type TMyClass = class private FData: Integer; public class operator Add(A,B: TMyClass): TMyClass; class operator Implicit(A: Integer): TMyClass; class operator Implicit(A: TMyClass): Integer; property Data: Integer read FData write FData; end; implementation { TMyClass } class operator TMyClass.Add(A, B: TMyClass): TMyClass; begin Result := TMyClass.Create; Result.Data := A.Data + B.Data; end; class operator TMyClass.Implicit(A: TMyClass): Integer; begin Result := A.Data; end; class operator TMyClass.Implicit(A: Integer): TMyClass; begin Result := TMyClass.Create; Result.Data := A; end; end.
unit ncaFrmPeriodo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel; type TFrmPeriodo = class(TForm) lbInicio: TcxLabel; lbFinal: TcxLabel; edInicio: TcxDateEdit; edFim: TcxDateEdit; btnOk: TcxButton; btnCancelar: TcxButton; procedure btnOkClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } function ObtemPeriodo(var I, F: TDateTime): Boolean; end; var FrmPeriodo: TFrmPeriodo; implementation resourcestring rsInformarInicio = 'É necessário informar uma data inicial'; rsInformarFinal = 'É necessário informar a data final'; rsFinalMenorInicio = 'A data final deve ser maior ou igual a data inicial'; {$R *.dfm} procedure TFrmPeriodo.btnOkClick(Sender: TObject); begin if edInicio.Date < EncodeDate(1980, 1, 1) then begin edInicio.SetFocus; raise Exception.Create(rsInformarInicio); end; if edFim.Date < EncodeDate(1980, 1, 1) then begin edFim.SetFocus; raise Exception.Create(rsInformarFinal); end; if edFim.Date < edInicio.Date then begin edInicio.SetFocus; raise Exception.Create(rsFinalMenorInicio); end; ModalResult := mrOk; end; procedure TFrmPeriodo.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; function TFrmPeriodo.ObtemPeriodo(var I, F: TDateTime): Boolean; begin ShowModal; if ModalResult=mrOk then begin Result := True; I := edInicio.Date; F := edFim.Date; end else Result := False; end; end.
{ DStun Description: A delphi librry for stun(rfc3489). License: 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/ Contact Details: EMail: heroyin@gmail.com unit: stun message Change log: (2007-6-11): - First version by heroyin@gmail.com. } unit DSMessage; interface uses Windows, SysUtils, Classes; const ///********** STUN message type **********/// /// STUN message is binding request. DSMT_BindingRequest = $0001; /// STUN message is binding request response. DSMT_BindingResponse = $0101; /// STUN message is binding requesr error response. DSMT_BindingErrorResponse = $0111; /// STUN message is "shared secret" request. DSMT_SharedSecretRequest = $0002; /// STUN message is "shared secret" request response. DSMT_SharedSecretResponse = $0102; /// STUN message is "shared secret" request error response. DSMT_SharedSecretErrorResponse = $0112; ///********** STUN attribute type **********/// DSAT_MappedAddress = $0001; DSAT_ResponseAddress = $0002; DSAT_ChangeRequest = $0003; DSAT_SourceAddress = $0004; DSAT_ChangedAddress = $0005; DSAT_Username = $0006; DSAT_Password = $0007; DSAT_MessageIntegrity = $0008; DSAT_ErrorCode = $0009; DSAT_UnknownAttribute = $000A; DSAT_ReflectedFrom = $000B; DSAT_XorMappedAddress = $8020; DSAT_XorOnly = $0021; DSAT_ServerName = $8022; ///********** STUN IPFamily **********/// DSIF_IPV4 = $01; DSIF_IPV6 = $02; type { dsntOpenInternet dsntSymmetricUdpFirewall dsntFullCone dsntRestrictedCone dsntPortRestrictedCone dsntSymmetric dsntOpenInternet ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì dsntSymmetricUdpFirewall ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì dsntFullCone ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì ¡Ì dsntRestrictedCone ¡Ì ¡Ì ¡Ì dsntPortRestrictedCone dsntSymmetric } TDSNetType = ( /// UDP is always blocked. dsntUdpBlocked, /// No NAT, public IP, no firewall. dsntOpenInternet, /// No NAT, public IP, but symmetric UDP firewall. dsntSymmetricUdpFirewall, /// A full cone NAT is one where all requests from the same internal IP address and port are /// mapped to the same external IP address and port. Furthermore, any external host can send /// a packet to the internal host, by sending a packet to the mapped external address. dsntFullCone, /// A restricted cone NAT is one where all requests from the same internal IP address and /// port are mapped to the same external IP address and port. Unlike a full cone NAT, an external /// host (with IP address X) can send a packet to the internal host only if the internal host /// had previously sent a packet to IP address X. dsntRestrictedCone, /// A port restricted cone NAT is like a restricted cone NAT, but the restriction /// includes port numbers. Specifically, an external host can send a packet, with source IP /// address X and source port P, to the internal host only if the internal host had previously /// sent a packet to IP address X and port P. dsntPortRestrictedCone, /// A symmetric NAT is one where all requests from the same internal IP address and port, /// to a specific destination IP address and port, are mapped to the same external IP address and /// port. If the same host sends a packet with the same source address and port, but to /// a different destination, a different mapping is used. Furthermore, only the external host that /// receives a packet can send a UDP packet back to the internal host. dsntSymmetric ); TDSIPAddress = packed record UnUsed: Byte; Family: Byte; Port_hi: Byte; Port_lo: Byte; IP: array [0..3] of byte; end; TDSErrorCode = record Code: integer; Reason: AnsiString; end; TDSResult = record NetType: TDSNetType; PublicIP: TDSIPAddress; end; type IDSAttribute = interface ['{D30F83F3-90CC-49D9-9BAF-80667D22E56A}'] procedure Build(AStream: TStream); stdcall; procedure Parser(AStream: TStream); stdcall; function GetAttributeLength: Word; stdcall; function GetAttributeType: Word; stdcall; function GetHeadLength: Integer; stdcall; procedure SetAttributeType(const Value: Word); stdcall; property AttributeLength: Word read GetAttributeLength; property AttributeType: Word read GetAttributeType write SetAttributeType; property HeadLength: Integer read GetHeadLength; end; IDSAddressAttribute = interface ['{720336AC-9AFB-47DE-9248-5C38F35E2259}'] function GetIPAddress: TDSIPAddress; stdcall; procedure SetIPAddress(const Value: TDSIPAddress); stdcall; property IPAddress: TDSIPAddress read GetIPAddress write SetIPAddress; end; IDSChangeRequestAttribute = interface ['{4292B9AB-591E-4D9F-BD1E-F855D230B475}'] function GetChangeIP: Boolean; stdcall; function GetChangePort: Boolean; stdcall; procedure SetChangeIP(const Value: Boolean); stdcall; procedure SetChangePort(const Value: Boolean); stdcall; property ChangeIP: Boolean read GetChangeIP write SetChangeIP; property ChangePort: Boolean read GetChangePort write SetChangePort; end; IDSStringAttribute = interface ['{79DD3703-3879-49C5-B252-07F1BDCD30D5}'] function GetStringValue: AnsiString; stdcall; procedure SetStringValue(const Value: AnsiString); stdcall; property StringValue: AnsiString read GetStringValue write SetStringValue; end; IDSErrorAttribute = interface ['{E74044FA-35F6-4230-BBF0-948091289FB5}'] function GetClasses: Byte; stdcall; function GetNumber: Word; stdcall; function GetReason: AnsiString; stdcall; procedure SetClasses(const Value: Byte); stdcall; procedure SetNumber(const Value: Word); stdcall; procedure SetReason(const Value: AnsiString); stdcall; property Classes: Byte read GetClasses write SetClasses; property Number: Word read GetNumber write SetNumber; property Reason: AnsiString read GetReason write SetReason; end; IDSMessage = interface ['{2229958A-01EA-4693-BD17-806274EF370F}'] procedure Build(AStream: TStream); function GetChangedAddress: IDSAddressAttribute; stdcall; function GetChangeRequestAttribute: IDSChangeRequestAttribute; stdcall; function GetErrorAttribute: IDSErrorAttribute; stdcall; function GetHeadLength: Integer; function GetMappedAddress: IDSAddressAttribute; stdcall; function GetMessageLength: Integer; stdcall; function GetMessageType: Word; stdcall; function GetPassword: IDSStringAttribute; stdcall; function GetReflectedFrom: IDSAddressAttribute; stdcall; function GetResponseAddress: IDSAddressAttribute; stdcall; function GetServerName: IDSStringAttribute; stdcall; function GetSourceAddress: IDSAddressAttribute; stdcall; function GetTransactionID: TGUID; stdcall; function GetUserName: IDSStringAttribute; stdcall; function GetXorMappedAddress: IDSAddressAttribute; stdcall; function GetXorOnly: IDSStringAttribute; stdcall; procedure Parser(AStream: TStream); procedure SetChangedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetChangeRequestAttribute(const Value: IDSChangeRequestAttribute); stdcall; procedure SetErrorAttribute(const Value: IDSErrorAttribute); stdcall; procedure SetMappedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetMessageType(const Value: Word); stdcall; procedure SetPassword(const Value: IDSStringAttribute); stdcall; procedure SetReflectedFrom(const Value: IDSAddressAttribute); stdcall; procedure SetResponseAddress(const Value: IDSAddressAttribute); stdcall; procedure SetServerName(const Value: IDSStringAttribute); stdcall; procedure SetSourceAddress(const Value: IDSAddressAttribute); stdcall; procedure SetUserName(const Value: IDSStringAttribute); stdcall; procedure SetXorMappedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetXorOnly(const Value: IDSStringAttribute); stdcall; property ChangedAddress: IDSAddressAttribute read GetChangedAddress write SetChangedAddress; property ChangeRequestAttribute: IDSChangeRequestAttribute read GetChangeRequestAttribute write SetChangeRequestAttribute; property ErrorAttribute: IDSErrorAttribute read GetErrorAttribute write SetErrorAttribute; property HeadLength: Integer read GetHeadLength; property MappedAddress: IDSAddressAttribute read GetMappedAddress write SetMappedAddress; property MessageLength: Integer read GetMessageLength; property MessageType: Word read GetMessageType write SetMessageType; property Password: IDSStringAttribute read GetPassword write SetPassword; property ReflectedFrom: IDSAddressAttribute read GetReflectedFrom write SetReflectedFrom; property ResponseAddress: IDSAddressAttribute read GetResponseAddress write SetResponseAddress; property ServerName: IDSStringAttribute read GetServerName write SetServerName; property SourceAddress: IDSAddressAttribute read GetSourceAddress write SetSourceAddress; property TransactionID: TGUID read GetTransactionID; property UserName: IDSStringAttribute read GetUserName write SetUserName; property XorMappedAddress: IDSAddressAttribute read GetXorMappedAddress write SetXorMappedAddress; property XorOnly: IDSStringAttribute read GetXorOnly write SetXorOnly; end; ///////////////////////////////classes/////////////////////////// TDSAttribute = class(TInterfacedObject, IDSAttribute) private FAttributeLength: Word; FAttributeType: Word; protected function GetAttributeLength: Word; stdcall; function GetAttributeType: Word; stdcall; function GetHeadLength: Integer; stdcall; procedure SetAttributeType(const Value: Word); stdcall; procedure Build(AStream: TStream); virtual; stdcall; procedure Parser(AStream: TStream); virtual; stdcall; property AttributeLength: Word read GetAttributeLength; property AttributeType: Word read GetAttributeType write SetAttributeType; property HeadLength: Integer read GetHeadLength; public constructor Create; virtual; destructor Destroy; override; end; TDSAddressAttribute = class(TDSAttribute, IDSAddressAttribute) private FIPAddress: TDSIPAddress; protected function GetIPAddress: TDSIPAddress; stdcall; procedure SetIPAddress(const Value: TDSIPAddress); stdcall; procedure Build(AStream: TStream); override; procedure Parser(AStream: TStream); override; property IPAddress: TDSIPAddress read GetIPAddress write SetIPAddress; public constructor Create; override; end; TDSChangeRequestAttribute = class(TDSAttribute, IDSChangeRequestAttribute) private FChangeIP: Boolean; FChangePort: Boolean; protected function GetChangeIP: Boolean; stdcall; function GetChangePort: Boolean; stdcall; procedure SetChangeIP(const Value: Boolean); stdcall; procedure SetChangePort(const Value: Boolean); stdcall; procedure Build(AStream: TStream); override; procedure Parser(AStream: TStream); override; property ChangeIP: Boolean read GetChangeIP write SetChangeIP; property ChangePort: Boolean read GetChangePort write SetChangePort; public constructor Create; override; end; TDSStringAttribute = class(TDSAttribute, IDSStringAttribute) private FStringValue: AnsiString; protected function GetStringValue: AnsiString; stdcall; procedure SetStringValue(const Value: AnsiString); stdcall; procedure Build(AStream: TStream); override; procedure Parser(AStream: TStream); override; property StringValue: AnsiString read GetStringValue write SetStringValue; public constructor Create; override; end; TDSErrorAttribute = class(TDSAttribute, IDSErrorAttribute) private FClasses: Byte; FNumber: Word; FReason: AnsiString; protected function GetClasses: Byte; stdcall; function GetNumber: Word; stdcall; function GetReason: AnsiString; stdcall; procedure SetClasses(const Value: Byte); stdcall; procedure SetNumber(const Value: Word); stdcall; procedure SetReason(const Value: AnsiString); stdcall; procedure Build(AStream: TStream); override; procedure Parser(AStream: TStream); override; property Classes: Byte read GetClasses write SetClasses; property Number: Word read GetNumber write SetNumber; property Reason: AnsiString read GetReason write SetReason; public constructor Create; override; end; TDSMessage = class(TInterfacedObject, IDSMessage) private FUserName: IDSStringAttribute; FPassword: IDSStringAttribute; FReflectedFrom: IDSAddressAttribute; FServerName: IDSStringAttribute; FXorMappedAddress: IDSAddressAttribute; FXorOnly: IDSStringAttribute; FResponseAddress: IDSAddressAttribute; FSourceAddress: IDSAddressAttribute; FChangedAddress: IDSAddressAttribute; FChangeRequestAttribute: IDSChangeRequestAttribute; FErrorAttribute: IDSErrorAttribute; FMappedAddress: IDSAddressAttribute; FMessageType: Word; FTransactionID: TGUID; function GetHeadLength: Integer; protected function GetChangedAddress: IDSAddressAttribute; stdcall; function GetChangeRequestAttribute: IDSChangeRequestAttribute; stdcall; function GetErrorAttribute: IDSErrorAttribute; stdcall; function GetMappedAddress: IDSAddressAttribute; stdcall; function GetMessageLength: Integer; stdcall; function GetMessageType: Word; stdcall; function GetPassword: IDSStringAttribute; stdcall; function GetReflectedFrom: IDSAddressAttribute; stdcall; function GetResponseAddress: IDSAddressAttribute; stdcall; function GetServerName: IDSStringAttribute; stdcall; function GetSourceAddress: IDSAddressAttribute; stdcall; function GetTransactionID: TGUID; stdcall; function GetUserName: IDSStringAttribute; stdcall; function GetXorMappedAddress: IDSAddressAttribute; stdcall; function GetXorOnly: IDSStringAttribute; stdcall; procedure SetChangedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetChangeRequestAttribute(const Value: IDSChangeRequestAttribute); stdcall; procedure SetErrorAttribute(const Value: IDSErrorAttribute); stdcall; procedure SetMappedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetMessageType(const Value: Word); stdcall; procedure SetPassword(const Value: IDSStringAttribute); stdcall; procedure SetReflectedFrom(const Value: IDSAddressAttribute); stdcall; procedure SetResponseAddress(const Value: IDSAddressAttribute); stdcall; procedure SetServerName(const Value: IDSStringAttribute); stdcall; procedure SetSourceAddress(const Value: IDSAddressAttribute); stdcall; procedure SetUserName(const Value: IDSStringAttribute); stdcall; procedure SetXorMappedAddress(const Value: IDSAddressAttribute); stdcall; procedure SetXorOnly(const Value: IDSStringAttribute); stdcall; public constructor Create; procedure Build(AStream: TStream); procedure Parser(AStream: TStream); property ChangedAddress: IDSAddressAttribute read GetChangedAddress write SetChangedAddress; property ChangeRequestAttribute: IDSChangeRequestAttribute read GetChangeRequestAttribute write SetChangeRequestAttribute; property ErrorAttribute: IDSErrorAttribute read GetErrorAttribute write SetErrorAttribute; property HeadLength: Integer read GetHeadLength; property MappedAddress: IDSAddressAttribute read GetMappedAddress write SetMappedAddress; property MessageLength: Integer read GetMessageLength; property MessageType: Word read GetMessageType write SetMessageType; property Password: IDSStringAttribute read GetPassword write SetPassword; property ReflectedFrom: IDSAddressAttribute read GetReflectedFrom write SetReflectedFrom; property ResponseAddress: IDSAddressAttribute read GetResponseAddress write SetResponseAddress; property ServerName: IDSStringAttribute read GetServerName write SetServerName; property SourceAddress: IDSAddressAttribute read GetSourceAddress write SetSourceAddress; property TransactionID: TGUID read GetTransactionID; property UserName: IDSStringAttribute read GetUserName write SetUserName; property XorMappedAddress: IDSAddressAttribute read GetXorMappedAddress write SetXorMappedAddress; property XorOnly: IDSStringAttribute read GetXorOnly write SetXorOnly; end; procedure WriteWord(AStream: TStream; AWord: Word); function ReadWord(AStream: TStream): Word; function ReadIPAddress(AStream: TStream): TDSIPAddress; function ReadString(AStream: TStream): AnsiString; function SameIPAddress(IP1, IP2: TDSIPAddress): Boolean; function SameGUID(GUID1, GUID2: TGUID): Boolean; function IPAddressToString(AIP: TDSIPAddress): AnsiString; function IPAdressToPort(AIP: TDSIPAddress): Word; implementation procedure WriteWord(AStream: TStream; AWord: Word); var tmpByte: Byte; begin tmpByte := Hi(AWord); AStream.Write(tmpByte, SizeOf(tmpByte)); tmpByte := Lo(AWord); AStream.Write(tmpByte, SizeOf(tmpByte)); end; function ReadWord(AStream: TStream): Word; var tmpLowByte, tmpHighByte: Byte; begin AStream.Read(tmpHighByte, SizeOf(tmpHighByte)); AStream.Read(tmpLowByte, SizeOf(tmpLowByte)); Result := (tmpHighByte shl 8) or tmpLowByte; end; function ReadIPAddress(AStream: TStream): TDSIPAddress; begin FillChar(Result, SizeOf(Result), #0); AStream.Position := 1; AStream.Read(Result, SizeOf(Result)); end; function ReadString(AStream: TStream): AnsiString; var tmpChar: array [0..255] of ansichar; begin AStream.Read(tmpChar, Length(tmpChar)); Result := tmpChar; end; function SameIPAddress(IP1, IP2: TDSIPAddress): Boolean; begin Result := (IP1.Family = IP2.Family) and (IP1.Port_hi = IP2.Port_hi) and (IP1.Port_lo = IP2.Port_lo) and (IP1.IP[0] = IP2.IP[0]) and (IP1.IP[1] = IP2.IP[1]) and (IP1.IP[2] = IP2.IP[2]) and (IP1.IP[3] = IP2.IP[3]); end; function SameGUID(GUID1, GUID2: TGUID): Boolean; begin Result := (GUID1.D1 = GUID2.D1) and (GUID1.D2 = GUID2.D2) and (GUID1.D3 = GUID2.D3) and (GUID1.D4[0] = GUID2.D4[0]) and (GUID1.D4[1] = GUID2.D4[1]) and (GUID1.D4[2] = GUID2.D4[2]) and (GUID1.D4[3] = GUID2.D4[3]) and (GUID1.D4[4] = GUID2.D4[4]) and (GUID1.D4[5] = GUID2.D4[5]) and (GUID1.D4[6] = GUID2.D4[6]) and (GUID1.D4[7] = GUID2.D4[7]); end; function IPAddressToString(AIP: TDSIPAddress): AnsiString; begin Result := Format('%d.%d.%d.%d', [AIP.IP[0], AIP.IP[1], AIP.IP[2], AIP.IP[3]]); end; function IPAdressToPort(AIP: TDSIPAddress): Word; begin Result := AIP.Port_hi shl 8 + AIP.Port_lo; end; { TDSAttribute RFC 3489 11.2. Each attribute is TLV encoded, with a 16 bit type, 16 bit AttrLength, and variable value: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | AttrLength | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Value .... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } constructor TDSAttribute.Create; begin inherited; FAttributeLength := 0; end; destructor TDSAttribute.Destroy; begin inherited; end; procedure TDSAttribute.Build(AStream: TStream); begin WriteWord(AStream, AttributeType); WriteWord(AStream, AttributeLength); end; function TDSAttribute.GetAttributeLength: Word; begin Result := FAttributeLength; end; function TDSAttribute.GetAttributeType: Word; begin Result := FAttributeType; end; function TDSAttribute.GetHeadLength: Integer; begin Result := 4; end; procedure TDSAttribute.SetAttributeType(const Value: Word); begin FAttributeType := Value; end; procedure TDSAttribute.Parser(AStream: TStream); begin FAttributeType := ReadWord(AStream); FAttributeLength := ReadWord(AStream); end; { TDSAddressAttribute It consists of an eight bit address family, and a sixteen bit port, followed by a fixed length value representing the IP address. 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |x x x x x x x x| Family | Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ } constructor TDSAddressAttribute.Create; begin inherited; FillChar(FIPAddress, SizeOf(FIPAddress), #0); FAttributeLength := FAttributeLength + SizeOf(FIPAddress); end; procedure TDSAddressAttribute.Build(AStream: TStream); begin inherited; AStream.Write(FIPAddress, SizeOf(FIPAddress)); end; function TDSAddressAttribute.GetIPAddress: TDSIPAddress; begin Result := FIPAddress; end; procedure TDSAddressAttribute.SetIPAddress(const Value: TDSIPAddress); begin FIPAddress := Value; end; procedure TDSAddressAttribute.Parser(AStream: TStream); begin inherited; AStream.Read(FIPAddress, SizeOf(FIPAddress)); end; { TDSChangeRequestAttribute The CHANGE-REQUEST attribute is used by the client to request that the server use a different address and/or port when sending the response. The attribute is 32 bits long, although only two bits (A and B) are used: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 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 0 0 0 0 0 A B 0| +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ The meaning of the flags is: A: This is the "change IP" flag. If true, it requests the server to send the Binding Response with a different IP address than the one the Binding Request was received on. B: This is the "change port" flag. If true, it requests the server to send the Binding Response with a different port than the one the Binding Request was received on. } constructor TDSChangeRequestAttribute.Create; begin inherited; FChangeIP := False; FChangePort := False; FAttributeLength := FAttributeLength + 4; end; procedure TDSChangeRequestAttribute.Build(AStream: TStream); var tmpWord: Integer; begin inherited; tmpWord := 0; if FChangeIP then tmpWord := tmpWord or $4000000; //0000 0000 0000 0100 if FChangePort then tmpWord := tmpWord or $2000000; //0000 0000 0000 0010 AStream.Write(tmpWord, SizeOf(tmpWord)); end; function TDSChangeRequestAttribute.GetChangeIP: Boolean; begin Result := FChangeIP; end; function TDSChangeRequestAttribute.GetChangePort: Boolean; begin Result := FChangePort; end; procedure TDSChangeRequestAttribute.Parser(AStream: TStream); var tmpWord: Integer; begin inherited; AStream.Read(tmpWord, SizeOf(tmpWord)); FChangeIP := (tmpWord and $40000000) <> 0; FChangePort := (tmpWord and $20000000) <> 0; end; procedure TDSChangeRequestAttribute.SetChangeIP(const Value: Boolean); begin FChangeIP := Value; end; procedure TDSChangeRequestAttribute.SetChangePort(const Value: Boolean); begin FChangePort := Value; end; { TDSStringAttribute } constructor TDSStringAttribute.Create; begin inherited; FStringValue := ''; end; procedure TDSStringAttribute.Build(AStream: TStream); begin inherited; AStream.Write(FStringValue, Length(FStringValue) + 1); end; function TDSStringAttribute.GetStringValue: AnsiString; begin Result := FStringValue; end; procedure TDSStringAttribute.Parser(AStream: TStream); begin inherited; StringValue := ReadString(AStream); end; procedure TDSStringAttribute.SetStringValue(const Value: AnsiString); begin FStringValue := Value; FAttributeLength := Length(FStringValue) + 1; end; { TDSErrorAttribute } constructor TDSErrorAttribute.Create; begin inherited; FClasses := 0; FNumber := 0; FReason := ''; /// 3+length(FReason) FAttributeLength := FAttributeLength + 3; end; procedure TDSErrorAttribute.Build(AStream: TStream); begin inherited; AStream.Write(FClasses, SizeOf(FClasses)); WriteWord(AStream, FNumber); AStream.Write(FReason, Length(FReason) + 1); end; procedure TDSErrorAttribute.Parser(AStream: TStream); begin inherited; AStream.Read(FClasses, SizeOf(FClasses)); FNumber := ReadWord(AStream); Reason := ReadString(AStream); end; function TDSErrorAttribute.GetClasses: Byte; begin Result := FClasses; end; function TDSErrorAttribute.GetNumber: Word; begin Result := FNumber; end; function TDSErrorAttribute.GetReason: AnsiString; begin Result := FReason; end; procedure TDSErrorAttribute.SetClasses(const Value: Byte); begin FClasses := Value; end; procedure TDSErrorAttribute.SetNumber(const Value: Word); begin FNumber := Value; end; procedure TDSErrorAttribute.SetReason(const Value: AnsiString); begin FReason := Value; FAttributeLength := 3 + Length(FReason) + 1; end; { TDSMessage RFC 3489 11.1. All STUN messages consist of a 20 byte header: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | STUN Message Type | Message Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Transaction ID +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ The message length is the count, in bytes, of the size of the message, not including the 20 byte header. } constructor TDSMessage.Create; begin inherited; CreateGUID(FTransactionID); FMessageType := 0; end; function TDSMessage.GetHeadLength: Integer; begin Result := 20; end; procedure TDSMessage.Build(AStream: TStream); procedure WriteAttribute(AInterface: IInterface); var tmpAttr: IDSAttribute; begin if AInterface.QueryInterface(IDSAttribute, tmpAttr) = S_OK then tmpAttr.Build(AStream); end; begin ///null stream AStream.Size := 0; WriteWord(AStream, MessageType); ///write length at last WriteWord(AStream, 0); AStream.Write(FTransactionID, SizeOf(FTransactionID)); if FUserName <> nil then (FUserName as IDSAttribute).Build(AStream); if FPassword <> nil then (FPassword as IDSAttribute).Build(AStream); if FReflectedFrom <> nil then (FReflectedFrom as IDSAttribute).Build(AStream); if FServerName <> nil then (FServerName as IDSAttribute).Build(AStream); if FXorMappedAddress <> nil then (FXorMappedAddress as IDSAttribute).Build(AStream); if FXorOnly <> nil then (FXorOnly as IDSAttribute).Build(AStream); if FResponseAddress <> nil then (FResponseAddress as IDSAttribute).Build(AStream); if FSourceAddress <> nil then (FSourceAddress as IDSAttribute).Build(AStream); if FChangedAddress <> nil then (FChangedAddress as IDSAttribute).Build(AStream); if FChangeRequestAttribute <> nil then (FChangeRequestAttribute as IDSAttribute).Build(AStream); if FErrorAttribute <> nil then (FErrorAttribute as IDSAttribute).Build(AStream); if FMappedAddress <> nil then (FMappedAddress as IDSAttribute).Build(AStream); AStream.Position := 2; WriteWord(AStream, MessageLength); end; function TDSMessage.GetChangedAddress: IDSAddressAttribute; begin Result := FChangedAddress; end; function TDSMessage.GetChangeRequestAttribute: IDSChangeRequestAttribute; begin Result := FChangeRequestAttribute; end; function TDSMessage.GetErrorAttribute: IDSErrorAttribute; begin Result := FErrorAttribute; end; function TDSMessage.GetMappedAddress: IDSAddressAttribute; begin Result := FMappedAddress; end; function TDSMessage.GetMessageLength: Integer; begin Result := 0; if FUserName <> nil then Result := Result + (FUserName as IDSAttribute).HeadLength + (FUserName as IDSAttribute).AttributeLength; if FPassword <> nil then Result := Result + (FPassword as IDSAttribute).HeadLength + (FPassword as IDSAttribute).AttributeLength; if FReflectedFrom <> nil then Result := Result + (FReflectedFrom as IDSAttribute).HeadLength + (FReflectedFrom as IDSAttribute).AttributeLength; if FServerName <> nil then Result := Result + (FServerName as IDSAttribute).HeadLength + (FServerName as IDSAttribute).AttributeLength; if FXorMappedAddress <> nil then Result := Result + (FXorMappedAddress as IDSAttribute).HeadLength + (FXorMappedAddress as IDSAttribute).AttributeLength; if FXorOnly <> nil then Result := Result + (FXorOnly as IDSAttribute).HeadLength + (FXorOnly as IDSAttribute).AttributeLength; if FResponseAddress <> nil then Result := Result + (FResponseAddress as IDSAttribute).HeadLength + (FResponseAddress as IDSAttribute).AttributeLength; if FSourceAddress <> nil then Result := Result + (FSourceAddress as IDSAttribute).HeadLength + (FSourceAddress as IDSAttribute).AttributeLength; if FChangedAddress <> nil then Result := Result + (FChangedAddress as IDSAttribute).HeadLength + (FChangedAddress as IDSAttribute).AttributeLength; if FChangeRequestAttribute <> nil then Result := Result + (FChangeRequestAttribute as IDSAttribute).HeadLength + (FChangeRequestAttribute as IDSAttribute).AttributeLength; if FErrorAttribute <> nil then Result := Result + (FErrorAttribute as IDSAttribute).HeadLength + (FErrorAttribute as IDSAttribute).AttributeLength; if FMappedAddress <> nil then Result := Result + (FMappedAddress as IDSAttribute).HeadLength + (FMappedAddress as IDSAttribute).AttributeLength; end; function TDSMessage.GetMessageType: Word; begin Result := FMessageType; end; function TDSMessage.GetPassword: IDSStringAttribute; begin Result := FPassword; end; function TDSMessage.GetReflectedFrom: IDSAddressAttribute; begin Result := FReflectedFrom; end; function TDSMessage.GetResponseAddress: IDSAddressAttribute; begin Result := FResponseAddress; end; function TDSMessage.GetServerName: IDSStringAttribute; begin Result := FServerName; end; function TDSMessage.GetSourceAddress: IDSAddressAttribute; begin Result := SourceAddress; end; function TDSMessage.GetTransactionID: TGUID; begin Result := FTransactionID; end; function TDSMessage.GetUserName: IDSStringAttribute; begin Result := FUserName; end; function TDSMessage.GetXorMappedAddress: IDSAddressAttribute; begin Result := FXorMappedAddress; end; function TDSMessage.GetXorOnly: IDSStringAttribute; begin Result := FXorOnly; end; procedure TDSMessage.Parser(AStream: TStream); var tmpAttrType: Word; tmpAddrAttr: TDSAddressAttribute; tmpRequestAttr: TDSChangeRequestAttribute; tmpStringAttr: TDSStringAttribute; tmpErrorAttr: TDSErrorAttribute; tmpAttrLength, tmpMessageLength: Word; begin if AStream.Size = 0 then Exit; AStream.Position := 0; FMessageType := ReadWord(AStream); tmpMessageLength := ReadWord(AStream); AStream.Read(FTransactionID, SizeOf(FTransactionID)); while (AStream.Position < (tmpMessageLength + HeadLength)) and (AStream.Position <> AStream.Size) do begin tmpAttrType := ReadWord(AStream); tmpAttrLength := ReadWord(AStream); AStream.Position := AStream.Position - SizeOf(tmpAttrType) - SizeOf(tmpAttrLength); case tmpAttrType of DSAT_MappedAddress: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FMappedAddress := tmpAddrAttr; end; DSAT_ResponseAddress: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FResponseAddress := tmpAddrAttr; end; DSAT_ChangeRequest: begin tmpRequestAttr := TDSChangeRequestAttribute.Create; tmpRequestAttr.Parser(AStream); FChangeRequestAttribute := tmpRequestAttr; end; DSAT_SourceAddress: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FSourceAddress := tmpAddrAttr; end; DSAT_ChangedAddress: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FChangedAddress := tmpAddrAttr; end; DSAT_Username: begin tmpStringAttr := TDSStringAttribute.Create; tmpStringAttr.Parser(AStream); FUserName := tmpStringAttr; end; DSAT_Password: begin tmpStringAttr := TDSStringAttribute.Create; tmpStringAttr.Parser(AStream); FPassword := tmpStringAttr; end; DSAT_MessageIntegrity: ///ignore AStream.Position := AStream.Position + tmpAttrLength; DSAT_ErrorCode: begin tmpErrorAttr := TDSErrorAttribute.Create; tmpErrorAttr.Parser(AStream); FErrorAttribute := tmpErrorAttr; end; DSAT_UnknownAttribute: ///ignore AStream.Position := AStream.Position + tmpAttrLength; DSAT_ReflectedFrom: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FReflectedFrom := tmpAddrAttr; end; DSAT_XorMappedAddress: begin tmpAddrAttr := TDSAddressAttribute.Create; tmpAddrAttr.Parser(AStream); FXorMappedAddress := tmpAddrAttr; end; DSAT_XorOnly: begin tmpStringAttr := TDSStringAttribute.Create; tmpStringAttr.Parser(AStream); FXorOnly := tmpStringAttr; end; DSAT_ServerName: begin tmpStringAttr := TDSStringAttribute.Create; tmpStringAttr.Parser(AStream); FServerName := tmpStringAttr; end; else begin ///ignore AStream.Position := AStream.Position + tmpAttrLength; if tmpAttrLength = 0 then Exit; end; end; end; end; procedure TDSMessage.SetChangedAddress(const Value: IDSAddressAttribute); begin FChangedAddress := Value; end; procedure TDSMessage.SetChangeRequestAttribute(const Value: IDSChangeRequestAttribute); begin FChangeRequestAttribute := Value; end; procedure TDSMessage.SetErrorAttribute(const Value: IDSErrorAttribute); begin FErrorAttribute := Value; end; procedure TDSMessage.SetMappedAddress(const Value: IDSAddressAttribute); begin FMappedAddress := Value; end; procedure TDSMessage.SetMessageType(const Value: Word); begin FMessageType := Value; end; procedure TDSMessage.SetPassword(const Value: IDSStringAttribute); begin FPassword := Value; end; procedure TDSMessage.SetReflectedFrom(const Value: IDSAddressAttribute); begin FReflectedFrom := Value; end; procedure TDSMessage.SetResponseAddress(const Value: IDSAddressAttribute); begin FResponseAddress := Value; end; procedure TDSMessage.SetServerName(const Value: IDSStringAttribute); begin FServerName := Value; end; procedure TDSMessage.SetSourceAddress(const Value: IDSAddressAttribute); begin FSourceAddress := Value; end; procedure TDSMessage.SetUserName(const Value: IDSStringAttribute); begin FUserName := Value; end; procedure TDSMessage.SetXorMappedAddress(const Value: IDSAddressAttribute); begin FXorMappedAddress := Value; end; procedure TDSMessage.SetXorOnly(const Value: IDSStringAttribute); begin FXorOnly := Value; end; end.
unit MainUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TNotifyStringEvent = procedure (Sender: TObject; const aString: string) of object; TfrmMain = class(TForm) edtFilename: TEdit; edtMD5: TEdit; edtExpected: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Button1: TButton; procedure Button1Click(Sender: TObject); procedure edtFilenameChange(Sender: TObject); private procedure CalcMD5(aFilename: string; fOnCalculated: TNotifyStringEvent); procedure HandleOnCalculated(Sender: TObject; const aString: String); { Private declarations } public { Public declarations } end; var frmMain: TfrmMain; implementation uses System.Threading, IdHashMessageDigest; {$R *.dfm} procedure TfrmMain.Button1Click(Sender: TObject); var dlgOpen: TOpenDialog; begin dlgopen := TOpenDialog.create(nil); try if dlgOpen.Execute then edtFilename.text := dlgOpen.Filename; finally dlgOpen.free; end; end; procedure TfrmMain.HandleOnCalculated(Sender: TObject; const aString : String); begin edtMD5.text := aString; end; procedure TfrmMain.edtFilenameChange(Sender: TObject); begin CalcMD5(TEdit(Sender).Text, HandleOnCalculated); end; procedure TfrmMain.CalcMD5(aFilename: string; fOnCalculated: TNotifyStringEvent); begin TTask.Run( procedure var Stream : TMemoryStream; MD5: TIdHashMessageDigest5; aMD5 : string; begin MD5 := nil; Stream := TMemoryStream.Create; try Stream.LoadFromFile(aFilename); Stream.Position := 0; MD5 := TIdHashMessageDigest5.Create; aMD5 := MD5.HashStreamAsHex(Stream); TThread.Queue(nil, procedure begin if assigned(fOnCalculated) then fOnCalculated(Stream, aMD5); end ); finally MD5.Free; Stream.Free; end; end ) end; end.
{----------------------------------------------------------------------------- TrendFollowert Name: Author: Roman Purpose: АЛГОРИТМ: Все действия производим по закрытию указанного дня. Внутри дня ничего не делаем. Открытие - закрытие позиции только ордерами. Сигнальная линия - экспоненциальная средняя, период 3 сдвиг вперед (в будущее) - 3 Правила: 1. Пересечение телом свечи средней - ставятся ордера или покупку Н+5п. (если свеча восходящая), или продажу L-5п (если свеча нисходящая). 2. Касание нижней тенью средней - ставится ордер на покупку Н+5 п. Касание верхней тенью средней - ставится ордер на продажу L-5п 3. Ордер отменяем только при возникновении противоположного сигнала. 4. Переносим если возникает сигнал в ту же сторону, но более выгодный (выше при продаже, ниже при покупке) 5. После открытия стоп ставится на противоположном конце -(+) 5 п. той же свечи. 6. Потом стоп или переносится в безубыток (если закрытие свечи выше (ниже) уровня открытия позиции более чем 10 п.), или подтягивается ближе на минимум двух последних свечей при покупке или максимум двух последних свечей при продаже. Это делается на каждой новой свече до закрытия позиции. 7. Когда позиция открыта, на сигналы не реагируем, дополнительных позиций не открываем. 8. Стоп в сторону увеличения не переносится. 9. Если после открытия позиции не можем поджать в безубыток, и две след. свечи заканчиваются хуже цены открытия позиции, ставим тейк +5п. 10. Если закрыло в безубытке или по тейку, следующая свеча не касается средней, но идет в том же направлении (выше / ниже предыдущих 3 свечей), исполняем условие 1. 11. Если свеча упирается в линию с сильным наклоном, пересекает ее хвостом, а телом не смогла пересечь, и очевидно, что след. свеча начнется за средней, исполняем условие 1. History: -----------------------------------------------------------------------------} unit FC.Trade.Trader.AverageBreakthrough; {$I Compiler.inc} interface uses Classes, Math,Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Collections.Map,Properties.Obj, Properties.Definitions, StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators, Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, StockChart.Definitions.Drawing,Graphics; type IStockTraderAverageBreakthrough = interface ['{797ED06B-5E31-4DD4-8FBE-BEC5CDEF31E1}'] end; //Свойства ордера TStockOrderProperties=class; IStockOrderProperties = interface (ISCAttribute) ['{FC5C8FCF-7C5E-49AB-A30F-99830E7AC5DF}'] function GetObject:TStockOrderProperties; end; //Атрибут "большого" ордера IStockLargeOrderAttribute = interface (ISCAttribute) ['{1197FB87-425F-423A-B546-A6C814832F9C}'] end; //Атрибут "маленького" ордера IStockSmallOrderAttribute = interface (ISCAttribute) ['{BDE21E2D-9D99-4E8B-8FF0-566041187DFC}'] end; TStockOrderProperties = class (TNameValuePersistentObjectRefCounted,IStockOrderProperties,ISCAttribute) public //Когда перевернулся 1H - тренд не в нашу сторону H1TrendTurnTime:TDateTime; //from IStockOrderProperties function GetObject:TStockOrderProperties; end; TStockLargeOrderAttribute = class (TNameValuePersistentObjectRefCounted,IStockLargeOrderAttribute,ISCAttribute) end; //Атрибут "маленького" ордера TStockSmallOrderAttribute = class (TNameValuePersistentObjectRefCounted,IStockSmallOrderAttribute,ISCAttribute) end; TStockTraderAverageBreakthrough = class (TStockTraderBase,IStockTraderAverageBreakthrough) private //Это временные переменные, испольщуемые при трейдинге FMA: ISCIndicatorMA; FMAIndex: integer; FLow: array [0..4] of TSCRealNumber; FHigh: array [0..4] of TSCRealNumber; FOpen: array [0..4] of TSCRealNumber; FClose: array [0..4] of TSCRealNumber; FPassedTimes:TMap<TDateTime,Boolean>; FPassedTimes2:TMap<TDateTime,Boolean>; protected function GetOrderProperties(const aOrder: IStockOrder): TStockOrderProperties; procedure GetProperties(aList: TPropertyList); override; procedure OnPropertyChanged(aNotifier:TProperty); override; //Отрубаем стандартные механизмы установки ST TP procedure SetTrailingStopAccordingProperty(aOrder: IStockOrder); override; procedure SetStopLossAccordingProperty(aOrder: IStockOrder); override; function CreateIndicatorMA(const aChart: IStockChart): ISCIndicatorMA; procedure InitMA(const aMA:ISCIndicatorMA; it:TStockTimeInterval); //форма для тестирования function TestBenchDialogClass: TClass; override; function Spread: TSCRealNumber; function SignalToOpen(const aTime: TDateTime): integer; procedure TryOpenOrder(aOrder: IStockOrder; const aTime: TDateTime); //Постараться передвинуть SL в безубыток procedure MoveSLToProfitablePoint(const aOrder: IStockOrder; const aTime: TDateTime); procedure AnalyzeOpenedOrder(const aOrder: IStockOrder; const aTime: TDateTime); procedure AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); procedure SetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); public procedure SetProject(const aValue : IStockProject); override; procedure OnBeginWorkSession; override; //Посчитать procedure UpdateStep2(const aTime: TDateTime); override; constructor Create; override; destructor Destroy; override; procedure Dispose; override; end; implementation uses Variants,DateUtils, SystemService, Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message, StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory, FC.DataUtils; const TrendToOrderKind : array [TSCTrendType] of TStockOrderKind = (okBuy,okSell,okBuy); const aOrderMargin=0.0005; { TStockTraderAverageBreakthrough } constructor TStockTraderAverageBreakthrough.Create; begin inherited Create; UnRegisterProperties([PropTrailingStop,PropTrailingStopDescend,PropMinimizationRiskType]); FPassedTimes:=TMap<TDateTime,Boolean>.Create; FPassedTimes2:=TMap<TDateTime,Boolean>.Create; end; destructor TStockTraderAverageBreakthrough.Destroy; begin inherited; FreeAndNil(FPassedTimes); FreeAndNil(FPassedTimes2); end; procedure TStockTraderAverageBreakthrough.Dispose; begin inherited; end; function TStockTraderAverageBreakthrough.CreateIndicatorMA(const aChart: IStockChart): ISCIndicatorMA; var aCreated: boolean; begin result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'ParabolicSAR-'+aChart.StockSymbol.GetTimeIntervalName,true,aCreated) as ISCIndicatorMA; if aCreated then begin InitMA(result,aChart.StockSymbol.TimeInterval); end; end; procedure TStockTraderAverageBreakthrough.GetProperties(aList: TPropertyList); begin inherited; end; procedure TStockTraderAverageBreakthrough.OnBeginWorkSession; begin inherited; FPassedTimes.Clear; FPassedTimes2.Clear; end; procedure TStockTraderAverageBreakthrough.OnPropertyChanged(aNotifier: TProperty); begin inherited; end; procedure TStockTraderAverageBreakthrough.SetMark(const aOrder: IStockOrder;const aMarkType: TSCChartMarkKind; const aMessage: string); begin AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; procedure TStockTraderAverageBreakthrough.SetProject(const aValue: IStockProject); begin if GetProject=aValue then exit; inherited; if aValue=nil then while ExpertCount>0 do DeleteExpert(0); if aValue <> nil then begin FMA:=CreateIndicatorMA(aValue.GetStockChart(sti1440)); end; end; procedure TStockTraderAverageBreakthrough.SetStopLossAccordingProperty(aOrder: IStockOrder); begin //Ничего! end; procedure TStockTraderAverageBreakthrough.SetTrailingStopAccordingProperty(aOrder: IStockOrder); begin //Ничего! end; function TStockTraderAverageBreakthrough.TestBenchDialogClass: TClass; begin result:=nil; end; function TStockTraderAverageBreakthrough.SignalToOpen(const aTime: TDateTime): integer; var aMA: TSCRealNumber; begin result:=0; if FMAIndex<FMA.GetPeriod+1 then exit; aMA:=FMA.GetValue(FMAIndex); // Пересечение Средней телом свечи, свеча восходящая - покупаем, см. Пр.1 if ((FOpen[0] <=aMA) and (FClose[0] >aMA)) then begin result:=1; exit; end; // Пересечение Средней телом свечи, свеча нисходящая - продаем, см. Пр.1 if ((FOpen[0] >=aMA) and (FClose[0] <aMA)) then begin result:=-1; exit; end; // Касание Средней нижней тенью свечи - ордер на покупку,см. Пр.2 // Касанием считаем пересечение, когда хвост выглядывает не более чем на 10pt if (FOpen[0] > aMA) and (FClose[0] > aMA) and (FLow[0] <=aMA) {and (aMA-FLow[0]<0.0010) }then begin result:=2; exit; end; // else result:=(-3); // (продаем, см. Пр.11) !!! ТУТ НАДО ДОРАБОТАТЬ УСЛОВИЕ СИЛЬНОГО НАКЛОНА СРЕДНЕЙ // Касание Средней верхней тенью свечи - ордер на продажу // Касанием считаем пересечение, когда хвост выглядывает не более чем на 10pt if (FOpen[0] < aMA) and (FClose[0] < aMA) and (FHigh[0] >=aMA) {and (FHigh[0]-aMA<0.0010) }then begin result:=-2; exit; end; // else result:=( 3); // (покупаем, см. Пр.11) !!! ТУТ НАДО ДОРАБОТАТЬ УСЛОВИЕ СИЛЬНОГО НАКЛОНА СРЕДНЕЙ (* if ((FHigh[1]>FHigh[2]) and (FHigh[1]>FHigh[3]) and (FHigh[1]>FHigh[4])) then begin result:=( 4); // Последняя свеча выше предыдущих трех (покупаем, см. Пр.10) exit; end; if (( FLow[1]< FLow[2]) and ( FLow[1]< FLow[3]) and ( FLow[1]< FLow[4])) then begin result:=(-4); // Последняя свеча выше предыдущих трех (покупаем, см. Пр.10) exit; end; *) end; function TStockTraderAverageBreakthrough.Spread: TSCRealNumber; begin result:=GetBroker.PointToPrice(GetSymbol,GetBroker.GetMarketInfo(GetSymbol).Spread); end; procedure TStockTraderAverageBreakthrough.TryOpenOrder(aOrder: IStockOrder; const aTime: TDateTime); var aOP,aSL,aTP: TSCRealNumber; aSignalToOpen: integer; aDelete: boolean; begin aSignalToOpen:=SignalToOpen(aTime); // Если имеем ОТЛОЖЕННЫЙ ордер и есть сигнал на новой свече, то: if (aOrder<>nil) and (aOrder.GetState=osPending) and (aSignalToOpen<>0) then begin aDelete:=false; if ((aOrder.GetKind=okBuy) and (aSignalToOpen <0)) then // 1) Если возник противоположный сигнал (см. Пр.3), begin aDelete:=true; GetBroker.AddMessage(aOrder,'Возник противоположный сигнал Sell (см. Пр.3)'); end else if((aOrder.GetKind=okSell) and (aSignalToOpen >0)) then begin aDelete:=true; GetBroker.AddMessage(aOrder,'Возник противоположный сигнал Buy (см. Пр.3)'); end // 2) Если возник сигнал в ту же сторону, что и прежде (см. Пр.4), else if (aOrder.GetKind=okBuy) and (aSignalToOpen >0) and (aOrder.GetPendingOpenPrice>FHigh[0]+aOrderMargin+Spread) then begin aDelete:=true; GetBroker.AddMessage(aOrder,'Возник сигнал Buy в ту же сторону, переоткрываемся (см. Пр.4)'); end else if (aOrder.GetKind=okSell) and (aSignalToOpen <0) and (aOrder.GetPendingOpenPrice<FLow[0]-aOrderMargin) then begin aDelete:=true; GetBroker.AddMessage(aOrder,'Возник сигнал Sell в ту же сторону, переоткрываемся (см. Пр.4)'); end; if aDelete then aOrder.RevokePending //удалем прежний ордер else exit; end; if (aSignalToOpen >0) then begin aOP := FHigh[0]+aOrderMargin+Spread; //стоп ставится на противоположном конце -(+) 5 п. той же свечи. aSL := FLow[0]-aOrderMargin; aTP := 0; //TP=OP+1*(OP-SL); if aOrder=nil then aOrder:=CreateEmptyOrder; aOrder.OpenAt(GetSymbol,okBuy,aOP,GetRecommendedRate,aSL,aTP,0); // ПОКУПКА AddMessageAndSetMark(aOrder,mkArrowUp,'Сработал сигнал Buy') end else if (aSignalToOpen <0) then begin aOP := FLow[0]-aOrderMargin; //стоп ставится на противоположном конце -(+) 5 п. той же свечи. aSL := FHigh[0]+aOrderMargin+Spread; aTP := 0; //TP=OP-1*(SL-OP); if aOrder=nil then aOrder:=CreateEmptyOrder; aOrder.OpenAt(GetSymbol,okSell,aOP,GetRecommendedRate,aSL,aTP,0); // ПРОДАЖА AddMessageAndSetMark(aOrder,mkArrowDown,'Сработал сигнал Sell') end; end; procedure TStockTraderAverageBreakthrough.MoveSLToProfitablePoint(const aOrder: IStockOrder; const aTime: TDateTime); var aValue: TStockRealNumber; begin // 1) Если закрытие свечи произошло выше/ниже цены открытия позиции на 10 пунктов и более, то ставим б/у if (GetExpectedLoss(aOrder)>0) and (aOrder.GetCurrentProfit>=GetBroker.PointToPrice(GetSymbol,10)) then begin aValue:=aOrder.GetOpenPrice+OrderKindSign[aOrder.GetKind]*aOrderMargin; if MoveStopLossCloser(aOrder, aValue) then GetBroker.AddMessage(aOrder,'Поставили стоп в б/у'); end; end; procedure TStockTraderAverageBreakthrough.AnalyzeOpenedOrder(const aOrder: IStockOrder; const aTime: TDateTime); begin // 1) Если закрытие свечи произошло выше/ниже цены открытия позиции на 10 пунктов и более, то ставим б/у MoveSLToProfitablePoint(aOrder,aTime); if (aTime-aOrder.GetOpenTime>=1-1/24) then // Прошел 1 день после открытия позиции // 2) Передвигаем стоп на минимум/максимум двух последних свечей, но только в сторону его уменьшения begin if (aOrder.GetKind=okBuy) then begin if MoveStopLossCloser(aOrder,Min(FLow[0],FLow[1])) then GetBroker.AddMessage(aOrder,'Подтянули Buy-стоп на минимум двух последних свечей'); end else begin if MoveStopLossCloser(aOrder,Max(FHigh[0],FHigh[1])) then GetBroker.AddMessage(aOrder,'Подтянули Sell-стоп на максимум двух последних свечей'); end; end; if (aTime-aOrder.GetOpenTime>=2-1/24) then // Прошло 2 дня после открытия позиции if GetExpectedLoss(aOrder)>0 then // 3) Если после открытия позиции не можем поджать в безубыток, и две след. // Свечи заканчиваются хуже цены открытия позиции, ставим тейк 5 п. begin if (aOrder.GetKind=okBuy) then begin //aOrder.SetTakeProfit(aOrder.GetOpenPrice+Spread+aOrderMargin); //GetBroker.AddMessage(aOrder,'Не можем поджать в б/у. Поставили Buy-профит +5pt'); end else begin //aOrder.SetTakeProfit(aOrder.GetOpenPrice-aOrderMargin); //GetBroker.AddMessage(aOrder,'Не можем поджать в б/у. Поставили Sell-профит +5pt'); end; end; end; procedure TStockTraderAverageBreakthrough.UpdateStep2(const aTime: TDateTime); var i: integer; aOrder: IStockOrder; begin RemoveClosedOrders; FMAIndex:=FMA.GetInputData.FindExactMatched(aTime); if FMAIndex=-1 then raise EAlgoError.Create; //Раньше нельзя начинать if FMAIndex<max(FMA.GetPeriod,4) then exit; if aTime<EncodeDate(2006,1,1) then exit; // if DateTimeToStr(aTime)='20.01.2006 22:59:00' then // Pause(DateTimeToStr(aTime)); // Входим на каждой дневной свече только один раз при её открытии if (not FPassedTimes.Lookup(Trunc(aTime))) then if ((HourOfTheDay(aTime)=22) and (MinuteOfTheHour(aTime)=59)) or //желательно попасть в 22:59 ((HourOfTheDay(aTime)=23)) then begin //Заполняем последние 4 свечки for i := 0 to 4 do begin with FMA.GetInputData[FMAIndex-i] do begin FOpen[i]:=DataOpen; FHigh[i]:=DataHigh; FLow[i]:=DataLow; FClose[i]:=DataClose; end; end; //Перебираем все отложенные и открытые ордера for i := 0 to GetOrders.Count-1 do begin aOrder:=GetOrders[i]; if aOrder.GetState =osPending then begin TryOpenOrder(aOrder,aTime); end else if aOrder.GetState = osOpened then begin AnalyzeOpenedOrder(aOrder,aTime); end; end; //Если нет текущих открытых ордеров, то пытаемся открыть новый RemoveClosedOrders; if GetOrders.Count=0 then begin TryOpenOrder(nil,aTime); end; //Добавляем в словарь запись о том, что эту минуту мы уже обработали, чтобы //следующий раз мы опять не открылись FPassedTimes.Add(Trunc(aTime),true); end; //На открытие каждой новой свечи повторяем еще раз процедуру со б/у //У Бапишпольца как-то непонятно написано, то-ли надо это делать в конце суток, то ли в начале //У него срабатывает б/у уже в следующих сутках if HourOfTheDay(aTime) in [23,0] then begin //Перебираем все отложенные и открытые ордера for i := 0 to GetOrders.Count-1 do begin aOrder:=GetOrders[i]; if aOrder.GetState = osOpened then //Если б/у так и не выставили, пробуем еще разок, только на следующие сутки if (GetExpectedLoss(aOrder)>0) and (aTime-aOrder.GetPendingOpenTime>1) then begin MoveSLToProfitablePoint(aOrder,aTime); if GetExpectedLoss(aOrder)<0 then GetBroker.AddMessage(aOrder,'Cтоп в б/у был подвинут после закрытия рынка (22:59)'); end; end; FPassedTimes2.Add(Trunc(aTime),true); end; end; procedure TStockTraderAverageBreakthrough.AddMessageAndSetMark(const aOrder: IStockOrder; const aMarkType: TSCChartMarkKind; const aMessage: string); begin GetBroker.AddMessage(aOrder,aMessage); AddMarkToCharts(GetBroker.GetCurrentTime, GetBroker.GetCurrentPrice({aOrder}self.GetSymbol,bpkBid), aMarkType,aMessage); end; function TStockTraderAverageBreakthrough.GetOrderProperties(const aOrder: IStockOrder): TStockOrderProperties; var i: integer; begin i:=aOrder.GetAttributes.IndexOf(IStockOrderProperties); if i=-1 then raise EAlgoError.Create; result:=(aOrder.GetAttributes.Items[i] as IStockOrderProperties).GetObject; end; procedure TStockTraderAverageBreakthrough.InitMA(const aMA:ISCIndicatorMA; it:TStockTimeInterval); begin aMA.SetMAMethod(mamExponential); aMA.SetShift(3); aMA.SetPeriod(3); aMA.SetApplyTo(atClose); end; { TStockOrderProperties } function TStockOrderProperties.GetObject: TStockOrderProperties; begin result:=self; end; initialization FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','Average Breakthrough',TStockTraderAverageBreakthrough,IStockTraderAverageBreakthrough); end.
{ ID: a2peter1 PROG: frac1 LANG: PASCAL } {$B-,I-,Q-,R-,S-} const problem = 'frac1'; var N : longint; procedure print(a,b,c,d: longint); begin if (a + c > N) or (b + d > N) then exit; print(a,b,a + c,b + d); writeln(a + c,'/',b + d); print(a + c,b + d,c,d); end;{print} begin assign(input,problem + '.in'); reset(input); assign(output,problem + '.out'); rewrite(output); readln(N); {Farey sequence} writeln('0/1'); print(0,1,1,1); writeln('1/1'); close(output); end.{main}
PROGRAM Fibonacci; var calls: longint; FUNCTION Fib(n: integer): longint; BEGIN Inc(calls); if n <= 2 then Fib := 1 else Fib := Fib(n-1) + Fib(n-2); END; (* Fib *) FUNCTION FibRec(n: integer; fn2, fn1: longint): longint; BEGIN if n <= 2 then FibRec := fn1 else FibRec := FibRec(n - 1, fn1, fn2 + fn1); END; FUNCTION Fib2(n: integer): longint; BEGIN Inc(calls); Fib2 := FibRec(n, 1, 1); END; BEGIN (* Fibonacci *) calls := 0; WriteLn('Fib 6: ', Fib2(6), ' calls: ', calls); calls := 0; WriteLn('Fib 10: ', Fib2(10), ' calls: ', calls); calls := 0; WriteLn('Fib 11: ', Fib2(11), ' calls: ', calls); calls := 0; WriteLn('Fib 12: ', Fib2(12), ' calls: ', calls); calls := 0; WriteLn('Fib 13: ', Fib2(13), ' calls: ', calls); calls := 0; WriteLn('Fib 14: ', Fib2(14), ' calls: ', calls); calls := 0; WriteLn('Fib 25: ', Fib2(25), ' calls: ', calls); END. (* Fibonacci *)
unit AddNewTable; interface uses SysUtils, Types, Classes, Variants, QGraphics, QControls, QForms, QDialogs, QStdCtrls, DB, DBClient, QButtons, QComCtrls, QGrids, QDBGrids; type TForm2 = class(TForm) ComboDataType: TComboBox; ClientDataSet1: TClientDataSet; EditFieldName: TEdit; EditFieldSize: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; ButtonAddField: TButton; ButtonCreateTable: TButton; DBGrid1: TDBGrid; DataSource1: TDataSource; SaveDialog1: TSaveDialog; ButtonCancel: TButton; procedure ButtonAddFieldClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure ButtonCreateTableClick(Sender: TObject); procedure ComboDataTypeChange(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; FieldNum: Integer; implementation uses MyBaseExpMain; {$R *.xfm} procedure TForm2.ButtonAddFieldClick(Sender: TObject); begin try FieldNum:=FieldNum+1; ClientDataSet1.Active:=False; with ClientDataSet1.FieldDefs.AddFieldDef do begin Name:=EditFieldName.Text; case ComboDataType.ItemIndex of 0:begin DataType:=ftString; Size:=StrToInt(EditFieldSize.Text); end; 1:DataType:=ftInteger; end; end; ClientDataSet1.CreateDataSet; EditFieldName.Text:='Field'+IntToStr(FieldNum); ComboDataType.ItemIndex:=0; finally ClientDataSet1.Active:=True; end; end; procedure TForm2.FormShow(Sender: TObject); begin FieldNum:=1; EditFieldName.Text:='Field1'; ClientDataSet1.Active:=False; ClientDataSet1.FieldDefs.Clear; end; procedure TForm2.ButtonCreateTableClick(Sender: TObject); begin If SaveDialog1.Execute then begin Clientdataset1.SaveToFile(SaveDialog1.filename,dfxml); Form1.ClientDataSet1.Active:=false; Form1.ClientDataSet1.FileName:=SaveDialog1.FileName; Form1.ClientDataSet1.Active:=true; Form1.StatusBar1.Panels[0].Text:=SaveDialog1.FileName; end; Form2.Close; end; procedure TForm2.ComboDataTypeChange(Sender: TObject); begin case ComboDataType.ItemIndex of 0:EditFieldSize.Text:='15'; 1:EditFieldSize.Text:='0'; end; end; procedure TForm2.ButtonCancelClick(Sender: TObject); begin Form2.Close; end; end.
unit FizzBuzz.GameLogic; interface type TFizzBuzzGame = class public const FizzText = 'Fizz'; BuzzText = 'Buzz'; private const defFizzValue = 3; defBuzzValue = 5; private fFizz:Integer; fBuzz:Integer; protected function IsMultiple(const x, y:Integer):Boolean; public constructor Create(); function CalcFizzBuzz(const pValue:Integer):string; property Fizz:Integer read fFizz write fFizz; property Buzz:Integer read fBuzz write fBuzz; end; implementation uses System.SysUtils; constructor TFizzBuzzGame.Create(); begin inherited; fFizz := defFizzValue; fBuzz := defBuzzValue; end; function TFizzBuzzGame.IsMultiple(const x, y:Integer):Boolean; begin Result := (x mod y = 0); end; function TFizzBuzzGame.CalcFizzBuzz(const pValue:Integer):string; begin Result := ''; if IsMultiple(pValue, Fizz) then begin Result := FizzText; end; if IsMultiple(pValue, Buzz) then begin Result := Result + BuzzText; end; if Result = '' then begin Result := IntToStr(pValue); end; end; end.
unit Test_FIToolkit.Commons.Utils; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses System.SysUtils, TestFramework, FIToolkit.Commons.Utils; type TestFIToolkitCommonsUtils = class (TGenericTestCase) published procedure TestAbortException; procedure TestArrayOfConstToStringArray; procedure TestExpandEnvVars; procedure TestGetFixInsightExePath; procedure TestGetModuleVersion; procedure TestIff; procedure TestPressAnyKeyPrompt; procedure TestPrintLn; procedure TestReadSmallTextFile; procedure TestTValueArrayToStringArray; procedure TestWaitForFileAccess; end; TestTExceptionHelper = class (TGenericTestCase) private type ETestError1 = class (Exception); ETestError2 = class (Exception); published procedure TestToString; end; TestTFileNameHelper = class (TGenericTestCase) published procedure TestExpand; procedure TestGetComparer; procedure TestIsApplicable; procedure TestIsEmpty; end; TestTPathHelper = class (TGenericTestCase) published procedure TestExpandIfNotExists; procedure TestGetDirectoryName; procedure TestGetExePath; procedure TestGetFullPath; procedure TestGetQuotedPath; procedure TestIsApplicableFileName; procedure TestIncludeTrailingPathDelimiter; end; TestTRttiTypeHelper = class (TGenericTestCase) private type TTestAttribute = class abstract (TCustomAttribute); IsArrayPropAttribute = class (TTestAttribute); IsStringPropAttribute = class (TTestAttribute); TTestStaticArray = array [0..9] of Byte; TTestDynamicArray = TArray<Byte>; strict private FDynamicArray : TTestDynamicArray; FStaticArray : TTestStaticArray; FAnsiString : AnsiString; FRawByteString : RawByteString; FShortString : ShortString; FString : String; FUnicodeString : UnicodeString; FUTF8String : UTF8String; FWideString : WideString; public [IsArrayProp] property PropDynamicArray : TTestDynamicArray read FDynamicArray; [IsArrayProp] property PropStaticArray : TTestStaticArray read FStaticArray; [IsStringProp] property PropAnsiString : AnsiString read FAnsiString; [IsStringProp] property PropRawByteString : RawByteString read FRawByteString; [IsStringProp] property PropShortString : ShortString read FShortString; [IsStringProp] property PropString : String read FString; [IsStringProp] property PropUnicodeString : UnicodeString read FUnicodeString; [IsStringProp] property PropUTF8String : UTF8String read FUTF8String; [IsStringProp] property PropWideString : WideString read FWideString; published procedure TestGetFullName; procedure TestGetMethod; procedure TestIsArray; procedure TestIsString; end; TestTTypeInfoHelper = class (TGenericTestCase) published procedure TestIsArray; procedure TestIsString; end; TestTTypeKindHelper = class (TGenericTestCase) published procedure TestIsArray; procedure TestIsString; end; TestTVarRecHelper = class (TGenericTestCase) published procedure TestToString; end; implementation uses System.Classes, System.IOUtils, System.Types, System.TypInfo, System.Rtti, System.Threading, Winapi.Windows, TestUtils, TestConsts; type TDummyClass = class (TObject); { TestFIToolkitCommonsUtils } procedure TestFIToolkitCommonsUtils.TestAbortException; begin CheckException( procedure begin raise AbortException; end, EAbort, 'CheckException::EAbort' ); end; procedure TestFIToolkitCommonsUtils.TestArrayOfConstToStringArray; var arrS : TArray<String>; begin arrS := ArrayOfConstToStringArray([42, True, 'test']); CheckEquals('42', arrS[0], 'arrS[0] = 42'); CheckEquals('True', arrS[1], 'arrS[1] = True'); CheckEquals('test', arrS[2], 'arrS[2] = "test"'); end; procedure TestFIToolkitCommonsUtils.TestExpandEnvVars; const STR_ENV_VAR = '%ProgramFiles%'; var ReturnValue, sExpected : String; begin ReturnValue := ExpandEnvVars(STR_ENV_VAR); CheckTrue(TDirectory.Exists(ReturnValue), 'CheckTrue::TDirectory.Exists(%s)', [ReturnValue]); CheckNotEquals(STR_ENV_VAR, ReturnValue, 'ReturnValue <> STR_ENV_VAR'); sExpected := TPath.GetGUIDFileName.QuotedString('%'); ReturnValue := ExpandEnvVars(sExpected); CheckEquals(sExpected, ReturnValue, 'ReturnValue = sExpected'); end; procedure TestFIToolkitCommonsUtils.TestGetFixInsightExePath; var ReturnValue : TFileName; begin ReturnValue := GetFixInsightExePath; CheckTrue(TPath.HasValidPathChars(ReturnValue, False), 'CheckTrue::HasValidPathChars'); CheckTrue(TPath.HasValidFileNameChars(TPath.GetFileName(ReturnValue), False), 'CheckTrue::HasValidFileNameChars'); CheckTrue(TFile.Exists(ReturnValue) or (ReturnValue = String.Empty), 'CheckTrue::(Exists or Empty)'); end; procedure TestFIToolkitCommonsUtils.TestGetModuleVersion; var iMajor, iMinor, iRelease, iBuild : Word; ReturnValue : Boolean; begin iMajor := 1; iMinor := 1; iRelease := 1; iBuild := 1; ReturnValue := GetModuleVersion(INVALID_HANDLE_VALUE, iMajor, iMinor, iRelease, iBuild); CheckFalse(ReturnValue, 'CheckFalse::ReturnValue'); CheckEquals<Word>(0, iMajor, 'iMajor = 0'); CheckEquals<Word>(0, iMinor, 'iMinor = 0'); CheckEquals<Word>(0, iRelease, 'iRelease = 0'); CheckEquals<Word>(0, iBuild, 'iBuild = 0'); ReturnValue := GetModuleVersion(GetModuleHandle(kernelbase), iMajor, iMinor, iRelease, iBuild); CheckTrue(ReturnValue, 'CheckFalse::ReturnValue'); CheckNotEquals<Word>(0, iMajor, 'iMajor <> 0'); end; procedure TestFIToolkitCommonsUtils.TestIff; type TTestEnum = (teFirst, teSecond, teThird); var iReturnValue, iTruePart, iFalsePart : Integer; sReturnValue, sTruePart, sFalsePart : String; eReturnValue, eTruePart, eFalsePart : TTestEnum; begin iTruePart := 1; iFalsePart := 0; sTruePart := '1'; sFalsePart := '0'; eTruePart := teFirst; eFalsePart := teThird; iReturnValue := Iff.Get<Integer>(True, iTruePart, iFalsePart); CheckEquals(iTruePart, iReturnValue, 'iReturnValue = iTruePart'); iReturnValue := Iff.Get<Integer>(False, iTruePart, iFalsePart); CheckEquals(iFalsePart, iReturnValue, 'iReturnValue = iFalsePart'); sReturnValue := Iff.Get<String>(True, sTruePart, sFalsePart); CheckEquals(sTruePart, sReturnValue, 'sReturnValue = sTruePart'); sReturnValue := Iff.Get<String>(False, sTruePart, sFalsePart); CheckEquals(sFalsePart, sReturnValue, 'sReturnValue = sFalsePart'); eReturnValue := Iff.Get<TTestEnum>(True, eTruePart, eFalsePart); CheckTrue(eReturnValue = eTruePart, 'eReturnValue = eTruePart'); eReturnValue := Iff.Get<TTestEnum>(False, eTruePart, eFalsePart); CheckTrue(eReturnValue = eFalsePart, 'eReturnValue = eFalsePart'); end; procedure TestFIToolkitCommonsUtils.TestPressAnyKeyPrompt; begin CheckException( procedure begin PressAnyKeyPrompt; end, nil, 'CheckException::<nil>' ); end; procedure TestFIToolkitCommonsUtils.TestPrintLn; begin CheckException( procedure begin PrintLn; end, nil, 'CheckException::<nil>' ); CheckException( procedure begin PrintLn('test'); end, nil, 'CheckException::<nil>' ); CheckException( procedure begin PrintLn(['test1', 'test2', 42]); end, nil, 'CheckException::<nil>' ); end; procedure TestFIToolkitCommonsUtils.TestReadSmallTextFile; const ARR_TEXT : array of String = [ 'line1', 'line2', 'line3', 'line4', 'line5', 'line6' ]; STR_FILENAME = 'temp_file.txt'; var L : TStringList; S : String; sFileName : TFileName; begin L := TStringList.Create; try for S in ARR_TEXT do L.Add(S); sFileName := TestDataDir + STR_FILENAME; L.SaveToFile(sFileName); { Case #1 - invalid params } S := ReadSmallTextFile(STR_NON_EXISTENT_FILE, 0, 0); CheckTrue(S.IsEmpty, 'CheckTrue::S.IsEmpty<invalid file name>'); S := ReadSmallTextFile(sFileName, -1, 1); CheckEquals(ARR_TEXT[0], S, '(S = ARR_TEXT[0])::<StartLine lt 0>'); S := ReadSmallTextFile(sFileName, 1, -1); CheckTrue(S.IsEmpty, 'CheckTrue::S.IsEmpty<EndLine lt 0>'); S := ReadSmallTextFile(sFileName, 2, 1); CheckTrue(S.IsEmpty, 'CheckTrue::S.IsEmpty<StartLine gt EndLine>'); S := ReadSmallTextFile(sFileName, Length(ARR_TEXT) + 1, Length(ARR_TEXT) + 2); CheckTrue(S.IsEmpty, 'CheckTrue::S.IsEmpty<StartLine gt ARR_TEXT.Length>'); { Case #2 - read all } S := ReadSmallTextFile(sFileName, 0, 0); CheckEquals(L.Text, S, 'S = L.Text'); { Case #3 - read part } S := ReadSmallTextFile(sFileName, 3, 5); CheckEquals(String.Join(sLineBreak, [ARR_TEXT[2], ARR_TEXT[3], ARR_TEXT[4]]), S, 'S = ARR_TEXT[2..4]'); finally L.Free; System.SysUtils.DeleteFile(sFileName); end; end; procedure TestFIToolkitCommonsUtils.TestTValueArrayToStringArray; var arrS : TArray<String>; begin arrS := TValueArrayToStringArray([42, True, 'test']); CheckEquals('42', arrS[0], 'arrS[0] = 42'); CheckEquals('True', arrS[1], 'arrS[1] = True'); CheckEquals('test', arrS[2], 'arrS[2] = "test"'); end; procedure TestFIToolkitCommonsUtils.TestWaitForFileAccess; const INT_CHECK_INTERVAL = 100; INT_TIMEOUT = INT_CHECK_INTERVAL * 4; var sFileName : String; ReturnValue : Boolean; Task : ITask; begin sFileName := GetTestIniFileName; System.SysUtils.DeleteFile(sFileName); ReturnValue := WaitForFileAccess(sFileName, TFileAccess.faRead, 0, 0); CheckFalse(ReturnValue, 'CheckFalse::ReturnValue<not FileExists(sFileName)>'); Task := TTask.Run( procedure begin TThread.Sleep(INT_TIMEOUT); TFile.Create(sFileName).Free; end ); ReturnValue := WaitForFileAccess(sFileName, TFileAccess.faRead, INT_CHECK_INTERVAL, INT_TIMEOUT div 2); CheckTrue(not ReturnValue and (Task.Status = TTaskStatus.Running), 'CheckTrue::(not ReturnValue)<Task.Status = Running>'); ReturnValue := WaitForFileAccess(sFileName, TFileAccess.faRead, INT_CHECK_INTERVAL, INT_TIMEOUT); CheckTrue(ReturnValue and (Task.Status = TTaskStatus.Completed), 'CheckTrue::(ReturnValue)<Task.Status = Completed>'); end; { TestTExceptionHelper } procedure TestTExceptionHelper.TestToString; const STR_ERRMSG1 = 'Error1'; STR_ERRMSG2 = 'Error2'; var ReturnValue : String; begin try try raise ETestError1.Create(STR_ERRMSG1); except Exception.RaiseOuterException(ETestError2.Create(STR_ERRMSG2)); end; except on E: Exception do begin CheckEquals(E.ToString, E.ToString(False), 'E.ToString(False) = E.ToString'); ReturnValue := E.ToString(True); CheckTrue(ReturnValue.Contains(ETestError1.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [ETestError1.ClassName]); CheckTrue(ReturnValue.Contains(STR_ERRMSG1), 'CheckTrue::ReturnValue.Contains(%s)', [STR_ERRMSG1]); CheckTrue(ReturnValue.Contains(ETestError2.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [ETestError2.ClassName]); CheckTrue(ReturnValue.Contains(STR_ERRMSG2), 'CheckTrue::ReturnValue.Contains(%s)', [STR_ERRMSG2]); CheckTrue(ReturnValue.Contains(E.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [E.ClassName]); CheckTrue(ReturnValue.Contains(E.Message), 'CheckTrue::ReturnValue.Contains(%s)', [E.Message]); CheckTrue(ReturnValue.Contains(E.InnerException.Message), 'CheckTrue::ReturnValue.Contains(%s)', [E.InnerException.Message]); end; end; try raise EAggregateException.Create([ETestError1.Create(STR_ERRMSG1), ETestError2.Create(STR_ERRMSG2)]); except on E: Exception do begin CheckEquals(E.ToString, E.ToString(False), 'E.ToString(False) = E.ToString'); ReturnValue := E.ToString(True); CheckTrue(ReturnValue.Contains(ETestError1.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [ETestError1.ClassName]); CheckTrue(ReturnValue.Contains(STR_ERRMSG1), 'CheckTrue::ReturnValue.Contains(%s)', [STR_ERRMSG1]); CheckTrue(ReturnValue.Contains(ETestError2.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [ETestError2.ClassName]); CheckTrue(ReturnValue.Contains(STR_ERRMSG2), 'CheckTrue::ReturnValue.Contains(%s)', [STR_ERRMSG2]); CheckTrue(ReturnValue.Contains(E.ClassName), 'CheckTrue::ReturnValue.Contains(%s)', [E.ClassName]); CheckTrue(ReturnValue.Contains(E.Message), 'CheckTrue::ReturnValue.Contains(%s)', [E.Message]); end; end; end; { TestTFileNameHelper } procedure TestTFileNameHelper.TestExpand; var sFileName : TFileName; sExpandedFileName : String; begin sFileName := '..\dir\file.ext'; sExpandedFileName := sFileName.Expand; CheckFalse(sExpandedFileName.StartsWith('..\'), 'CheckFalse::StartsWith("..\")'); CheckTrue(sExpandedFileName.Length > Length(sFileName), 'CheckTrue::(Expanded.Length > Original.Length)'); end; procedure TestTFileNameHelper.TestGetComparer; var sFileName, sLesser, sEqual, sGreater : TFileName; begin sFileName := 'D:\work\project.doc'; sLesser := 'C:\work\project.doc'; sEqual := 'D:\WORK\project.doc'; sGreater := 'E:\work\project.doc'; with TFileName.GetComparer do begin CheckEquals(GreaterThanValue, Compare(sFileName, sLesser), 'sFileName > sLesser'); CheckEquals(EqualsValue, Compare(sFileName, sEqual), 'sFileName = sEqual'); CheckEquals(LessThanValue, Compare(sFileName, sGreater), 'sFileName < sGreater'); end; end; procedure TestTFileNameHelper.TestIsApplicable; var FileName : TFileName; begin FileName := TPath.GetDirectoryName(ParamStr(0)); CheckFalse(FileName.IsApplicable, 'CheckFalse::(%s)', [FileName]); FileName := TPath.GetFileName(ParamStr(0)); CheckTrue(FileName.IsApplicable, 'CheckTrue::(%s)', [FileName]); FileName := ParamStr(0); CheckTrue(FileName.IsApplicable, 'CheckTrue::(%s)', [FileName]); FileName := STR_NON_EXISTENT_DIR; CheckFalse(FileName.IsApplicable, 'CheckFalse::(%s)', [STR_NON_EXISTENT_DIR]); FileName := STR_INVALID_FILENAME; CheckFalse(FileName.IsApplicable, 'CheckFalse::(%s)', [STR_INVALID_FILENAME]); end; procedure TestTFileNameHelper.TestIsEmpty; var FileName : TFileName; begin FileName := String.Empty; CheckTrue(FileName.IsEmpty, 'CheckTrue::(<empty>)'); FileName := ' '; CheckFalse(FileName.IsEmpty, 'CheckFalse::(<whitespace>)'); FileName := STR_NON_EXISTENT_FILE; CheckFalse(FileName.IsEmpty, 'CheckFalse::(<filename>)'); end; { TestTPathHelper } procedure TestTPathHelper.TestExpandIfNotExists; const STR_ENV_VAR = '%SystemRoot%'; var ReturnValue : String; begin ReturnValue := TPath.ExpandIfNotExists(STR_ENV_VAR); CheckNotEquals(STR_ENV_VAR, ReturnValue, 'ReturnValue <> STR_ENV_VAR'); end; procedure TestTPathHelper.TestGetDirectoryName; const STR_FULL_FILE_NAME = 'C:\test\file.ext'; STR_SHORT_FILE_NAME = 'file.ext'; var ReturnValue : String; begin ReturnValue := TPath.GetDirectoryName(String.Empty, False); CheckTrue(ReturnValue.IsEmpty, 'CheckTrue::ReturnValue.IsEmpty<False>'); ReturnValue := TPath.GetDirectoryName(String.Empty, True); CheckTrue(ReturnValue.IsEmpty, 'CheckTrue::ReturnValue.IsEmpty<True>'); ReturnValue := TPath.GetDirectoryName(STR_FULL_FILE_NAME, False); CheckFalse(ReturnValue.EndsWith(TPath.DirectorySeparatorChar), 'CheckFalse::EndsWith(TPath.DirectorySeparatorChar)</False>'); ReturnValue := TPath.GetDirectoryName(STR_FULL_FILE_NAME, True); CheckTrue(ReturnValue.EndsWith(TPath.DirectorySeparatorChar), 'CheckTrue::EndsWith(TPath.DirectorySeparatorChar)</True>'); ReturnValue := TPath.GetDirectoryName(STR_SHORT_FILE_NAME, False); CheckTrue(ReturnValue.IsEmpty, 'CheckTrue::ReturnValue.IsEmpty<STR_SHORT_FILE_NAME, False>'); ReturnValue := TPath.GetDirectoryName(STR_SHORT_FILE_NAME, True); CheckTrue(ReturnValue.IsEmpty, 'CheckTrue::ReturnValue.IsEmpty<STR_SHORT_FILE_NAME, True>'); end; procedure TestTPathHelper.TestGetExePath; var ReturnValue, sExpected : String; begin ReturnValue := TPath.GetExePath; sExpected := ExtractFilePath(ParamStr(0)); CheckEquals(sExpected, ReturnValue, 'ReturnValue = sExpected'); CheckTrue(ReturnValue.EndsWith(TPath.DirectorySeparatorChar), 'CheckTrue::EndsWith(TPath.DirectorySeparatorChar)'); CheckTrue(TDirectory.Exists(ReturnValue), 'CheckTrue::TDirectory.Exists(ReturnValue)'); end; procedure TestTPathHelper.TestGetFullPath; const STR_ENV_VAR = '%ProgramFiles%'; var ReturnValue, sExpected : String; begin ReturnValue := TPath.GetFullPath(STR_ENV_VAR, True, True); CheckTrue(TDirectory.Exists(ReturnValue), 'CheckTrue::TDirectory.Exists(%s)', [ReturnValue]); CheckNotEquals(STR_ENV_VAR, ReturnValue, 'ReturnValue <> STR_ENV_VAR'); sExpected := ParamStr(0); ReturnValue := TPath.GetFullPath(sExpected, False, True); CheckEquals(sExpected, ReturnValue, 'ReturnValue = sExpected'); end; procedure TestTPathHelper.TestGetQuotedPath; const CHR_QUOTE = '"'; STR_PATH_QUOTED_NONE = 'C:\test\file.ext'; STR_PATH_QUOTED_LEFT = CHR_QUOTE + STR_PATH_QUOTED_NONE; STR_PATH_QUOTED_RIGHT = STR_PATH_QUOTED_NONE + CHR_QUOTE; STR_PATH_QUOTED_BOTH = CHR_QUOTE + STR_PATH_QUOTED_NONE + CHR_QUOTE; STR_PATH_EXPECTED = CHR_QUOTE + STR_PATH_QUOTED_NONE + CHR_QUOTE; var ReturnValue : String; begin ReturnValue := TPath.GetQuotedPath(String.Empty, CHR_QUOTE); CheckTrue(ReturnValue.StartsWith(CHR_QUOTE) and ReturnValue.EndsWith(CHR_QUOTE), 'CheckTrue::(ReturnValue(<empty>) = "")'); ReturnValue := TPath.GetQuotedPath(STR_PATH_QUOTED_NONE, CHR_QUOTE); CheckEquals(STR_PATH_EXPECTED, ReturnValue, 'ReturnValue(STR_PATH_QUOTED_NONE) = STR_EXPECTED'); ReturnValue := TPath.GetQuotedPath(STR_PATH_QUOTED_LEFT, CHR_QUOTE); CheckEquals(STR_PATH_EXPECTED, ReturnValue, 'ReturnValue(STR_PATH_QUOTED_LEFT) = STR_EXPECTED'); ReturnValue := TPath.GetQuotedPath(STR_PATH_QUOTED_RIGHT, CHR_QUOTE); CheckEquals(STR_PATH_EXPECTED, ReturnValue, 'ReturnValue(STR_PATH_QUOTED_RIGHT) = STR_EXPECTED'); ReturnValue := TPath.GetQuotedPath(STR_PATH_QUOTED_BOTH, CHR_QUOTE); CheckEquals(STR_PATH_EXPECTED, ReturnValue, 'ReturnValue(STR_PATH_QUOTED_BOTH) = STR_EXPECTED'); ReturnValue := TPath.GetQuotedPath(STR_PATH_QUOTED_NONE, #0); CheckEquals(STR_PATH_QUOTED_NONE, ReturnValue, 'ReturnValue(STR_PATH_QUOTED_NONE, #0) = STR_PATH_QUOTED_NONE'); end; procedure TestTPathHelper.TestIncludeTrailingPathDelimiter; const STR_PATH = 'C:\test\subdir'; var ReturnValue : String; begin ReturnValue := TPath.IncludeTrailingPathDelimiter(String.Empty); CheckTrue(ReturnValue.IsEmpty, 'CheckTrue::ReturnValue.IsEmpty'); ReturnValue := TPath.IncludeTrailingPathDelimiter(STR_PATH); CheckTrue(ReturnValue.EndsWith(TPath.DirectorySeparatorChar), 'CheckTrue::EndsWith(TPath.DirectorySeparatorChar)<no trailing path delim>'); ReturnValue := TPath.IncludeTrailingPathDelimiter(STR_PATH + TPath.DirectorySeparatorChar); CheckTrue(ReturnValue.EndsWith(TPath.DirectorySeparatorChar), 'CheckTrue::EndsWith(TPath.DirectorySeparatorChar)<trailing path delim>'); CheckFalse(ReturnValue.EndsWith(TPath.DirectorySeparatorChar + TPath.DirectorySeparatorChar), 'CheckFalse::EndsWith(TPath.DirectorySeparatorChar + TPath.DirectorySeparatorChar)'); end; procedure TestTPathHelper.TestIsApplicableFileName; var FileName : TFileName; begin FileName := TPath.GetDirectoryName(ParamStr(0)); CheckFalse(TPath.IsApplicableFileName(FileName), 'CheckFalse::(%s)', [FileName]); FileName := TPath.GetFileName(ParamStr(0)); CheckTrue(TPath.IsApplicableFileName(FileName), 'CheckTrue::(%s)', [FileName]); FileName := ParamStr(0); CheckTrue(TPath.IsApplicableFileName(FileName), 'CheckTrue::(%s)', [FileName]); CheckFalse(TPath.IsApplicableFileName(STR_NON_EXISTENT_DIR), 'CheckFalse::(%s)', [STR_NON_EXISTENT_DIR]); CheckFalse(TPath.IsApplicableFileName(STR_INVALID_FILENAME), 'CheckFalse::(%s)', [STR_INVALID_FILENAME]); end; { TestTRttiTypeHelper } procedure TestTRttiTypeHelper.TestGetFullName; var Ctx : TRttiContext; ReturnValue : String; begin Ctx := TRttiContext.Create; try ReturnValue := Ctx.GetType(Self.ClassType).GetFullName; CheckEquals(Self.QualifiedClassName, ReturnValue, 'ReturnValue = Self.QualifiedClassName'); ReturnValue := Ctx.GetType(TDummyClass).GetFullName; CheckEquals(TDummyClass.ClassName, ReturnValue, 'ReturnValue = TDummyClass.ClassName'); finally Ctx.Free; end; end; procedure TestTRttiTypeHelper.TestGetMethod; var Ctx : TRttiContext; ReturnValue : TRttiMethod; begin Ctx := TRttiContext.Create; try ReturnValue := Ctx.GetType(Self.ClassType).GetMethod(@TestTRttiTypeHelper.TestGetMethod); CheckTrue(Assigned(ReturnValue), 'CheckTrue::Assigned(ReturnValue)'); CheckEquals('TestGetMethod', ReturnValue.Name, 'ReturnValue.Name = TestGetMethod'); finally Ctx.Free; end; end; procedure TestTRttiTypeHelper.TestIsArray; var Ctx : TRttiContext; Prop : TRttiProperty; Attr : TCustomAttribute; begin Ctx := TRttiContext.Create; try for Prop in Ctx.GetType(Self.ClassType).GetDeclaredProperties do for Attr in Prop.GetAttributes do if Attr is IsArrayPropAttribute then begin CheckTrue(Prop.PropertyType.IsArray, 'CheckTrue::<%s is array>', [Prop.Name]); Break; end; finally Ctx.Free; end; end; procedure TestTRttiTypeHelper.TestIsString; var Ctx : TRttiContext; Prop : TRttiProperty; Attr : TCustomAttribute; begin Ctx := TRttiContext.Create; try for Prop in Ctx.GetType(Self.ClassType).GetDeclaredProperties do for Attr in Prop.GetAttributes do if Attr is IsStringPropAttribute then begin CheckTrue(Prop.PropertyType.IsString, 'CheckTrue::<%s is string>', [Prop.Name]); Break; end; finally Ctx.Free; end; end; { TestTTypeInfoHelper } procedure TestTTypeInfoHelper.TestIsArray; type TTestStaticArray = array [0..9] of Byte; TTestDynamicArray = TArray<Byte>; begin CheckTrue(PTypeInfo(TypeInfo(TTestStaticArray)).IsArray, 'CheckTrue::TTestStaticArray'); CheckTrue(PTypeInfo(TypeInfo(TTestDynamicArray)).IsArray, 'CheckTrue::TTestDynamicArray'); end; procedure TestTTypeInfoHelper.TestIsString; begin CheckTrue(PTypeInfo(TypeInfo(String)).IsString, 'CheckTrue::String'); CheckTrue(PTypeInfo(TypeInfo(ShortString)).IsString, 'CheckTrue::ShortString'); CheckTrue(PTypeInfo(TypeInfo(AnsiString)).IsString, 'CheckTrue::AnsiString'); CheckTrue(PTypeInfo(TypeInfo(WideString)).IsString, 'CheckTrue::WideString'); CheckTrue(PTypeInfo(TypeInfo(UnicodeString)).IsString, 'CheckTrue::UnicodeString'); CheckTrue(PTypeInfo(TypeInfo(UTF8String)).IsString, 'CheckTrue::UTF8String'); CheckTrue(PTypeInfo(TypeInfo(RawByteString)).IsString, 'CheckTrue::RawByteString'); end; { TestTTypeKindHelper } procedure TestTTypeKindHelper.TestIsArray; type TTestStaticArray = array [0..9] of Byte; TTestDynamicArray = TArray<Byte>; begin CheckTrue(PTypeInfo(TypeInfo(TTestStaticArray)).Kind.IsArray, 'CheckTrue::TTestStaticArray'); CheckTrue(PTypeInfo(TypeInfo(TTestDynamicArray)).Kind.IsArray, 'CheckTrue::TTestDynamicArray'); end; procedure TestTTypeKindHelper.TestIsString; begin CheckTrue(PTypeInfo(TypeInfo(String)).Kind.IsString, 'CheckTrue::String'); CheckTrue(PTypeInfo(TypeInfo(ShortString)).Kind.IsString, 'CheckTrue::ShortString'); CheckTrue(PTypeInfo(TypeInfo(AnsiString)).Kind.IsString, 'CheckTrue::AnsiString'); CheckTrue(PTypeInfo(TypeInfo(WideString)).Kind.IsString, 'CheckTrue::WideString'); CheckTrue(PTypeInfo(TypeInfo(UnicodeString)).Kind.IsString, 'CheckTrue::UnicodeString'); CheckTrue(PTypeInfo(TypeInfo(UTF8String)).Kind.IsString, 'CheckTrue::UTF8String'); CheckTrue(PTypeInfo(TypeInfo(RawByteString)).Kind.IsString, 'CheckTrue::RawByteString'); end; { TestTVarRecHelper } procedure TestTVarRecHelper.TestToString; const BOOL_TEST = True; INT_TEST = 777; STR_ANSI = AnsiString('AnsiString'); STR_DEFAULT = String('String'); STR_SHORT : String[11] = 'ShortString'; STR_UNICODE = UnicodeString('UnicodeString'); STR_WIDE = WideString('WideString'); type TVarArgProc = reference to procedure (const Args : array of const); var P : TVarArgProc; begin P := procedure (const Args : array of const) begin CheckTrue(Args[0].ToString = BoolToStr(BOOL_TEST), 'Args[0] = BOOL_TEST'); CheckTrue(Args[1].ToString = INT_TEST.ToString, 'Args[1] = INT_TEST'); CheckTrue(Args[2].ToString = STR_ANSI, 'Args[2] = STR_ANSI'); CheckTrue(Args[3].ToString = STR_DEFAULT, 'Args[3] = STR_DEFAULT'); CheckTrue(Args[4].ToString = String(STR_SHORT), 'Args[4] = STR_SHORT'); CheckTrue(Args[5].ToString = STR_UNICODE, 'Args[5] = STR_UNICODE'); CheckTrue(Args[6].ToString = STR_WIDE, 'Args[6] = STR_WIDE'); CheckTrue(Args[7].ToString = sLineBreak, 'Args[7] = sLineBreak'); end; P([BOOL_TEST, INT_TEST, STR_ANSI, STR_DEFAULT, STR_SHORT, STR_UNICODE, STR_WIDE, sLineBreak]); end; initialization // Register any test cases with the test runner RegisterTest(TestFIToolkitCommonsUtils.Suite); RegisterTest(TestTExceptionHelper.Suite); RegisterTest(TestTFileNameHelper.Suite); RegisterTest(TestTPathHelper.Suite); RegisterTest(TestTRttiTypeHelper.Suite); RegisterTest(TestTTypeInfoHelper.Suite); RegisterTest(TestTTypeKindHelper.Suite); RegisterTest(TestTVarRecHelper.Suite); end.
unit loginFrame; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, LCLintf, LCLtype, Base64, Dialogs, constants, httpsend, ssl_openssl, jsonparser, fpjson; type Tlogin = class(TFrame) loginButton: TButton; userEdit: TEdit; passwordEdit: TEdit; Label1: TLabel; Label2: TLabel; procedure loginButtonClick(Sender: TObject); private { private declarations } //httpClient: TFPhttpClient; public { public declarations } urlStem : string; parentHandle: HWND; session_id: string; loginOK: boolean; end; implementation {$R *.lfm} { Tlogin } procedure Tlogin.loginButtonClick(Sender: TObject); var url :string; auth64 :string; httpsend: THTTPSend; jData: TJSONData; jObj: TJSONObject; begin loginOK := false; url := 'http://' + server + ':' + port + '/json/login'; { auth64 := encodeStringBase64(userEdit.Text + ':' + passwordEdit.Text); try httpClient := TFPHttpClient.create(nil); httpClient.addHeader('Authorization','Basic ' + auth64); try httpClient.get(url); if (httpClient.responseStatusCode = 200) then begin loginOK := true; session_id := httpClient.Cookies[0]; end; except on E: Exception do if (httpClient.responseStatusCode = 401) then ShowMessage('Login failed') else ShowMessage(E.message); end; finally httpClient.free; end; if (loginOK) then postMessage(parentHandle, LM_FRAME_MSG, FN_LOGIN, LOGIN_PASS) else postMessage(parentHandle, LM_FRAME_MSG, FN_LOGIN, LOGIN_INVALID); } postMessage(parentHandle, LM_FRAME_MSG, FR_LOGIN, NO_VALUE) end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Buttons; type { TfrmfindName } TfrmfindName = class(TForm) bmbReset: TBitBtn; btnSave: TButton; btnLoad: TButton; btnDelete: TButton; gbpNames: TGroupBox; lblName: TLabel; lblResult: TLabel; dlgOpen: TOpenDialog; dlgSave: TSaveDialog; lstNames: TListBox; procedure bmbResetClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnFindClick(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); private { private declarations } public { public declarations } end; var frmfindName: TfrmfindName; implementation {$R *.lfm} { TfrmfindName } procedure TfrmfindName.btnSaveClick(Sender: TObject); begin if dlgSave.Execute then lstNames.Lines.SaveToFile(dlgSave.FileName) else ShowMessage('Invalid file name'); end; procedure TfrmfindName.btnLoadClick(Sender: TObject); begin if dlgOpen.Execute then lstNames.Lines.LoadFromFile(dlgOpen.FileName) else ShowMessage('Invalid file name'); end; procedure TfrmfindName.bmbResetClick(Sender: TObject); begin lstNames.Clear; lstNames.SetFocus; end; procedure TfrmfindName.btnDeleteClick(Sender: TObject); var NameToDelete: string; LineCount, Index, ListIndex, NumDeleted: integer begin //Get the index of the selected name ListIndex:=lstNames.ItemIndex; //use index to get name, store uppercase form in NameToDelete NameToDelete:=UpperCase(lstNames.Items[ListIndex]); end; end.
unit BodiesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, System.Generics.Collections, DSWrap; type TBodyW = class(TDSWrap) private FBody: TFieldWrap; FID: TFieldWrap; FIDBodyKind: TFieldWrap; public constructor Create(AOwner: TComponent); override; property Body: TFieldWrap read FBody; property ID: TFieldWrap read FID; property IDBodyKind: TFieldWrap read FIDBodyKind; end; TQueryBodies = class(TQueryBase) FDUpdateSQL: TFDUpdateSQL; private FW: TBodyW; { Private declarations } protected public constructor Create(AOwner: TComponent); override; procedure LocateOrAppend(const ABody: string; AIDBodyKind: Integer); property W: TBodyW read FW; { Public declarations } end; implementation {$R *.dfm} uses StrHelper; constructor TQueryBodies.Create(AOwner: TComponent); begin inherited; FW := TBodyW.Create(FDQuery); end; procedure TQueryBodies.LocateOrAppend(const ABody: string; AIDBodyKind: Integer); var AFieldNames: string; begin Assert(not ABody.IsEmpty); Assert(AIDBodyKind > 0); AFieldNames := Format('%s;%s', [W.IDBodyKind.FieldName, W.Body.FieldName]); if not FDQuery.LocateEx(AFieldNames, VarArrayOf([AIDBodyKind, ABody]), [lxoCaseInsensitive]) then begin W.TryAppend; W.Body.F.Value := ABody; W.IDBodyKind.F.Value := AIDBodyKind; W.TryPost; end; end; constructor TBodyW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FBody := TFieldWrap.Create(Self, 'Body'); FIDBodyKind := TFieldWrap.Create(Self, 'IDBodyKind'); end; end.
unit ASDOpenGL; {<|Модуль библиотеки ASDEngine|>} {<|Дата создания 31.05.07|>} {<|Автор Adler3D|>} {<|e-mail : Adler3D@Mail.ru|>} {<|Дата последнего изменения 31.05.07|>} interface uses Windows, OpenGL, ASDUtils, ASDInterface, ASDType, ASDLog, ASDClasses; type PFontData = ^TFontData; TFontData = record Font: ITexImage; List: Cardinal; Size: Cardinal; Width: array[0..255] of ShortInt; end; GLHandleARB = Integer; TOpenGL = class(TASDObject, IOpenGL) private FNPS: TCalcNPS; public constructor CreateEx; override; destructor Destroy; override; procedure UnLoad; override; public function FPS: Integer; procedure VSync(Active: Boolean); overload; function VSync: Boolean; overload; procedure Clear(Color, Depth, Stencil: Boolean); procedure Swap; procedure AntiAliasing(Samples: Integer); overload; function AntiAliasing: Integer; overload; procedure Set2D(x, y, w, h: Single); procedure Set3D(FOV, zNear, zFar: Single); procedure LightDef(ID: Integer); procedure LightPos(ID: Integer; X, Y, Z: Single); procedure LightColor(ID: Integer; R, G, B: Single); function FontCreate(Name: PChar; Size: Integer): TFont; procedure FontFree(Font: TFont); procedure TextOut(Font: TFont; X, Y: Real; Text: PChar); function TextLen(Font: TFont; Text: PChar): Integer; function FontHeigth(Font: TFont): Integer; procedure Blend(BType: TBlendType); function ScreenShot(FileName: PChar): Boolean; public DC: HDC; // Device Context RC: HGLRC; // OpenGL Rendering Context fnt_debug: Integer; // fps - frames per second AASamples: Integer; AAFormat: Integer; g_vsync: Boolean; Fonts: array of PFontData; extension: string; // Строка содержит в себе все доступные OpenGL расширения procedure AddLog(Text: string); procedure GetPixelFormat; function Init: Boolean; procedure ReadExtensions; end; // Процедурки и константы отсутствующие в стандартном OpenGL.pas const // Textures GL_MAX_TEXTURE_UNITS_ARB = $84E2; GL_MAX_TEXTURE_SIZE = $0D33; GL_CLAMP_TO_EDGE = $812F; GL_RGB8 = $8051; GL_RGBA8 = $8058; GL_BGR = $80E0; GL_BGRA = $80E1; GL_TEXTURE0_ARB = $84C0; GL_TEXTURE1_ARB = $84C1; GL_TEXTURE_MAX_ANISOTROPY_EXT = $84FE; GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = $84FF; // AA WGL_SAMPLE_BUFFERS_ARB = $2041; // Symbolickй konstanty pro multisampling WGL_SAMPLES_ARB = $2042; WGL_DRAW_TO_WINDOW_ARB = $2001; WGL_SUPPORT_OPENGL_ARB = $2010; WGL_DOUBLE_BUFFER_ARB = $2011; // FBO GL_FRAMEBUFFER_EXT = $8D40; GL_RENDERBUFFER_EXT = $8D41; GL_DEPTH_COMPONENT24_ARB = $81A6; GL_COLOR_ATTACHMENT0_EXT = $8CE0; GL_DEPTH_ATTACHMENT_EXT = $8D00; GL_FRAMEBUFFER_BINDING_EXT = $8CA6; GL_FRAMEBUFFER_COMPLETE_EXT = $8CD5; // Shaders GL_VERTEX_SHADER_ARB = $8B31; GL_FRAGMENT_SHADER_ARB = $8B30; GL_OBJECT_COMPILE_STATUS_ARB = $8B81; GL_OBJECT_LINK_STATUS_ARB = $8B82; // VBO GL_ARRAY_BUFFER_ARB = $8892; GL_ELEMENT_ARRAY_BUFFER_ARB = $8893; GL_STATIC_DRAW_ARB = $88E4; GL_NORMAL_ARRAY = $8075; GL_COLOR_ARRAY = $8076; GL_VERTEX_ARRAY = $8074; GL_TEXTURE_COORD_ARRAY = $8078; procedure glGenTextures(n: GLsizei; textures: PGLuint); stdcall; external opengl32; procedure glBindTexture(target: GLenum; texture: GLuint); stdcall; external opengl32; procedure glDeleteTextures(N: GLsizei; Textures: PGLuint); stdcall; external opengl32; function glIsTexture(texture: GLuint): GLboolean; stdcall; external opengl32; procedure glCopyTexImage2D(target: GLEnum; level: GLint; internalFormat: GLEnum; x, y: GLint; width, height: GLsizei; border: GLint); stdcall; external opengl32; var // VSync WGL_EXT_swap_control: Boolean; wglSwapIntervalEXT: function(interval: GLint): Boolean; stdcall; wglGetSwapIntervalEXT: function: GLint; stdcall; // MultiTexture GL_ARB_multitexture: Boolean; glActiveTextureARB: procedure(texture: GLenum); stdcall; glClientActiveTextureARB: procedure(texture: Cardinal); stdcall; // FrameBuffer GL_EXT_framebuffer_object: Boolean; glGenRenderbuffersEXT: procedure(n: GLsizei; renderbuffers: PGLuint); stdcall; glDeleteRenderbuffersEXT: procedure(n: GLsizei; const renderbuffers: PGLuint); stdcall; glBindRenderbufferEXT: procedure(target: GLenum; renderbuffer: GLuint); stdcall; glRenderbufferStorageEXT: procedure(target: GLenum; internalformat: GLenum; width: GLsizei; height: GLsizei); stdcall; glGenFramebuffersEXT: procedure(n: GLsizei; framebuffers: PGLuint); stdcall; glDeleteFramebuffersEXT: procedure(n: GLsizei; const framebuffers: PGLuint); stdcall; glBindFramebufferEXT: procedure(target: GLenum; framebuffer: GLuint); stdcall; glFramebufferTexture2DEXT: procedure(target: GLenum; attachment: GLenum; textarget: GLenum; texture: GLuint; level: GLint); stdcall; glFramebufferRenderbufferEXT: procedure(target: GLenum; attachment: GLenum; renderbuffertarget: GLenum; renderbuffer: GLuint); stdcall; glCheckFramebufferStatusEXT: function(target: GLenum): GLenum; stdcall; // Shaders GL_ARB_shading_language: Boolean; glDeleteObjectARB: procedure(Obj: GLHandleARB); stdcall; glCreateProgramObjectARB: function: GLHandleARB; stdcall; glCreateShaderObjectARB: function(shaderType: GLEnum): GLHandleARB; stdcall; glShaderSourceARB: procedure(shaderObj: GLHandleARB; count: GLSizei; src: Pointer; len: Pointer); stdcall; glAttachObjectARB: procedure(programObj, shaderObj: GLhandleARB); stdcall; glLinkProgramARB: procedure(programObj: GLHandleARB); stdcall; glUseProgramObjectARB: procedure(programObj: GLHandleARB); stdcall; glCompileShaderARB: function(shaderObj: GLHandleARB): GLboolean; stdcall; glGetObjectParameterivARB: procedure(Obj: GLHandleARB; pname: GLEnum; params: PGLuint); stdcall; glGetAttribLocationARB: function(programObj: GLhandleARB; const char: PChar): GLInt; stdcall; glGetUniformLocationARB: function(programObj: GLhandleARB; const char: PChar): GLInt; stdcall; glVertexAttrib1fARB: procedure(index: GLuint; x: GLfloat); stdcall; glVertexAttrib2fARB: procedure(index: GLuint; x, y: GLfloat); stdcall; glVertexAttrib3fARB: procedure(index: GLuint; x, y, z: GLfloat); stdcall; glUniform1fARB: procedure(location: GLint; v0: GLfloat); stdcall; glUniform2fARB: procedure(location: GLint; v0, v1: GLfloat); stdcall; glUniform3fARB: procedure(location: GLint; v0, v1, v2: GLfloat); stdcall; glUniform4fARB: procedure(location: GLint; v0, v1, v2, v3: GLfloat); stdcall; glUniform1iARB: procedure(location: GLint; v0: GLint); stdcall; // Vertex Buffer Object GL_ARB_vertex_buffer_object: Boolean; glBindBufferARB: procedure(target: GLenum; buffer: GLenum); stdcall; glDeleteBuffersARB: procedure(n: GLsizei; const buffers: PGLuint); stdcall; glGenBuffersARB: procedure(n: GLsizei; buffers: PGLuint); stdcall; glBufferDataARB: procedure(target: GLenum; size: GLsizei; const data: PGLuint; usage: GLenum); stdcall; glBufferSubDataARB: procedure(target: GLenum; offset: GLsizei; size: GLsizei; const data: PGLuint); stdcall; procedure glNormalPointer(type_: GLenum; stride: Integer; const P: PGLuint); stdcall; external opengl32; procedure glColorPointer(size: Integer; _type: GLenum; stride: Integer; const _pointer: PGLuint); stdcall; external opengl32; procedure glVertexPointer(size: Integer; _type: GLenum; stride: Integer; const _pointer: PGLuint); stdcall; external opengl32; procedure glTexCoordPointer(size: Integer; _type: GLenum; stride: Integer; const _pointer: PGLuint); stdcall; external opengl32; procedure glInterleavedArrays(format: GLenum; stride: GLsizei; const _pointer: PGLuint); stdcall; external opengl32; procedure glEnableClientState(_array: GLenum); stdcall; external opengl32; procedure glDisableClientState(_array: GLenum); stdcall; external opengl32; procedure glDrawElements(mode: GLenum; count: GLsizei; _type: GLenum; const indices: PGLuint); stdcall; external opengl32; var GL_max_Aniso: Integer; implementation uses ASDEng; constructor TOpenGL.CreateEx; begin inherited CreateEx; g_vsync := False; FNPS := TCalcNPS.CreateEx(1000); FNPS.Mode := cmAccum; end; destructor TOpenGL.Destroy; var I: Integer; begin for i := 0 to Length(Fonts) - 1 do FontFree(i); if (DC <> 0) and (RC <> 0) then begin if RC <> 0 then wglDeleteContext(RC); if DC <> 0 then ReleaseDC(Window.Handle, DC); end; inherited; end; function TOpenGL.FPS: Integer; begin Result := Round(FNPS.NPS); end; procedure TOpenGL.VSync(Active: Boolean); begin g_vsync := Active; end; function TOpenGL.VSync: Boolean; begin Result := g_vsync; end; procedure TOpenGL.Clear(Color, Depth, Stencil: Boolean); var flag: DWORD; begin flag := 0; if Color then flag := flag or GL_COLOR_BUFFER_BIT; if Depth then flag := flag or GL_DEPTH_BUFFER_BIT; if Stencil then flag := flag or GL_STENCIL_BUFFER_BIT; glClear(flag); end; procedure TOpenGL.Swap; begin if WGL_EXT_swap_control and (wglGetSwapIntervalEXT <> Byte(g_vsync)) then wglSwapIntervalEXT(Byte(g_vsync)); glFlush; SwapBuffers(DC); FNPS.Next; end; procedure TOpenGL.AntiAliasing(Samples: Integer); begin if not Window.Ready then AASamples := Samples; end; function TOpenGL.AntiAliasing: Integer; begin Result := AASamples end; procedure TOpenGL.Set2D(x, y, w, h: Single); begin glMatrixMode(GL_PROJECTION); glLoadIdentity; glOrtho(x, x + w, y + h, y, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity; end; procedure TOpenGL.Set3D(FOV, zNear, zFar: Single); begin glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(FOV, Window.Width / Window.Height, zNear, zFar); glMatrixMode(GL_MODELVIEW); glLoadIdentity; end; procedure TOpenGL.LightDef(ID: Integer); const light_position: array[0..3] of single = (1, 1, 1, 0); white_light: array[0..3] of single = (1, 1, 1, 1); begin glLightfv(ID, GL_POSITION, @light_position); glLightfv(ID, GL_DIFFUSE, @white_light); glLightfv(ID, GL_SPECULAR, @white_light); end; procedure TOpenGL.LightPos(ID: Integer; X, Y, Z: Single); var p: array[0..3] of Single; begin p[0] := X; p[1] := Y; p[2] := Z; p[3] := 1; glLightfv(ID, GL_POSITION, @p); end; procedure TOpenGL.LightColor(ID: Integer; R, G, B: Single); var c: array[0..3] of Single; begin c[0] := R; c[1] := G; c[2] := B; c[3] := 1; glLightfv(ID, GL_DIFFUSE, @c); glLightfv(ID, GL_SPECULAR, @c); end; function TOpenGL.FontCreate(Name: PChar; Size: Integer): TFont; const TEX_SIZE = 512; var FNT: HFONT; DC: HDC; MDC: HDC; BMP: HBITMAP; BI: BITMAPINFO; pix: PByteArray; i: Integer; cs: TSize; s, t: Single; Data: PByteArray; begin DC := GetDC(Window.Handle); FNT := CreateFont(-MulDiv(Size, GetDeviceCaps(DC, LOGPIXELSY), 72), 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, 0, Name); ZeroMemory(@BI, SizeOf(BI)); with BI.bmiHeader do begin biSize := SizeOf(BITMAPINFOHEADER); biWidth := TEX_SIZE; biHeight := TEX_SIZE; biPlanes := 1; biBitCount := 24; biSizeImage := biWidth * biHeight * biBitCount div 8; end; MDC := CreateCompatibleDC(DC); BMP := CreateDIBSection(MDC, BI, DIB_RGB_COLORS, Pointer(pix), 0, 0); ZeroMemory(pix, TEX_SIZE * TEX_SIZE * 3); SelectObject(MDC, BMP); SelectObject(MDC, FNT); SetBkMode(MDC, TRANSPARENT); SetTextColor(MDC, $FFFFFF); for i := 0 to 255 do Windows.TextOut(MDC, i mod 16 * (TEX_SIZE div 16), i div 16 * (TEX_SIZE div 16), @Char(i), 1); Result := HIGH(TFont); for i := 0 to Length(Fonts) - 1 do if Fonts[i] = nil then begin Result := i; break; end; if Result = HIGH(TFont) then begin Result := Length(Fonts); SetLength(Fonts, Result + 1); end; New(Fonts[Result]); with Fonts[Result]^ do begin GetMem(Data, TEX_SIZE * TEX_SIZE * 2); for i := 0 to TEX_SIZE * TEX_SIZE - 1 do begin Data[i * 2] := 255; Data[i * 2 + 1] := pix[i * 3]; end; Font := Texture.NewTex(PChar('*Font_' + Name + '_' + IntToStr(Result) + '*'), Data, 2, GL_LUMINANCE_ALPHA, TEX_SIZE, TEX_SIZE, 0, True, False); FreeMem(Data); List := glGenLists(256); for i := 0 to 255 do begin glNewList(List + Cardinal(i), GL_COMPILE); s := (i mod 16) / 16; t := (i div 16) / 16; GetTextExtentPoint32(MDC, @Char(i), 1, cs); Width[i] := cs.cx; glBegin(GL_QUADS); glTexCoord2f(s, 1 - t); glVertex2f(0, 0); glTexCoord2f(s + cs.cx / 512, 1 - t); glVertex2f(cs.cx, 0); glTexCoord2f(s + cs.cx / 512, 1 - t - cs.cy / 512); glVertex2f(cs.cx, cs.cy); glTexCoord2f(s, 1 - t - cs.cy / 512); glVertex2f(0, cs.cy); glEnd; glTranslatef(cs.cx, 0, 0); glEndList; end; end; Fonts[Result].Size := Size; DeleteObject(FNT); DeleteObject(BMP); DeleteDC(MDC); ReleaseDC(Window.Handle, DC); end; procedure TOpenGL.FontFree(Font: TFont); begin if (Font >= Cardinal(Length(Fonts))) or (Fonts[Font] = nil) then Exit; Texture.Delete(Fonts[Font]^.Font); Fonts[Font]^.Font.UnLoad; glDeleteLists(Fonts[Font]^.List, 256); Dispose(Fonts[Font]); Fonts[Font] := nil; end; procedure TOpenGL.TextOut(Font: TFont; X, Y: Real; Text: PChar); var str: string; i: Integer; begin if (Font >= Cardinal(Length(Fonts))) or (Fonts[Font] = nil) then Exit; glPushAttrib(GL_ENABLE_BIT); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_LIGHTING); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GEQUAL, 0.1); Blend(BT_SUB); glListBase(Fonts[Font]^.List); Fonts[Font]^.Font.Enable; glPushMatrix; glTranslatef(X, Y, 0); str := Text; for i := 1 to Length(str) do glCallLists(1, GL_UNSIGNED_BYTE, @str[i]); glPopMatrix; glPopAttrib; end; procedure TOpenGL.Blend(BType: TBlendType); begin if BType = BT_NONE then glDisable(GL_BLEND) else begin glEnable(GL_BLEND); case BType of // обычное смешивание BT_SUB: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // сложение BT_ADD: glBlendFunc(GL_SRC_ALPHA, GL_ONE); // умножение BT_MULT: glBlendFunc(GL_ZERO, GL_SRC_COLOR); end; end; end; function TOpenGL.ScreenShot(FileName: PChar): Boolean; var F: HFile; pix: Pointer; TGA: packed record FileType: Byte; ColorMapType: Byte; ImageType: Byte; ColorMapStart: Word; ColorMapLength: Word; ColorMapDepth: Byte; OrigX: Word; OrigY: Word; iWidth: Word; iHeight: Word; iBPP: Byte; ImageInfo: Byte; end; BMP: packed record bfType: Word; bfSize: DWORD; bfReserved1: Word; bfReserved2: Word; bfOffBits: DWORD; biSize: DWORD; biWidth: Integer; biHeight: Integer; biPlanes: Word; biBitCount: Word; biCompression: DWORD; biSizeImage: DWORD; biXPelsPerMeter: Integer; biYPelsPerMeter: Integer; biClrUsed: DWORD; biClrImportant: DWORD; end; begin Result := False; GetMem(pix, Window.Width * Window.Height * 3); glReadPixels(0, 0, Window.Width, Window.Height, GL_BGR, GL_UNSIGNED_BYTE, pix); F := FileCreate(FileName); if not FileValid(F) then Exit; if Copy(FileName, Length(FileName) - 2, 3) = 'tga' then with TGA, Window do begin FileType := 0; ColorMapType := 0; ImageType := 2; ColorMapStart := 0; ColorMapLength := 0; ColorMapDepth := 0; OrigX := 0; OrigY := 0; iWidth := Width; iHeight := Height; iBPP := 24; ImageInfo := 0; FileWrite(F, TGA, SizeOf(TGA)); end else with BMP, Window do begin bfType := $4D42; bfSize := Width * Height * 3 + SizeOf(BMP); bfReserved1 := 0; bfReserved2 := 0; bfOffBits := SizeOf(BMP); biSize := SizeOf(BITMAPINFOHEADER); biWidth := Width; biHeight := Height; biPlanes := 1; biBitCount := 24; biCompression := 0; biSizeImage := Width * Height * 3; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; FileWrite(F, BMP, SizeOf(BMP)); end; FileWrite(F, pix^, Window.Width * Window.Height * 3); FileClose(F); FreeMem(pix); Result := True; end; procedure TOpenGL.AddLog(Text: string); begin Log.Print(Self, PChar(Text)); end; procedure TOpenGL.GetPixelFormat; var wglChoosePixelFormatARB: function(hdc: HDC; const piAttribIList: PGLint; const pfAttribFList: PGLfloat; nMaxFormats: GLuint; piFormats: PGLint; nNumFormats: PGLuint): BOOL; stdcall; fAttributes: array[0..1] of Single; iAttributes: array[0..11] of Integer; pfd: PIXELFORMATDESCRIPTOR; DC: Cardinal; hwnd: Cardinal; wnd: TWndClassEx; function GetFormat: Boolean; var Format: Integer; numFormats: Cardinal; begin iAttributes[7] := AASamples; if wglChoosePixelFormatARB(GetDC(hWnd), @iattributes, @fattributes, 1, @Format, @numFormats) and (numFormats >= 1) then begin AAFormat := Format; Result := True; end else begin dec(AASamples); Result := False; end; end; label ext; begin if AASamples = 0 then Exit; ZeroMemory(@wnd, SizeOf(wnd)); with wnd do begin cbSize := SizeOf(wnd); lpfnWndProc := @DefWindowProc; hCursor := LoadCursor(0, IDC_ARROW); lpszClassName := 'eXAAtest'; end; if RegisterClassEx(wnd) = 0 then Exit; hwnd := CreateWindow('eXAAtest', nil, WS_POPUP, 0, 0, 0, 0, 0, 0, 0, nil); DC := GetDC(hwnd); if DC = 0 then goto ext; FillChar(pfd, SizeOf(pfd), 0); with pfd do begin nSize := SizeOf(TPIXELFORMATDESCRIPTOR); nVersion := 1; dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType := PFD_TYPE_RGBA; cColorBits := 32; cDepthBits := 24; cStencilBits := 8; iLayerType := PFD_MAIN_PLANE; end; if not SetPixelFormat(DC, ChoosePixelFormat(DC, @pfd), @pfd) then goto ext; if not wglMakeCurrent(DC, wglCreateContext(DC)) then goto ext; fAttributes[0] := 0; fAttributes[1] := 0; iAttributes[0] := WGL_DRAW_TO_WINDOW_ARB; iAttributes[1] := 1; iAttributes[2] := WGL_SUPPORT_OPENGL_ARB; iAttributes[3] := 1; iAttributes[4] := WGL_SAMPLE_BUFFERS_ARB; iAttributes[5] := 1; iAttributes[6] := WGL_SAMPLES_ARB; iAttributes[8] := WGL_DOUBLE_BUFFER_ARB; iAttributes[9] := 1; iAttributes[10] := 0; iAttributes[11] := 0; wglChoosePixelFormatARB := wglGetProcAddress('wglChoosePixelFormatARB'); if @wglChoosePixelFormatARB = nil then Exit; while (AASamples > 0) and (not GetFormat) do ; // смертельный номер! ext: ReleaseDC(hwnd, DC); DestroyWindow(hwnd); UnRegisterClass('eXAAtest', 0); end; function TOpenGL.Init: Boolean; var pfd: PIXELFORMATDESCRIPTOR; iFormat: Integer; begin Result := False; AddLog('init graphics core'); DC := GetDC(Window.Handle); if DC = 0 then begin AddLog('Fatal Error "GetDC"'); Exit; end; FillChar(pfd, SizeOf(pfd), 0); with pfd do begin nSize := SizeOf(TPIXELFORMATDESCRIPTOR); nVersion := 1; dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; iPixelType := PFD_TYPE_RGBA; cColorBits := 32; cDepthBits := 24; cStencilBits := 8; iLayerType := PFD_MAIN_PLANE; end; if AAFormat > 0 then iFormat := AAFormat else iFormat := ChoosePixelFormat(DC, @pfd); if iFormat = 0 then begin AddLog('Fatal Error "ChoosePixelFormat"'); Exit; end; if not SetPixelFormat(DC, iFormat, @pfd) then begin AddLog('Fatal Error "SetPixelFormat"'); Exit; end; RC := wglCreateContext(DC); if RC = 0 then begin AddLog('Fatal Error "wglCreateContext"'); Exit; end; if not wglMakeCurrent(DC, RC) then begin AddLog('Fatal Error "wglCreateContext"'); Exit; end; // Инициализация доступных расширений ReadExtensions; // Настройка glDepthFunc(GL_LESS); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glClearColor(0, 0, 0, 0); glEnable(GL_COLOR_MATERIAL); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0); glViewport(0, 0, Window.Width, Window.Height); // Создание default текстуры и т.п. if not Texture.Init then Exit; // Создание Debug шрифта fnt_debug := FontCreate('FixedSys', 8); // Готово Result := True; end; procedure TOpenGL.ReadExtensions; var i: Integer; begin // Получаем адреса дополнительных процедур OpenGL AddLog('GL_VENDOR : ' + glGetString(GL_VENDOR)); AddLog('GL_RENDERER : ' + glGetString(GL_RENDERER)); AddLog('GL_VERSION : ' + glGetString(GL_VERSION)); glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, @i); AddLog('MAX_TEX_UNITS : ' + IntToStr(i)); glGetIntegerv(GL_MAX_TEXTURE_SIZE, @i); AddLog('MAX_TEX_SIZE : ' + IntToStr(i)); glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, @GL_max_aniso); AddLog('MAX_ANISOTROPY : ' + IntToStr(GL_max_aniso)); AddLog('USE_AA_SAMPLES : ' + IntToStr(AASamples)); AddLog('Reading extensions'); extension := glGetString(GL_EXTENSIONS); // Итак, нормальные люди (не извращенцы) которым // глубоко плевать на скорость запуска их приложений (игр) // производят поиск расширений стандартным методом // через строку GL_EXTENSIONS // Этот метод может съесть до нескольких секунд (проверено) // Эту "ерунду" я не смог пропусть, и сделал своё чёрное дело... // пробуем получить адрес процедуры принадлежащей нужному нам расширению // в случае успеха (<> nil) расширение существует и наоборот... // 1439 мс VS 229 мс на проверке 4 расширений :) // Управление вертикальной синхронизацией wglSwapIntervalEXT := wglGetProcAddress('wglSwapIntervalEXT'); if @wglSwapIntervalEXT <> nil then begin AddLog('- WGL_EXT_swap_control'#9#9': Ok'); WGL_EXT_swap_control := True; wglGetSwapIntervalEXT := wglGetProcAddress('wglGetSwapIntervalEXT'); end else AddLog('- WGL_EXT_swap_control'#9#9': Fail'); // Мультитекстурирование glActiveTextureARB := wglGetProcAddress('glActiveTextureARB'); if @glActiveTextureARB <> nil then begin AddLog('- GL_ARB_multitexture'#9#9': Ok'); GL_ARB_multitexture := True; glClientActiveTextureARB := wglGetProcAddress('glClientActiveTextureARB'); end else AddLog('- GL_ARB_multitexture'#9#9': Fail'); // рендер в текстуру glGenRenderbuffersEXT := wglGetProcAddress('glGenRenderbuffersEXT'); if @glGenRenderbuffersEXT <> nil then begin AddLog('- GL_EXT_framebuffer_object'#9#9': Ok'); GL_EXT_framebuffer_object := True; glDeleteRenderbuffersEXT := wglGetProcAddress('glDeleteRenderbuffersEXT'); glBindRenderbufferEXT := wglGetProcAddress('glBindRenderbufferEXT'); glRenderbufferStorageEXT := wglGetProcAddress('glRenderbufferStorageEXT'); glGenFramebuffersEXT := wglGetProcAddress('glGenFramebuffersEXT'); glDeleteFramebuffersEXT := wglGetProcAddress('glDeleteFramebuffersEXT'); glBindFramebufferEXT := wglGetProcAddress('glBindFramebufferEXT'); glFramebufferTexture2DEXT := wglGetProcAddress('glFramebufferTexture2DEXT'); glFramebufferRenderbufferEXT := wglGetProcAddress('glFramebufferRenderbufferEXT'); glCheckFramebufferStatusEXT := wglGetProcAddress('glCheckFramebufferStatusEXT'); end else AddLog('- GL_EXT_framebuffer_object'#9#9': Fail'); // шейдеры glDeleteObjectARB := wglGetProcAddress('glDeleteObjectARB'); if @glDeleteObjectARB <> nil then begin AddLog('- GL_ARB_shading_language'#9#9': Ok'); GL_ARB_shading_language := True; glCreateProgramObjectARB := wglGetProcAddress('glCreateProgramObjectARB'); glCreateShaderObjectARB := wglGetProcAddress('glCreateShaderObjectARB'); glShaderSourceARB := wglGetProcAddress('glShaderSourceARB'); glAttachObjectARB := wglGetProcAddress('glAttachObjectARB'); glLinkProgramARB := wglGetProcAddress('glLinkProgramARB'); glUseProgramObjectARB := wglGetProcAddress('glUseProgramObjectARB'); glCompileShaderARB := wglGetProcAddress('glCompileShaderARB'); glGetObjectParameterivARB := wglGetProcAddress('glGetObjectParameterivARB'); glGetAttribLocationARB := wglGetProcAddress('glGetAttribLocationARB'); glGetUniformLocationARB := wglGetProcAddress('glGetUniformLocationARB'); // attribs glVertexAttrib1fARB := wglGetProcAddress('glVertexAttrib1fARB'); glVertexAttrib2fARB := wglGetProcAddress('glVertexAttrib2fARB'); glVertexAttrib3fARB := wglGetProcAddress('glVertexAttrib3fARB'); // uniforms glUniform1fARB := wglGetProcAddress('glUniform1fARB'); glUniform2fARB := wglGetProcAddress('glUniform2fARB'); glUniform3fARB := wglGetProcAddress('glUniform3fARB'); glUniform1iARB := wglGetProcAddress('glUniform1iARB'); end else AddLog('- GL_ARB_shading_language'#9#9': Fail'); // VBO :) glBindBufferARB := wglGetProcAddress('glBindBufferARB'); if @glBindBufferARB <> nil then begin AddLog('- GL_ARB_vertex_buffer_object'#9': Ok'); GL_ARB_vertex_buffer_object := True; glBindBufferARB := wglGetProcAddress('glBindBufferARB'); glDeleteBuffersARB := wglGetProcAddress('glDeleteBuffersARB'); glGenBuffersARB := wglGetProcAddress('glGenBuffersARB'); glBufferDataARB := wglGetProcAddress('glBufferDataARB'); glBufferSubDataARB := wglGetProcAddress('glBufferSubDataARB'); end else AddLog('- GL_ARB_vertex_buffer_object'#9': Fail'); end; procedure TOpenGL.UnLoad; begin FNPS.UnLoad; FontFree(fnt_debug); //== Высвобождение ресурсов if (DC <> 0) and (RC <> 0) then begin // Удаляем OpenGL контекст if RC <> 0 then wglDeleteContext(RC); // Удаляем графический контекст окна if DC <> 0 then ReleaseDC(Window.Handle, DC); end; inherited; end; function TOpenGL.FontHeigth(Font: TFont): Integer; begin Result := Fonts[Font]^.Size * 2; end; function TOpenGL.TextLen(Font: TFont; Text: PChar): Integer; var str: string; i: Integer; begin Result := 0; if (Font >= Cardinal(Length(Fonts))) or (Fonts[Font] = nil) then Exit; str := Text; for i := 1 to Length(Text) do Result := Result + Fonts[Font]^.Width[Byte(str[i])]; end; end.
unit FindFile; // FindFile version 1.0.1 // // Copyright (C) September 1997 Walter Dorawa // // Everyone is free to use this code as they wish, but // if you use it commercially then I wouldn't mind a // little something. // // Please submit suggestions, bugs, or any improvements to // walterd@gte.net // // Improvements: 10-21-97 // Attributes property TotalFile // Abort property TotalSpace // OnNewPath event TotalDir // // thanks to: Howard Harvey, Jim Keatley and Dale Derix // for suggestions and code improvements // interface uses Classes, SysUtils, Dialogs; type TAttrOption = (ffReadOnly, ffHidden, ffSystem, ffVolumeID, ffDirectory, ffArchive); TAttrOptions = set of TAttrOption; TNewPathEvent = procedure(Sender: TObject; NewPath: string; var Abort: boolean) of object; TFindFile = class(TComponent) private { Private declarations } FAbort:boolean; FTotalSpace:longint; FTotalDir:longint; FTotalFile:longint; FAttribs:TAttrOptions; FDirectory:string; FRecurse:boolean; FFilter :string; FFiles: TStrings; FBeforeExecute: TNotifyEvent; FAfterExecute: TNotifyEvent; FOnNewPath: TNewPathEvent; procedure SearchCurrentDirectory(Directory:string); procedure SearchRecursive(Directory:string); function FindSubDirectory(strDirs:TStringList; Directory:string):Boolean; protected { Protected declarations } procedure SetFiles(Value: TStrings); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Execute; dynamic; property TotalSpace: longint read FTotalSpace write FTotalSpace; property TotalDir: longint read FTotalDir write FTotalDir; property TotalFile: longint read FTotalFile write FTotalFile; property Abort: boolean read FAbort write FAbort default False; published { Published declarations } property Recurse: boolean read FRecurse write FRecurse default False; property Directory: string read FDirectory write FDirectory; property Filter: string read FFilter write FFilter; property Files: TStrings read FFiles write SetFiles; property Attributes: TAttrOptions read FAttribs write FAttribs default [ffReadOnly, ffHidden, ffSystem, ffArchive]; property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute; property AfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute; property OnNewPath: TNewPathEvent read FOnNewPath write FOnNewPath; end; procedure Register; //=================================================================================== //=================================================================================== implementation const DefaultFilter = '*.*'; var Attribs:integer; constructor TFindFile.Create(AOwner: TComponent); begin inherited Create(AOwner); FFilter:=DefaultFilter; FAttribs:=[ffReadOnly, ffHidden, ffSystem, ffArchive]; FFiles:=TStringList.Create; end; destructor TFindFile.Destroy; begin FFiles.Free; inherited Destroy; end; procedure TFindFile.SetFiles(Value: TStrings); begin FFiles.Assign(Value); end; procedure TFindFile.Execute; begin Attribs:=0; if ffReadOnly in Attributes then Attribs:=Attribs+faReadOnly; if ffHidden in Attributes then Attribs:=Attribs+faHidden; if ffSystem in Attributes then Attribs:=Attribs+faSysFile; if ffVolumeID in Attributes then Attribs:=Attribs+faVolumeID; if ffDirectory in Attributes then Attribs:=Attribs+faDirectory; if ffArchive in Attributes then Attribs:=Attribs+faArchive; FFiles.Clear; FTotalSpace:=0; FTotalDir:=0; FTotalFile:=0; if Assigned(FBeforeExecute) then FBeforeExecute(Self); if Length(FDirectory)<>0 then if FRecurse then SearchRecursive(FDirectory) else SearchCurrentDirectory(FDirectory); if Assigned(FAfterExecute) then FAfterExecute(Self); end; procedure TFindFile.SearchCurrentDirectory(Directory:string); var i:integer; srchRec:TSearchRec; begin if Directory[Length(Directory)]<>'\' then AppendStr(Directory,'\'); if Assigned(FOnNewPath) then FOnNewPath(Self,Directory,FAbort); if FAbort then Exit; i:=FindFirst(Directory+FFilter,Attribs,srchRec); while i=0 do begin if (srchRec.Name<>'.') and (srchRec.Name<>'..') then begin FFiles.Add(Directory+srchRec.Name); case srchRec.Attr of faDirectory: Inc(FTotalDir); else Inc(FTotalFile); end; FTotalSpace:=FTotalSpace+srchRec.Size; end; i:=FindNext(srchRec); end; FindClose(srchRec); end; procedure TFindFile.SearchRecursive(Directory:string); var strDirs:TStringList; begin strDirs:=TStringList.Create; try if Directory[Length(Directory)]<>'\' then AppendStr(Directory,'\'); strDirs.Clear; strDirs.Add(Directory); while strDirs.Count<>0 do begin FindSubDirectory(strDirs,strDirs.Strings[0]); SearchCurrentDirectory(strDirs.Strings[0]); strDirs.Delete(0); if FAbort then Exit; end; finally strDirs.Free; end; end; function TFindFile.FindSubDirectory(strDirs:TStringList; Directory:string):Boolean; var i:integer; srchRec:TSearchRec; begin Result:=True; if Directory[Length(Directory)]<>'\' then AppendStr(Directory,'\'); i:=FindFirst(Directory+'*.*',faAnyFile,srchRec); while i=0 do begin if ((srchRec.Attr and faDirectory)>0) and (srchRec.Name<>'.') and (srchRec.Name<>'..') then begin strDirs.Add(Directory+srchRec.Name); end; i:=FindNext(srchRec); end; FindClose(srchRec); end; procedure Register; begin RegisterComponents('Samples', [TFindFile]); end; end.
unit SourceLocation; interface uses Classes, SysUtils, StrUtils; type TLocation = record Offset: Integer; EndOffset: Integer; Line: Integer; Column: Integer; end; PLocation = ^TLocation; function DescribeLocation(const Location: TLocation): String; function BeyondLocation(const Location: TLocation): TLocation; implementation function DescribeLocation(const Location: TLocation): String; begin Result := '(:'+IntToStr(Location.Line)+':'+IntToStr(Location.Column)+')['+IntToStr(Location.Offset)+':'+IntToStr(Location.EndOffset)+']'; end; function BeyondLocation(const Location: TLocation): TLocation; begin Result := Location; Inc(Result.Column, Result.EndOffset - Result.Offset); Result.Offset := Result.EndOffset; end; end.
unit Web.HTTPS; interface uses SysUtils, Classes, IdSSLOpenSSL, Web.HTTP; type THTTPSWeb = class(THTTPWeb) private SSLIoHandler: TIdSSLIOHandlerSocketOpenSSL; procedure SetSSLIoHandler; public constructor Create; destructor Destroy; override; function GetToStringList(const PathToGet: String): TStringList; override; function GetToStringStream(const PathToGet: String): TStringStream; override; end; implementation { THTTPWeb } constructor THTTPSWeb.Create; const Timeout = 1500; begin inherited; SSLIoHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); SSLIoHandler.ConnectTimeout := Timeout; SSLIoHandler.ReadTimeout := Timeout; end; destructor THTTPSWeb.Destroy; begin FreeAndNil(SSLIoHandler); inherited; end; procedure THTTPSWeb.SetSSLIoHandler; begin Connector.IOHandler := SSLIoHandler; end; function THTTPSWeb.GetToStringList(const PathToGet: String): TStringList; begin SetSSLIoHandler; result := inherited GetToStringList(PathToGet); end; function THTTPSWeb.GetToStringStream(const PathToGet: String): TStringStream; begin SetSSLIoHandler; result := inherited GetToStringStream(PathToGet); end; end.
unit Finance; interface uses Finance.interfaces; type TFinance = class(TInterfacedObject, iFinance) private FCurrencies : iFinanceCurrencies; FStocks : iFinanceStocks; FTaxes : iFinanceTaxes; FKey : string; public constructor Create; destructor Destroy; override; class function New : iFinance; function Key (value : string) : iFinance; function Get : iFinance; function Currencies : iFinanceCurrencies; function Stocks : iFinanceStocks; function Taxes : iFinanceTaxes; end; implementation uses RESTRequest4D.Request, System.JSON, System.Generics.Collections, Finance.Currencies, Finance.Stocks, Finance.Taxes; { TFinance } constructor TFinance.Create; begin FCurrencies := TFinanceCurrencies.Create(Self); FStocks := TFinanceStocks.Create(Self); FTaxes := TFinanceTaxes.Create(Self); end; function TFinance.Currencies: iFinanceCurrencies; begin Result := FCurrencies; end; destructor TFinance.Destroy; begin inherited; end; function TFinance.Get: iFinance; var Response : IResponse; JSONValue, JSONResult : TJSONObject; begin Result := Self; Response := TRequest.New.BaseURL('https://api.hgbrasil.com/finance' + Fkey) .Accept('application/json') .Get; JsonValue := TJSONObject(Response.JSONValue); JsonResult := JsonValue.pairs[2].JsonValue as TJSONObject; FCurrencies.SetJSON(JsonResult.pairs[0].JsonValue as TJSONObject); FStocks.SetJSON(JsonResult.pairs[1].JsonValue as TJSONObject); FTaxes.SetJSON(JsonResult.pairs[4].JsonValue as TJSONArray) end; function TFinance.Key(value: string): iFinance; begin Result := Self; FKey := '?key=' + value; end; class function TFinance.New: iFinance; begin Result := Self.Create; end; function TFinance.Stocks: iFinanceStocks; begin Result := FStocks; end; function TFinance.Taxes: iFinanceTaxes; begin Result := FTaxes; end; end.
unit Users; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton, Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel, Vcl.ExtCtrls, RzPanel, RzDBEdit, Vcl.DBCtrls, RzDBCmbo, User, LocalUser; type TfrmUsers = class(TfrmBaseGridDetail) Label2: TLabel; edUsername: TRzDBEdit; Label3: TLabel; edPassword: TRzDBEdit; urlRoles: TRzURLLabel; edCreditLimit: TRzDBNumericEdit; Label4: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure urlRolesClick(Sender: TObject); procedure grListDblClick(Sender: TObject); private { Private declarations } LUser: TLocalUser; procedure ShowAssignedRoles; procedure SaveRoles; protected procedure SearchList; override; procedure BindToObject; override; function EntryIsValid: boolean; override; function NewIsAllowed: boolean; override; function EditIsAllowed: boolean; override; public { Public declarations } end; implementation {$R *.dfm} uses SecurityData, IFinanceDialogs, IFinanceGlobal, Right, AssignRoles, Role; { TfrmUsers } procedure TfrmUsers.BindToObject; begin inherited; LUser.Name := grList.DataSource.DataSet.FieldByName('employee_name').AsString; LUser.UserId := grList.DataSource.DataSet.FieldByName('id_num').AsString; LUser.Passkey := edPassword.Text; end; function TfrmUsers.EditIsAllowed: boolean; begin Result := ifn.User.HasRights([PRIV_SEC_USER_MODIFY],false); end; function TfrmUsers.EntryIsValid: boolean; var error: string; begin if not LUser.HasName then error := 'Please enter username.' else if not LUser.HasPasskey then error := 'Please enter password.'; Result := error = ''; if not Result then ShowErrorBox(error); end; procedure TfrmUsers.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; LUser.Free; end; procedure TfrmUsers.FormCreate(Sender: TObject); begin LUser := TLocalUser.Create; inherited; end; procedure TfrmUsers.grListDblClick(Sender: TObject); begin inherited; ShowAssignedRoles; end; function TfrmUsers.NewIsAllowed: boolean; begin // Result := ifn.User.HasRight(Z9ADD_USER9Add_new_user_login); Result := false; end; procedure TfrmUsers.SaveRoles; var LRole: TRole; sql: string; i, cnt: integer; begin try try cnt := LUser.RolesCount - 1; for i := 0 to cnt do begin LRole := LUser.Roles[i]; if LRole.Modified then begin if LRole.AssignedNewValue then sql := 'INSERT INTO SYSUSERROLE VALUES (' + QuotedStr(LRole.Code) + ',' + QuotedStr(LUser.UserId) + ');' else sql := 'DELETE FROM SYSUSERROLE WHERE ROLE_CODE = ' + QuotedStr(LRole.Code) + ' AND ID_NUM = ' + QuotedStr(LUser.UserId) + ';'; // execute the sql dmSecurity.dstRoles.Connection.Execute(sql); end; end; // end for except on E: Exception do ShowErrorBox(E.Message); end; finally end; end; procedure TfrmUsers.SearchList; var filterStr: string; begin filterStr := 'EMPLOYEE_NAME LIKE ' + QuotedStr('%' + UpperCase(edSearchKey.Text) + '%'); grList.DataSource.DataSet.Filter := filterStr; end; procedure TfrmUsers.ShowAssignedRoles; begin BindToObject; with TfrmAssignRoles.Create(self.Parent,LUser) do begin try ShowModal; if ModalResult = mrOk then SaveRoles; finally Free; end; end; end; procedure TfrmUsers.urlRolesClick(Sender: TObject); begin inherited; ShowAssignedRoles; end; end.
object fmOptions: TfmOptions Left = 192 Top = 107 BorderStyle = bsDialog Caption = 'Options' ClientHeight = 147 ClientWidth = 273 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter PixelsPerInch = 96 TextHeight = 13 object laPollingInterval: TLabel Left = 24 Top = 32 Width = 72 Height = 13 Caption = '&Polling Interval:' FocusControl = cmbPollingInterval end object cmbPollingInterval: TComboBox Left = 112 Top = 28 Width = 137 Height = 21 Style = csDropDownList ItemHeight = 13 TabOrder = 0 Items.Strings = ( '10 minutes' '1 hour' '5 hours' '10 hours' '1 day' '1 week') end object cbRunAtWinStartup: TCheckBox Left = 24 Top = 64 Width = 225 Height = 17 Caption = '&Run at Windows Startup' TabOrder = 1 end object btOk: TButton Left = 51 Top = 100 Width = 75 Height = 22 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 2 end object btCancel: TButton Left = 147 Top = 100 Width = 75 Height = 22 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 3 end end
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIResDef.pas // Creator : Shen Min // Date : 2002-5-15 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIResDef; interface {$I SUIPack.inc} {$IFDEF RES_ALL} {$R UIResAll.res} {$ELSE} {$IFDEF RES_MACOS} {$R UIResMac.res} {$ENDIF} {$IFDEF RES_WINXP} {$R UIResXP.res} {$ENDIF} {$IFDEF RES_DEEPBLUE} {$R UIResDB.res} {$ENDIF} {$IFDEF RES_BLUEGLASS} {$R UIResBG.res} {$ENDIF} {$IFDEF RES_PROTEIN} {$R UIResPt.res} {$ENDIF} {$R UIResCom.res} {$ENDIF} {$R SUIPack.dcr} resourcestring {$IFDEF LANG_CHS} SUI_TITLE_MENUITEM_MINIMIZE = '最小化(&N)'; SUI_TITLE_MENUITEM_MAXIMIZE = '最大化/还原(&X)'; SUI_TITLE_MENUITEM_CLOSE = '关闭(&C)'; {$ELSE} SUI_TITLE_MENUITEM_MINIMIZE = 'Mi&nimize'; SUI_TITLE_MENUITEM_MAXIMIZE = 'Ma&ximize/Restore'; SUI_TITLE_MENUITEM_CLOSE = '&Close'; {$ENDIF} implementation end.
program letterFrequency(input, output, stdErr); var chart: array[char] of integer; c: char; begin for c := low(chart) to high(chart) do begin chart[c] := 0; end; // parameter-less EOF() checks for EOF(input) while not EOF() do begin read(c); inc(chart[c]); end; // now, chart[someLetter] gives you the letter’s frequency end.
unit CloseGateState; interface uses System.SysUtils, GateInterface, GateClass; type TCloseGate = class(TInterfacedObject, IGate) private Gate: TGate; Paid: Boolean; public constructor Create(Gate: TGate); procedure Enter; procedure Pay; procedure PayOk; end; implementation uses OpenGateState; { TCloseGate } constructor TCloseGate.Create(Gate: TGate); begin Self.Gate := Gate; Paid := False; end; procedure TCloseGate.Enter; begin Writeln('You have to pay, so then the gate will be opened...'); end; procedure TCloseGate.Pay; begin Writeln('Processing the payment...'); Self.Gate.ChangeState(TOpenGate.Create(Self.Gate)); Paid := True; PayOk; end; procedure TCloseGate.PayOk; begin if Paid = False then Writeln('You have to pay first...') else Writeln('You paid the gate, go ahead...'); end; end.
unit ASDVector; {<|Модуль библиотеки ASDEngine|>} {<|Дата создания 08.07.07|>} {<|Автор Adler3D|>} {<|e-mail : Adler3D@Mail.ru|>} {<|Дата последнего изменения 08.07.07|>} interface {$D-} Uses Windows; type PVector = ^TVector; TVector = record X, Y: Real; end; PVectorAngle = ^TVectorAngle; TVectorAngle = record Alfa, Dlina: Real; end; PLine = ^TLine; TLine = record A, B: TVector; end; function MakeVector(X, Y: Real): TVector; function MakeVectorAngle(Alfa, Dlina: Real): TVectorAngle; function MakeLine(A, B: TVector): TLine; function VectorAdd(A, B: TVector): TVector; function VectorMul(V: TVector; Value: Real): TVector; function VectorDiv(V: TVector; Value: Real): TVector; function VectorSub(A, B: TVector): TVector; function VectorMagnitude(V: TVector): Real; function VectorGetAlfa(V: TVector): Real; function VectorAngleToVector(V: TVectorAngle): TVector; function VectorToVectorAngle(V: TVector): TVectorAngle; function VectorNormal(V: TVector): TVector; function VectorSetAlfa(V: TVector; Alfa: Real): TVector; function VectorAddAlfa(V: TVector; Alfa: Real): TVector; function VectorSetDlina(V: TVector; Dlina: Real): TVector; function VectorAddDlina(V: TVector; Dlina: Real): TVector; function VectorEquel(V1, V2: TVector): Boolean; function Prompting(A, B: TVector; const Vector: TVector; AddAlfa: Real): TVector; function PromptingAlfa(A, B: TVector; const Vector: TVector; AddAlfa: Real): Real; function RndReal(Min, Max: Real; Step: Real = 0.1): Real; function VectorToPoint(V: TVector): TPoint; function PointToVector(P: TPoint): TVector; {function VectorToStr(V: TVector): string; function StrToVector(S: string): TVector;} function VectorCompareAlfa(VA, VB: TVector): Real; function VectorCompareDlina(VA, VB: TVector): Real; function VectorABDlina(A,B:TVector):Real; function ArcTan2(const Y, X: Extended): Extended; const NulVectorAngle: TVectorAngle = (Alfa: 0; Dlina: 0); NulVector: TVector = (X: 0.000; Y: 0.000); implementation function ArcTan2(const Y, X: Extended): Extended; asm FLD Y FLD X FPATAN FWAIT end; function VectorABDlina(A,B:TVector):Real; begin Result := ((A.X - B.X) * (A.X - B.X) + (A.Y - B.Y) * (A.Y - B.Y)); end; function RndReal(Min, Max: Real; Step: Real = 0.1): Real; begin Result := Random(Round((Max - Min) / Step)) * Step + Min; end; function VectorToPoint(V: TVector): TPoint; begin Result.X := Round(V.X); Result.Y := Round(V.Y); end; function PointToVector(P: TPoint): TVector; begin Result.X := P.X; Result.Y := P.Y; end; {function PromptingAlfa(A, B: TVector; const Vector: TVector; AddAlfa: Real): Real; function Moderne(mode, dive: real): Real; begin Result := mode - (dive * trunc(mode / dive)); end; var Z, Go: Real; V: TVectorAngle; const Rg: Real = (Pi / 180); begin Result:=0; V := VectorToVectorAngle(Vector); V.Alfa := V.Alfa / Rg; Z := Arctan2((B.Y - A.Y), (B.X - A.X)) / Rg; Go := Moderne((ABS(Z - V.Alfa)), 360); if (Z >= V.Alfa) and (Go <= 180) then Result := +AddAlfa; if (Z < V.Alfa) and (Go < 180) then Result := -AddAlfa; if (Z >= V.Alfa) and (Go > 180) then Result := -AddAlfa; if (Z < V.Alfa) and (Go > 180) then Result := +AddAlfa; end;} function PromptingAlfa(A, B: TVector; const Vector: TVector; AddAlfa: Real): Real; function Moderne(mode, dive: real): Real; begin Result := mode - (dive * trunc(mode / dive)); end; var TAlfa, SAlfa: Real; V: TVector; begin V := VectorSub(A, B); TAlfa := VectorGetAlfa(V); SAlfa := VectorGetAlfa(Vector); if Abs(TAlfa - SAlfa) > Pi then begin if TAlfa < SAlfa then TAlfa := TAlfa + (2 * Pi) else SAlfa := SAlfa + (2 * Pi); end; if Abs(TAlfa - SAlfa) >= AddAlfa then begin if TAlfa < SAlfa then Result := +AddAlfa else Result := -AddAlfa; end else Result := 0; end; function Prompting(A, B: TVector; const Vector: TVector; AddAlfa: Real): TVector; function Moderne(mode, dive: real): Real; begin Result := mode - (dive * trunc(mode / dive)); end; var PAlfa, Alfa, AddReal: Real; V: TVectorAngle; const Rg: Real = (Pi / 180); begin AddReal := 0; V := VectorToVectorAngle(Vector); V.Alfa := V.Alfa / Rg; PAlfa := Arctan2((B.Y - A.Y), (B.X - A.X)) / Rg; Alfa := Moderne((ABS(PAlfa - V.Alfa)), 360); if (PAlfa >= V.Alfa) and (Alfa <= 180) then AddReal := +AddAlfa; if (PAlfa < V.Alfa) and (Alfa < 180) then AddReal := -AddAlfa; if (PAlfa >= V.Alfa) and (Alfa > 180) then AddReal := -AddAlfa; if (PAlfa < V.Alfa) and (Alfa > 180) then AddReal := +AddAlfa; V.Alfa := V.Alfa * Rg; V.Alfa := V.Alfa + AddReal; Result := VectorAngleToVector(V); end; function VectorEquel(V1, V2: TVector): Boolean; begin Result := (V1.X = V2.X) and (V1.Y = V2.Y); end; function VectorSetDlina(V: TVector; Dlina: Real): TVector; var K: Real; begin K := Dlina / Sqrt((V.X * V.X) + (V.Y * V.Y)); Result.X := V.X*K; Result.Y := V.Y*K; end; function VectorAddDlina(V: TVector; Dlina: Real): TVector; var K: Real; begin K := Dlina / Sqrt((V.X * V.X) + (V.Y * V.Y)); Result.X := V.X+(V.X*K); Result.Y := V.Y+(V.Y*K); end; function VectorSetAlfa(V: TVector; Alfa: Real): TVector; var M: Real; begin M := Sqrt((V.X * V.X) + (V.Y * V.Y)); Result.X := M * Cos(Alfa); Result.Y := M * Sin(Alfa); end; function VectorAddAlfa(V: TVector; Alfa: Real): TVector; begin Result.X := V.X * Cos(Alfa) - V.Y * Sin(Alfa); Result.Y := V.X * Sin(Alfa) + V.Y * Cos(Alfa); end; function VectorNormal(V: TVector): TVector; begin Result.Y := Sqrt((V.X * V.X) + (V.Y * V.Y)); if Result.Y = 0 then begin Result.X := 0; Exit; end; Result.X := V.X / Result.Y; Result.Y := V.Y / Result.Y; end; function MakeVectorAngle(Alfa, Dlina: Real): TVectorAngle; begin Result.Alfa := Alfa; Result.Dlina := Dlina; end; function VectorAngleToVector(V: TVectorAngle): TVector; begin Result.X := Cos(V.Alfa) * V.Dlina; Result.Y := Sin(V.Alfa) * V.Dlina; end; function VectorToVectorAngle(V: TVector): TVectorAngle; begin Result.Alfa := ArcTan2(V.Y, V.X); Result.Dlina := Sqrt((V.Y * V.Y) + (V.X * V.X)); end; function MakeVector(X, Y: Real): TVector; begin Result.X := X; Result.Y := Y; end; function VectorAdd(A, B: TVector): TVector; begin Result.X := A.X + B.X; Result.Y := A.Y + B.Y; end; function VectorMul(V: TVector; Value: Real): TVector; begin Result.X := V.X * Value; Result.Y := V.Y * Value; end; function VectorDiv(V: TVector; Value: Real): TVector; begin Result.X := V.X / Value; Result.Y := V.Y / Value; end; function VectorMagnitude(V: TVector): Real; begin Result := Sqrt((V.X * V.X) + (V.Y * V.Y)); end; function VectorGetAlfa(V: TVector): Real; begin Result := ArcTan2(V.Y, V.X); end; function VectorSub(A, B: TVector): TVector; begin Result.X := A.X - B.X; Result.Y := A.Y - B.Y; end; {function VectorToStr(V: TVector): string; begin Result := 'X:' + FloatToStrF(V.X, ffFixed, 8, 16); Result := Result + ' Y:' + FloatToStrF(V.Y, ffNumber, 8, 16); end; function StrToVector(S: string): TVector; var P: Integer; S1, S2: string; begin P := Pos(' ', S); S1 := Copy(S, 3, P - 3); S2 := Copy(S, P + 3, 128); Result.X := StrToFloat(S1); Result.Y := StrToFloat(S2); end;} function VectorCompareAlfa(VA, VB: TVector): Real; var A, B: Real; begin A := ArcTan2(VA.Y, VA.X); B := ArcTan2(VB.Y, VB.X); if Abs(A - B) >= Pi then begin if A < B then A := A + (2 * Pi) else B := B + (2 * Pi); end; Result := A - B; end; function VectorCompareDlina(VA, VB: TVector): Real; var A, B: Real; begin A := VectorMagnitude(VA); B := VectorMagnitude(VB); Result := A - B; end; function MakeLine(A, B: TVector): TLine; begin Result.A := A; Result.B := B; end; end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.DBXJSON; interface uses Data.DBXPlatform, System.SysUtils, System.JSON ; type /// <summary>Represents the base class for callback methods.</summary> TDBXCallback = class abstract public /// <summary> Holds the client side callback logic. /// </summary> /// <remarks> /// Function doesn't have argument ownership /// /// </remarks> /// <param name="Arg">- JSON value</param> /// <returns>JSON value</returns> function Execute(const Arg: TJSONValue): TJSONValue; overload; virtual; abstract; /// <summary> Holds the client side callback logic. /// </summary> /// <remarks> /// Function doesn't have argument ownership /// /// </remarks> /// <param name="Arg">- Object value</param> /// <returns>an object instance</returns> function Execute(Arg: TObject): TObject; overload; virtual; abstract; {$IFNDEF AUTOREFCOUNT} /// <summary> Manage reference count by increasing with one unit /// /// </summary> /// <returns>new count</returns> function AddRef: Integer; virtual; /// <summary> Decreases the reference count. If the count is zero (or less) /// </summary> /// <remarks> If the count is zero (or less) /// the instance self-destructs. /// /// </remarks> /// <returns>current count</returns> function Release: Integer; virtual; {$ENDIF !AUTOREFCOUNT} protected /// <summary> Override the method if you are using the connection handler. /// </summary> /// <remarks> /// /// The information when is provided when known. /// /// </remarks> /// <param name="ConnectionHandler">- connection handler as an Object</param> procedure SetConnectionHandler(const ConnectionHandler: TObject); virtual; procedure SetDsServer(const DsServer: TObject); virtual; /// <summary> Override this method if you are using the parameter ordinal (index in the /// parameter list, starting with zero). /// </summary> /// <remarks> /// /// The information when is provided when known. /// /// </remarks> /// <param name="Ordinal">- callback parameter index </param> procedure SetOrdinal(const Ordinal: Integer); virtual; function IsConnectionLost: Boolean; virtual; private {$IFNDEF AUTOREFCOUNT} FFRefCount: Integer; {$ENDIF !AUTOREFCOUNT} public /// <summary> Override the method if you are using the connection handler. /// </summary> /// <remarks> /// /// The information when is provided when known. /// /// </remarks> property ConnectionHandler: TObject write SetConnectionHandler; property DsServer: TObject write SetDsServer; /// <summary> Override this method if you are using the parameter ordinal (index in the /// parameter list, starting with zero). /// </summary> /// <remarks> /// /// The information when is provided when known. /// /// </remarks> property Ordinal: Integer write SetOrdinal; property ConnectionLost: Boolean read IsConnectionLost; public /// <summary> Constant for JSON based argument remote invocation /// </summary> const ArgJson = 1; /// <summary> Constant for object based argument remote invocation /// </summary> const ArgObject = 2; end; /// <summary>Represents an intermediate placeholder for a callback /// instance.</summary> TDBXCallbackDelegate = class(TDBXCallback) public /// <summary> Frees the delegate, if any /// </summary> destructor Destroy; override; /// <summary> see com.borland.dbx.json.DBXCallback#execute(com.borland.dbx.json.JSONValue) /// </summary> function Execute(const Arg: TJSONValue): TJSONValue; overload; override; /// <summary> see <see cref="TDBXCallback.execute(TObject)"/> /// </summary> function Execute(Arg: TObject): TObject; overload; override; protected procedure SetDelegate(const Callback: TDBXCallback); virtual; function GetDelegate: TDBXCallback; virtual; procedure SetConnectionHandler(const ConnectionHandler: TObject); override; procedure SetOrdinal(const Ordinal: Integer); override; procedure SetDsServer(const DsServer: TObject); override; function IsConnectionLost: Boolean; override; private FDelegate: TDBXCallback; [Weak]FConnectionHandler: TObject; [Weak]FDsServer: TObject; FOrdinal: Integer; public property Delegate: TDBXCallback read GetDelegate write SetDelegate; end; /// <summary>Represents an extension of the base class for callback /// methods.</summary> TDBXNamedCallback = class abstract(TDBXCallback) public /// <summary> constructor for a named callback, which takes in the callback's name /// </summary> /// <param name="name">the name of the callback</param> constructor Create(const Name: string); protected /// <summary> Returns the name of this callback /// </summary> /// <returns>the callback's name</returns> function GetName: string; virtual; protected FName: string; public /// <summary> Returns the name of this callback /// </summary> /// <returns>the callback's name</returns> property Name: string read GetName; end; function GetUSFormat : TFormatSettings; implementation uses Data.DBXCommonResStrs, Data.DBXCommon, System.StrUtils ; const HexChars = '0123456789ABCDEF'; function GetUSFormat : TFormatSettings; begin Result := TFormatSettings.Create( 'en-US' ); end; procedure TDBXCallback.SetConnectionHandler(const ConnectionHandler: TObject); begin end; procedure TDBXCallback.SetDsServer(const DsServer: TObject); begin end; procedure TDBXCallback.SetOrdinal(const Ordinal: Integer); begin end; {$IFNDEF AUTOREFCOUNT} function TDBXCallback.AddRef: Integer; begin Inc(FFRefCount); Result := FFRefCount; end; function TDBXCallback.Release: Integer; var Count: Integer; begin Dec(FFRefCount); Count := FFRefCount; if Count <= 0 then self.Free; Result := Count; end; {$ENDIF !AUTOREFCOUNT} function TDBXCallback.IsConnectionLost: Boolean; begin Result := False; end; destructor TDBXCallbackDelegate.Destroy; begin FreeAndNil(FDelegate); inherited Destroy; end; function TDBXCallbackDelegate.Execute(const Arg: TJSONValue): TJSONValue; begin Result := FDelegate.Execute(Arg); end; function TDBXCallbackDelegate.Execute(Arg: TObject): TObject; begin Result := FDelegate.Execute(Arg); end; procedure TDBXCallbackDelegate.SetDelegate(const Callback: TDBXCallback); begin FDelegate := Callback; if FDelegate <> nil then begin FDelegate.Ordinal := FOrdinal; FDelegate.ConnectionHandler := FConnectionHandler; FDelegate.DsServer := FDsServer; end; end; function TDBXCallbackDelegate.GetDelegate: TDBXCallback; begin Result := FDelegate; end; function TDBXCallbackDelegate.IsConnectionLost: Boolean; begin if Assigned(FDelegate) then Exit(FDelegate.ConnectionLost); Exit(False); end; procedure TDBXCallbackDelegate.SetConnectionHandler(const ConnectionHandler: TObject); begin FConnectionHandler := ConnectionHandler; if FDelegate <> nil then FDelegate.ConnectionHandler := ConnectionHandler; end; procedure TDBXCallbackDelegate.SetOrdinal(const Ordinal: Integer); begin FOrdinal := Ordinal; if FDelegate <> nil then FDelegate.Ordinal := Ordinal; end; procedure TDBXCallbackDelegate.SetDsServer(const DsServer: TObject); begin FDsServer := DsServer; if FDelegate <> nil then FDelegate.DsServer := DsServer; end; constructor TDBXNamedCallback.Create(const Name: string); begin inherited Create; FName := Name; end; function TDBXNamedCallback.GetName: string; begin Result := FName; end; end.
unit Router4D.Interfaces; {$I Router4D.inc} interface uses System.Classes, System.Generics.Collections, System.UITypes, SysUtils, {$IFDEF HAS_FMX} FMX.Types, {$ELSE} Vcl.ExtCtrls, Vcl.Forms, {$ENDIF} Router4D.Props; type iRouter4D = interface ['{56BF88E9-25AB-49C7-8CB2-F89C95F34816}'] end; iRouter4DComponent = interface ['{C605AEFB-36DC-4952-A3D9-BA372B998BC3}'] {$IFDEF HAS_FMX} function Render : TFMXObject; {$ElSE} function Render : TForm; {$ENDIF} procedure UnRender; end; iRouter4DComponentProps = interface ['{FAF5DD55-924F-4A8B-A436-208891FFE30A}'] procedure Props ( aProps : TProps ); end; iRouter4DLink = interface ['{3C80F86A-D6B8-470C-A30E-A82E620F6F1D}'] {$IFDEF HAS_FMX} function &To ( aPatch : String; aComponent : TFMXObject ) : iRouter4DLink; overload; function Animation ( aAnimation : TProc<TFMXObject> ) : iRouter4DLink; {$ELSE} function &To ( aPatch : String; aComponent : TPanel ) : iRouter4DLink; overload; function Animation ( aAnimation : TProc<TPanel> ) : iRouter4DLink; {$ENDIF} function &To ( aPatch : String) : iRouter4DLink; overload; function &To ( aPatch : String; aProps : TProps; aKey : String = '') : iRouter4DLink; overload; function &To ( aPatch : String; aNameContainer : String) : iRouter4DLink; overload; function IndexLink ( aPatch : String ) : iRouter4DLink; function GoBack : iRouter4DLink; end; iRouter4DRender = interface ['{2BD026ED-3A92-44E9-8CD4-38E80CB2F000}'] {$IFDEF HAS_FMX} function SetElement ( aComponent : TFMXObject; aIndexComponent : TFMXObject = nil ) : iRouter4DRender; {$ELSE} function SetElement ( aComponent : TPanel; aIndexComponent : TPanel = nil ) : iRouter4DRender; {$ENDIF} end; iRouter4DSwitch = interface ['{0E49AFE7-9329-4F0C-B289-A713FA3DFE45}'] function Router(aPath : String; aRouter : TPersistentClass; aSidebarKey : String = 'SBIndex'; isVisible : Boolean = True) : iRouter4DSwitch; function UnRouter(aPath : String) : iRouter4DSwitch; end; iRouter4DSidebar = interface ['{B4E8C229-A801-4FCA-AF7B-DEF8D0EE5DFE}'] function Name ( aValue : String ) : iRouter4DSidebar; overload; {$IFDEF HAS_FMX} function MainContainer ( aValue : TFMXObject ) : iRouter4DSidebar; overload; function MainContainer : TFMXObject; overload; function LinkContainer ( aValue : TFMXObject ) : iRouter4DSidebar; function Animation ( aAnimation : TProc<TFMXObject> ) : iRouter4DSidebar; function RenderToListBox : iRouter4DSidebar; {$ELSE} function MainContainer ( aValue : TPanel ) : iRouter4DSidebar; overload; function MainContainer : TPanel; overload; function LinkContainer ( aValue : TPanel ) : iRouter4DSidebar; function Animation ( aAnimation : TProc<TPanel> ) : iRouter4DSidebar; {$ENDIF} function Name : String; overload; function FontSize ( aValue : Integer ) : iRouter4DSidebar; function FontColor ( aValue : TAlphaColor ) : iRouter4DSidebar; function ItemHeigth ( aValue : Integer ) : iRouter4DSidebar; end; implementation end.
unit Module.DataSet.ConfigMemento.Filter; interface uses FireDac.Comp.Client, Module.DataSet.ConfigMemento; type TConfigFilter = class(TInterfacedObject, IInterface) private FDataSet: TFDMemTable; FFilter: string; FFiltered: boolean; public constructor Create(const ADataSet: TFDMemTable); destructor Destroy; override; end; implementation { TConfigFilter } constructor TConfigFilter.Create(const ADataSet: TFDMemTable); begin FDataSet := ADataSet; FFilter := FDataSet.Filter; FFiltered := FDataSet.Filtered; end; destructor TConfigFilter.Destroy; begin FDataSet.Filter := FFilter; FDataSet.Filtered := FFiltered; inherited; end; end.
{*------------------------------------------------------------------------------ *ModuleInit_u * The actual Apache API routines are assigned in the ApacheInit.pas unit. * When working with the Apache API you should try to put the assignments * in a seperate unit so that your WebModule is Portable. * *About this demo. * This demo will show how to assign the module initialization handler. It will * Load an ini file and display this data when this module is uses as a content * handler. *-----------------------------------------------------------------------------} unit ModuleInit_u; interface uses {$IFDEF WINDOWS} Windows, Messages, {$ENDIF} SysUtils, Classes, HTTPApp, ApacheApp, HTTPD, IniFiles, // unit that contains the Apache Handlers. ApacheInit; type TWebModule1 = class(TWebModule) procedure WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); private public constructor Create(AOwner: TComponent); override; end; var WebModule1: TWebModule1; implementation {$R *.dfm} constructor TWebModule1.Create(AOwner: TComponent); begin inherited Create(AOwner); end; procedure TWebModule1.WebModule1WebActionItem1Action(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean); var i, count: integer; begin Response.Content:='These are that were initialized by the module<BR><BR>'; Response.Content:= Response.Content + '<B>Interbase Drivers</B><BR>'; // read the ini values out to the client count:= Interbase_Drivers.Count; for i:=0 to count -1 do response.Content:= Response.Content + Interbase_Drivers.Strings[i] + '<BR>'; Response.Content:= Response.Content + '<B>IBLocal Settings</B><BR>'; count:=IBLocal_Settings.Count; for i:=0 to count-1 do Response.Content:= Response.Content + IBLocal_Settings.Strings[i] + '<BR>'; end; initialization // make the assignments here // ApacheOnInit :=WebModule1.Apache_OnInit; end.// end Unit
unit Mock.CommandSets; interface uses Windows, SysUtils, Dialogs, Mock.OSFile.IoControl, CommandSet, BufferInterpreter, Device.SMART.List; type TMockCommandSet = class abstract(TCommandSet) public function IsExternal: Boolean; override; end; TIntelNVMeCommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TSamsungNVMeCommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TOSNVMeCommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TATACommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TLegacyATACommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TSATCommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TNVMeWithoutDriverCommandSet = class sealed(TMockCommandSet) public procedure Flush; override; function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function DataSetManagement(StartLBA, LBACount: Int64): Cardinal; override; function IsDataSetManagementSupported: Boolean; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; end; TCommandOrder = ( CommandOrderOfNVMeIntel, CommandOrderOfNVMeSamsung, CommandOrderOfATA, CommandOrderOfATALegacy, CommandOrderOfSAT, CommandOrderOfNVMeWithoutDriver, CommandOrderFinished); EWrongOrderException = class(Exception); function GetCurrentCommandSet: TCommandOrder; implementation var CurrentCommandSet: TCommandOrder; function GetCurrentCommandSet: TCommandOrder; begin result := CurrentCommandSet; end; procedure TIntelNVMeCommandSet.Flush; begin inherited; end; function TIntelNVMeCommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfNVMeIntel then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TIntelNVMeCommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TIntelNVMeCommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TIntelNVMeCommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TIntelNVMeCommandSet.RAWSMARTReadData: String; begin result := ''; end; function TIntelNVMeCommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; procedure TSamsungNVMeCommandSet.Flush; begin inherited; end; function TSamsungNVMeCommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfNVMeSamsung then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TSamsungNVMeCommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TSamsungNVMeCommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TSamsungNVMeCommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TSamsungNVMeCommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TSamsungNVMeCommandSet.RAWSMARTReadData: String; begin result := ''; end; procedure TOSNVMeCommandSet.Flush; begin inherited; end; function TOSNVMeCommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfNVMeIntel then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TOSNVMeCommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TOSNVMeCommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TOSNVMeCommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TOSNVMeCommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TOSNVMeCommandSet.RAWSMARTReadData: String; begin result := ''; end; procedure TATACommandSet.Flush; begin inherited; end; function TATACommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfATA then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TATACommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TATACommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TATACommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TATACommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TATACommandSet.RAWSMARTReadData: String; begin result := ''; end; procedure TLegacyATACommandSet.Flush; begin inherited; end; function TLegacyATACommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfATALegacy then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TLegacyATACommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TLegacyATACommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TLegacyATACommandSet.DataSetManagement( StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TLegacyATACommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TLegacyATACommandSet.RAWSMARTReadData: String; begin result := ''; end; procedure TSATCommandSet.Flush; begin inherited; end; function TSATCommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := ''; if CurrentCommandSet = TCommandOrder.CommandOrderOfSAT then result.Model := 'Right!' else exit; Inc(CurrentCommandSet); end; function TSATCommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TSATCommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TSATCommandSet.DataSetManagement(StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TSATCommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TSATCommandSet.RAWSMARTReadData: String; begin result := ''; end; procedure TNVMeWithoutDriverCommandSet.Flush; begin inherited; end; function TNVMeWithoutDriverCommandSet.IdentifyDevice: TIdentifyDeviceResult; begin result.Model := 'Right!'; end; function TNVMeWithoutDriverCommandSet.SMARTReadData: TSMARTValueList; begin result := nil; end; function TNVMeWithoutDriverCommandSet.IsDataSetManagementSupported: Boolean; begin result := false; end; function TNVMeWithoutDriverCommandSet.DataSetManagement( StartLBA, LBACount: Int64): Cardinal; begin result := 1; end; function TNVMeWithoutDriverCommandSet.RAWIdentifyDevice: String; begin result := ''; end; function TNVMeWithoutDriverCommandSet.RAWSMARTReadData: String; begin result := ''; end; { TMockCommandSet } function TMockCommandSet.IsExternal: Boolean; begin result := false; end; initialization CurrentCommandSet := CommandOrderOfNVMeIntel; finalization end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.ODBCDef; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.Intf; type // TFDPhysODBCConnectionDefParams // Generated for: FireDAC ODBC driver TFDODBCNumericFormat = (nfBinary, nfString); TFDODBCVersion = (ov3_8, ov3_0); /// <summary> TFDPhysODBCConnectionDefParams class implements FireDAC ODBC driver specific connection definition class. </summary> TFDPhysODBCConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetODBCAdvanced: String; procedure SetODBCAdvanced(const AValue: String); function GetLoginTimeout: Integer; procedure SetLoginTimeout(const AValue: Integer); function GetODBCDriver: String; procedure SetODBCDriver(const AValue: String); function GetDataSource: String; procedure SetDataSource(const AValue: String); function GetNumericFormat: TFDODBCNumericFormat; procedure SetNumericFormat(const AValue: TFDODBCNumericFormat); function GetODBCVersion: TFDODBCVersion; procedure SetODBCVersion(const AValue: TFDODBCVersion); function GetMetaDefCatalog: String; procedure SetMetaDefCatalog(const AValue: String); function GetMetaDefSchema: String; procedure SetMetaDefSchema(const AValue: String); function GetMetaCurCatalog: String; procedure SetMetaCurCatalog(const AValue: String); function GetMetaCurSchema: String; procedure SetMetaCurSchema(const AValue: String); function GetRDBMS: TFDRDBMSKind; procedure SetRDBMS(const AValue: TFDRDBMSKind); published property DriverID: String read GetDriverID write SetDriverID stored False; property ODBCAdvanced: String read GetODBCAdvanced write SetODBCAdvanced stored False; property LoginTimeout: Integer read GetLoginTimeout write SetLoginTimeout stored False; property ODBCDriver: String read GetODBCDriver write SetODBCDriver stored False; property DataSource: String read GetDataSource write SetDataSource stored False; property NumericFormat: TFDODBCNumericFormat read GetNumericFormat write SetNumericFormat stored False default nfString; property ODBCVersion: TFDODBCVersion read GetODBCVersion write SetODBCVersion stored False default ov3_0; property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False; property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False; property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False; property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False; property RDBMS: TFDRDBMSKind read GetRDBMS write SetRDBMS stored False; end; implementation uses FireDAC.Stan.Consts; // TFDPhysODBCConnectionDefParams // Generated for: FireDAC ODBC driver {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetODBCAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetODBCAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_ODBC_ODBCAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetLoginTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetLoginTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Common_LoginTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetODBCDriver: String; begin Result := FDef.AsString[S_FD_ConnParam_ODBC_ODBCDriver]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetODBCDriver(const AValue: String); begin FDef.AsString[S_FD_ConnParam_ODBC_ODBCDriver] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetDataSource: String; begin Result := FDef.AsString[S_FD_ConnParam_ODBC_DataSource]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetDataSource(const AValue: String); begin FDef.AsString[S_FD_ConnParam_ODBC_DataSource] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetNumericFormat: TFDODBCNumericFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_ODBC_NumericFormat]; if CompareText(s, 'Binary') = 0 then Result := nfBinary else if CompareText(s, 'String') = 0 then Result := nfString else Result := nfString; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetNumericFormat(const AValue: TFDODBCNumericFormat); const C_NumericFormat: array[TFDODBCNumericFormat] of String = ('Binary', 'String'); begin FDef.AsString[S_FD_ConnParam_ODBC_NumericFormat] := C_NumericFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetODBCVersion: TFDODBCVersion; var s: String; begin s := FDef.AsString[S_FD_ConnParam_ODBC_ODBCVersion]; if CompareText(s, '3.8') = 0 then Result := ov3_8 else if CompareText(s, '3.0') = 0 then Result := ov3_0 else Result := ov3_0; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetODBCVersion(const AValue: TFDODBCVersion); const C_ODBCVersion: array[TFDODBCVersion] of String = ('3.8', '3.0'); begin FDef.AsString[S_FD_ConnParam_ODBC_ODBCVersion] := C_ODBCVersion[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetMetaDefCatalog: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetMetaDefCatalog(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetMetaDefSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetMetaDefSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetMetaCurCatalog: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetMetaCurCatalog(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetMetaCurSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetMetaCurSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysODBCConnectionDefParams.GetRDBMS: TFDRDBMSKind; var oManMeta: IFDPhysManagerMetadata; begin FDPhysManager.CreateMetadata(oManMeta); Result := oManMeta.GetRDBMSKind(FDef.AsString[S_FD_ConnParam_Common_RDBMS]); end; {-------------------------------------------------------------------------------} procedure TFDPhysODBCConnectionDefParams.SetRDBMS(const AValue: TFDRDBMSKind); var oManMeta: IFDPhysManagerMetadata; begin FDPhysManager.CreateMetadata(oManMeta); FDef.AsString[S_FD_ConnParam_Common_RDBMS] := oManMeta.GetRDBMSName(AValue); end; end.
unit u_xml_globals; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DOM,u_xml; type { TXMLglobalType } TXMLglobalType = class(TDOMElement) private function Get_Comment: AnsiString; function Get_CreateTS: TDateTime; function Get_Expires: Boolean; function Get_ExpireTS: TDateTime; function Get_Former: AnsiString; function Get_LastUpdate: TDateTime; function Get_Name: AnsiString; function Get_Value: AnsiString; procedure Set_Comment(const AValue: AnsiString); procedure Set_CreateTS(const AValue: TDateTime); procedure Set_Expires(const AValue: Boolean); procedure Set_ExpireTS(const AValue: TDateTime); procedure Set_Former(const AValue: AnsiString); procedure Set_LastUpdate(const AValue: TDateTime); procedure Set_Name(const AValue: AnsiString); procedure Set_Value(const AValue: AnsiString); public procedure Remove; property Name : AnsiString read Get_Name write Set_Name; property Value : AnsiString read Get_Value write Set_Value; property LastUpdate : TDateTime read Get_LastUpdate write Set_LastUpdate; property Expires : Boolean read Get_Expires write Set_Expires; property Former : AnsiString read Get_Former write Set_Former; property Comment : AnsiString read Get_Comment write Set_Comment; property CreateTS : TDateTime read Get_CreateTS write Set_CreateTS; property ExpireTS : TDateTime read Get_ExpireTS write Set_ExpireTS; end; TXMLGlobalsType = specialize TXMLElementList<TXMLGlobalType>; implementation //========================================================================= uses XMLRead, XMLWrite, uxPLConst, StrUtils, cDateTime, cStrings; // TXMLGlobalType ======================================================================== function TXMLglobalType.Get_Comment: AnsiString; begin Result := GetAttribute(K_XML_STR_COMMENT); end; function TXMLglobalType.Get_CreateTS: TDateTime; var s : string; begin s := GetAttribute(K_XML_STR_CREATE); if s<>'' then result := StrToDateTime(s); end; function TXMLGlobalType.Get_Expires: Boolean; begin Result := (GetAttribute(K_XML_STR_Expires)=K_STR_TRUE) end; function TXMLglobalType.Get_ExpireTS: TDateTime; var s : string; begin s := GetAttribute(K_XML_STR_EXPIRE); if s<>'' then result := StrToDateTime(s); end; function TXMLglobalType.Get_Former: AnsiString; begin Result := GetAttribute(K_XML_STR_FORMER);end; function TXMLGlobalType.Get_LastUpdate: TDateTime; // Input field is formed like that : 2010-08-17T15:08:28.9063908+02:00 var str : string; begin Str := GetAttribute(K_XML_STR_Lastupdate); Str := AnsiLeftStr( Str, AnsiPos( '.', Str)-1); // Cut before '.' Str := StrRemoveChar( Str, '-'); // Remove '-' char Result := ISO8601StringAsDateTime(Str); end; function TXMLGlobalType.Get_Name: AnsiString; begin Result := GetAttribute(K_XML_STR_Name); end; function TXMLGlobalType.Get_Value: AnsiString; begin Result := GetAttribute(K_XML_STR_Value); end; procedure TXMLglobalType.Set_Comment(const AValue: AnsiString); begin SetAttribute(K_XML_STR_COMMENT,AValue); end; procedure TXMLglobalType.Set_CreateTS(const AValue: TDateTime); begin SetAttribute(K_XML_STR_CREATE, DateTimeToStr(aValue)); end; procedure TXMLglobalType.Set_Expires(const AValue: Boolean); begin SetAttribute(K_XML_STR_Expires,IfThen(aValue, K_STR_TRUE, K_STR_FALSE)); end; procedure TXMLglobalType.Set_ExpireTS(const AValue: TDateTime); begin SetAttribute(K_XML_STR_EXPIRE, DateTimeToStr(aValue)); end; procedure TXMLglobalType.Set_Former(const AValue: AnsiString); begin SetAttribute(K_XML_STR_FORMER, aValue); end; procedure TXMLglobalType.Set_LastUpdate(const AValue: TDateTime); // Restore 'a kind of' original formatting begin SetAttribute(K_XML_STR_Lastupdate, FormatDateTime('yyyy-mm-dd',aValue) + 'T' + FormatDateTime('hh:mm:ss.00+00:00',aValue)); end; procedure TXMLglobalType.Set_Name(const AValue: AnsiString); begin SetAttribute(K_XML_STR_Name,AValue); end; procedure TXMLglobalType.Set_Value(const AValue: AnsiString); begin SetAttribute(K_XML_STR_Value,AValue); end; procedure TXMLglobalType.Remove; begin ParentNode.RemoveChild(self); end; end.
unit u_xpl_message_GUI; {============================================================================== UnitName = u_xpl_message_GUI UnitVersion = 0.91 UnitDesc = xPL Message GUI management object and function UnitCopyright = GPL by Clinique / xPL Project ============================================================================== 0.91 : Forked from version 0.96 of uxplmessage, handling all user interface functions } {$i xpl.inc} interface uses Classes, SysUtils, u_xpl_Message; type TButtonOption = ( boLoad, boSave, boCopy, boSend, boClose, boOk, boAbout); TButtonOptions = set of TButtonOption; { TxPLMessageGUI } TxPLMessageGUI = class(TxPLMessage) public function Edit : boolean; dynamic; procedure Show(options : TButtonOptions); procedure ShowForEdit(const options : TButtonOptions; const bModal : boolean = false; const bAdvancedMode : boolean = true); function SelectFile : boolean; end; implementation { ==============================================================} uses frm_xPLMessage , v_xplmsg_opendialog , Controls , Forms ; procedure TxPLMessageGUI.ShowForEdit(const options: TButtonOptions; const bModal: boolean; const bAdvancedMode : boolean = true); begin with TfrmxPLMessage.Create(Application) do try xPLMessage := self; buttonOptions := options; FrameMessage.edtSource.ReadOnly := false; tsRaw.TabVisible := bAdvancedMode; tsPSScript.TabVisible := tsRaw.Visible; if bModal then ShowModal else Show; finally end; end; function TxPLMessageGUI.Edit : boolean; begin with TfrmxPLMessage.Create(Application) do try xPLMessage := self; result := (ShowModal = mrOk); finally Destroy; end; end; procedure TxPLMessageGUI.Show(options : TButtonOptions); begin with TfrmxPLMessage.Create(Application) do try xPLMessage := self; buttonOptions := options; Show; finally end; end; function TxPLMessageGUI.SelectFile: boolean; begin with TxPLMsgOpenDialog.create(Application) do try result := Execute; if result then LoadFromFile(FileName); finally Destroy; end; end; end.
unit uMainForm; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ExtCtrls, //GLScene GLScene, GLObjects, GLCadencer, GLWin32Viewer, GLBaseClasses, GLCrossPlatform, GLTexture, GLBitmapFont, GLWindowsFont, GLBehaviours, GLConsole, GLCoordinates, GLSimpleNavigation, GLUtils; type TMainForm = class(TForm) Viewer: TGLSceneViewer; GLCadencer1: TGLCadencer; Scene: TGLScene; GLCamera1: TGLCamera; Font1: TGLWindowsBitmapFont; GLCube1: TGLCube; GLLightSource1: TGLLightSource; Splitter1: TSplitter; Panel1: TPanel; GroupBox1: TGroupBox; ListBox1: TListBox; Splitter2: TSplitter; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; Button1: TButton; Button2: TButton; Timer1: TTimer; Label1: TLabel; Label2: TLabel; Button6: TButton; Button7: TButton; GLSimpleNavigation1: TGLSimpleNavigation; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: char); procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); procedure ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); procedure FormResize(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure CheckBox3Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure Button7Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } procedure OnHelloCommand(const Sender: TGLConsoleCommand; const Console: TGLCustomConsole; var Command: TGLUserInputCommand); public procedure OnCommand(const Sender: TGLConsoleCommand; const Console: TGLCustomConsole; var Command: TGLUserInputCommand); end; var MainForm: TMainForm; Console: TGLConsole; implementation {$R *.DFM} procedure TMainForm.OnHelloCommand(const Sender: TGLConsoleCommand; const Console: TGLCustomConsole; var Command: TGLUserInputCommand); begin Console.AddLine('Hi, dude!'); end; procedure TMainForm.OnCommand(const Sender: TGLConsoleCommand; const Console: TGLCustomConsole; var Command: TGLUserInputCommand); var I: integer; str: string; begin if Command.CommandCount = 0 then exit; Command.strings[0] := lowercase(Command.strings[0]); if Command.strings[0] = 'echo' then begin for I := 1 to Command.CommandCount - 1 do str := str + Command.strings[I]; Console.AddLine('You just typed: ' + str); Command.UnknownCommand := False; end else if Command.strings[0] = 'exit' then begin Application.Terminate; Command.UnknownCommand := False; // user won't see it anyway, but you should // get used to puting this line in every // command you recognize :) end; if Command.UnknownCommand then Console.AddLine('Current supported external commands are:' + '"echo" and "exit"!'); end; procedure TMainForm.FormCreate(Sender: TObject); begin Console := TGLConsole.CreateAsChild(Scene.Objects); Console.Visible := False; Console.SceneViewer := Viewer; Console.Font := Font1; //optional stuff: SetGLSceneMediaDir(); Console.HudSprite.Material.Texture.Image.LoadFromFile('GLScene.bmp'); Console.AddLine('Console started'); Console.HUDSpriteColor := clWhite; Console.FontColor := clBlue; //two ways of processing commands: //1) manual Console.OnCommandIssued := OnCommand; //2)using built-in objects (prefered) with Console.Commands.Add do begin CommandName := 'hello'; ShortHelp := 'Says hi to you too'; LongHelp.Add('Well, the console really does say "Hi, dude" to you, because'); LongHelp.Add('it is roude not to greet someone, when he says "hello" to you ;)'); OnCommand := OnHelloCommand; end; //register additional commands to enable auto-completion function with Console.AdditionalCommands do begin Add('echo'); Add('exit'); end; end; procedure TMainForm.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double); begin Viewer.Invalidate(); end; procedure TMainForm.FormKeyPress(Sender: TObject; var Key: char); begin Console.ProcessKeyPress(Key); end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState); begin Console.ProcessKeyDown(Key); end; procedure TMainForm.ViewerMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer); begin Console.Visible := not Console.Visible; end; procedure TMainForm.FormResize(Sender: TObject); begin Console.RefreshHudSize(); end; procedure TMainForm.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then Console.Options := Console.Options + [coAutoCompleteCommandsOnKeyPress] else Console.Options := Console.Options - [coAutoCompleteCommandsOnKeyPress]; Viewer.SetFocus(); end; procedure TMainForm.CheckBox2Click(Sender: TObject); begin if CheckBox2.Checked then Console.Options := Console.Options + [coAutoCompleteCommandsOnEnter] else Console.Options := Console.Options - [coAutoCompleteCommandsOnEnter]; Viewer.SetFocus(); end; procedure TMainForm.CheckBox3Click(Sender: TObject); begin if CheckBox3.Checked then Console.Options := Console.Options + [coShowConsoleHelpIfUnknownCommand] else Console.Options := Console.Options - [coShowConsoleHelpIfUnknownCommand]; Viewer.SetFocus(); end; procedure TMainForm.Button1Click(Sender: TObject); begin Console.TypedCommands.SaveToFile('saved_typed_commands.ini'); Viewer.SetFocus(); end; procedure TMainForm.Button2Click(Sender: TObject); begin Console.ColsoleLog.SaveToFile('saved_console_output.ini'); Viewer.SetFocus(); end; procedure TMainForm.Button6Click(Sender: TObject); begin Console.TypedCommands.LoadFromFile('saved_typed_commands.ini'); Viewer.SetFocus(); end; procedure TMainForm.Button7Click(Sender: TObject); begin Console.ColsoleLog.LoadFromFile('saved_console_output.ini'); Console.RefreshHudSize(); Viewer.SetFocus(); end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin GLCadencer1.Enabled := False; Console.Destroy; end; end.
unit ReportCashBook; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, ComCtrls, ToolWin; type TReportCashBookForm = class(TForm) Panel1: TPanel; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; ToolButton3: TToolButton; PrintButton: TToolButton; DBGridEh1: TDBGridEh; CloseButton: TButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CloseButtonClick(Sender: TObject); procedure PrintButtonClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ReportCashBookForm: TReportCashBookForm; implementation uses Main, StoreDM, ReportDM, ReportCashBookDateSelect, ReportCashBookItem, ReportDebtorPrint; {$R *.dfm} procedure TReportCashBookForm.FormCreate(Sender: TObject); begin CloseButton.Left := Panel1.Width - CloseButton.Width - 10; with ReportDataModule.CashBookDataSet do begin SelectSQL.Clear; SelectSQL.Add('SELECT *'); SelectSQL.Add('FROM "CashBook"'); SelectSQL.Add('WHERE "FirmID" = ' + IntToStr(MainFirm)); SelectSQL.Add('ORDER BY "Date"'); // ShowMessage(SQL.Text); Open; end; Caption := 'Кассовая книга'; end; procedure TReportCashBookForm.FormClose(Sender: TObject; var Action: TCloseAction); begin ReportDataModule.CashBookDataSet.Close; Release; end; procedure TReportCashBookForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TReportCashBookForm.PrintButtonClick(Sender: TObject); begin ReportDebtorPrintForm := TReportDebtorPrintForm.Create(Self); // ReportDebtorPrintForm.ShowModal; end; procedure TReportCashBookForm.Edit1Change(Sender: TObject); {var Find : String;{} begin { Find := AnsiUpperCase(Edit1.Text); with ReportDataModule.DebtorQuery do begin Close; SQL.Strings[2] := 'WHERE (UPPER("CustomerName" COLLATE PXW_CYRL) CONTAINING ''' + Find + ''')'; Open; end;{} end; procedure TReportCashBookForm.InsertButtonClick(Sender: TObject); begin ReportDataModule.CashBookDataSet.Append; ReportDataModule.CashBookDataSet['FirmID'] := MainFirm; ReportCashBookDateSelectForm := TReportCashBookDateSelectForm.Create(Self); ReportCashBookDateSelectForm.ShowModal; ReportDataModule.CashBookDataSet.Post; ReportCashBookItemForm := TReportCashBookItemForm.Create(Self); ReportCashBookItemForm.ShowModal; if ReportCashBookItemForm.ModalResult = mrOK then ReportDataModule.CashBookTransaction.Commit else ReportDataModule.CashBookTransaction.Rollback; ReportDataModule.CashBookDataSet.Open; end; procedure TReportCashBookForm.EditButtonClick(Sender: TObject); begin ReportCashBookItemForm := TReportCashBookItemForm.Create(Self); ReportCashBookItemForm.ShowModal; end; end.
{$mode objfpc} program serialportnames; uses Objects, Classes, SysUtils, BaseUnix; function GetSerialPortNames: string; type TSerialStruct = packed record typ: Integer; line: Integer; port: Cardinal; irq: Integer; flags: Integer; xmit_fifo_size: Integer; custom_divisor: Integer; baud_base: Integer; close_delay: Word; io_type: Char; reserved_char: Char; hub6: Integer; closing_wait: Word; // time to wait before closing closing_wait2: Word; // no longer used... iomem_base: ^Char; iomem_reg_shift: Word; port_high: Cardinal; iomap_base: LongWord; // cookie passed into ioremap end; var i: Integer; sr : TSearchRec; sl: TStringList; st: stat; s: String; fd: PtrInt; Ser : TSerialStruct; const TIOCGSERIAL = $541E; PORT_UNKNOWN = 0; begin Result := ''; sl := TStringList.Create; try // 1. Alle möglichen Ports finden if FindFirst('/sys/class/tty/*', LongInt($FFFFFFFF), sr) = 0 then begin repeat if (sr.Name <> '.') and (sr.Name <> '..') Then if (sr.Attr and LongInt($FFFFFFFF)) = Sr.Attr then sl.Add(sr.Name); until FindNext(sr) <> 0; end; FindClose(sr); // 2. heraussuchen ob ./device/driver vorhanden ist for i := sl.Count - 1 Downto 0 Do Begin If Not DirectoryExists('/sys/class/tty/' + sl[i] + '/device/driver') Then sl.Delete(i); // Nicht vorhanden >> Port existiert nicht end; // 3. Herausfinden welcher Treiber st.st_mode := 0; for i := sl.Count - 1 Downto 0 Do Begin IF fpLstat('/sys/class/tty/' + sl[i] + '/device', st) = 0 Then Begin if fpS_ISLNK(st.st_mode) Then Begin s := fpReadLink('/sys/class/tty/' + sl[i] + '/device/driver'); s := ExtractFileName(s); // 4. Bei serial8250 Treiber muss der Port geprüft werden If s = 'serial8250' Then Begin sl.Objects[i] := TObject(PtrInt(1)); fd := FpOpen('/dev/' + sl[i], O_RDWR Or O_NONBLOCK Or O_NOCTTY); If fd > 0 Then Begin If FpIOCtl(fd, TIOCGSERIAL, @Ser) = 0 Then Begin If Ser.typ = PORT_UNKNOWN Then // PORT_UNKNOWN sl.Delete(i); end; FpClose(fd); end else sl.Delete(i); // Port kann nicht geöffnet werden end; End; end; end; // 5. Dev anhängen for i := 0 To sl.Count - 1 Do sl[i] := '/dev/' + sl[i]; Result := sl.CommaText; finally sl.Free; end; end; begin writeln(); writeln(getserialportnames); writeln(); end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC monitor TCP/IP based implementation } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.Moni.RemoteClient; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Moni.Base; type {----------------------------------------------------------------------------} { TFDMoniRemoteClientLink } {----------------------------------------------------------------------------} [ComponentPlatformsAttribute(pfidWindows)] TFDMoniRemoteClientLink = class(TFDMoniClientLinkBase) private FRemoteClient: IFDMoniRemoteClient; function IsHS: Boolean; function GetHost: String; procedure SetHost(const AValue: String); function GetPort: Integer; procedure SetPortI(const AValue: Integer); function GetTimeout: Integer; procedure SetTimeout(const AValue: Integer); protected function GetMoniClient: IFDMoniClient; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property RemoteClient: IFDMoniRemoteClient read FRemoteClient; published property Host: String read GetHost write SetHost stored IsHS; property Port: Integer read GetPort write SetPortI default C_FD_MonitorPort; property Timeout: Integer read GetTimeout write SetTimeout default C_FD_MonitorTimeout; property Tracing; end; implementation uses {$IFDEF MSWINDOWS} Winapi.Windows, Winapi.WinSock, {$ENDIF} {$IFDEF UNIX} sockets, netdb, {$ENDIF} System.SysUtils, System.Variants, System.Win.ScktComp, System.Generics.Collections, System.Types, FireDAC.Moni.RemoteBase, FireDAC.Stan.Factory, FireDAC.Stan.Util; type // client TFDMoniRemoteClientQueueItem = class; TFDMoniRemoteClientAdapterList = class; TFDMoniRemoteSender = class; TFDMoniRemoteClient = class; {----------------------------------------------------------------------------} { TFDMoniRemoteClientQueueItem } {----------------------------------------------------------------------------} TFDMoniRemoteClientQueueItem = class(TFDMoniRemoteQueueItem) end; {----------------------------------------------------------------------------} { TFDMoniRemoteClientAdapterList } {----------------------------------------------------------------------------} TFDMoniRemoteClientAdapterList = class(TFDMoniRemoteAdapterList) private FNextHandle: Integer; public function GetUniqueHandle: LongWord; end; {----------------------------------------------------------------------------} { TFDMoniRemoteSender } {----------------------------------------------------------------------------} TFDMoniRemoteSender = class(TFDMoniRemoteQueueWorker) private FTCPClient: TClientSocket; FStream: TFDMoniRemoteStream; FClient: TFDMoniRemoteClient; FTimeout: Integer; FHost: String; FPort: Integer; FOnDisconnect: TNotifyEvent; function GetTracing: Boolean; procedure SetTracing(const AValue: Boolean); function IsMonitorRunning: Boolean; procedure DoDisconnect(Sender: TObject; Socket: TCustomWinSocket); protected function GetQueue: TFDMoniRemoteQueue; override; procedure DoAction; override; public constructor Create(AClient: TFDMoniRemoteClient); destructor Destroy; override; property Port: Integer read FPort write FPort default C_FD_MonitorPort; property Host: String read FHost write FHost; property Timeout: Integer read FTimeout write FTimeout default C_FD_MonitorTimeout; property Tracing: Boolean read GetTracing write SetTracing default False; property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; end; {----------------------------------------------------------------------------} { TFDMoniRemoteClient } {----------------------------------------------------------------------------} TFDMoniRemoteClient = class (TFDMoniClientBase, IFDMoniRemoteClient) private FSender: TFDMoniRemoteSender; FQueue: TFDMoniRemoteQueue; FAdapterList: TFDMoniRemoteClientAdapterList; FPackVersion: Integer; FProcessID: LongWord; FMonitorID: LongWord; FDestroying: Boolean; FDisconnecting: Boolean; function BuildItem(AEventKind: TFDMoniRemoteQueueEventKind): TFDMoniRemoteClientQueueItem; procedure DoDisconnected(Sender: TObject); protected // IFDMoniClient procedure Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String; const AArgs: array of const); override; function RegisterAdapter(const AAdapter: IFDMoniAdapter): LongWord; override; procedure UnregisterAdapter(const AAdapter: IFDMoniAdapter); override; procedure AdapterChanged(const AAdapter: IFDMoniAdapter); override; // IFDMoniRemoteClient function GetHost: String; procedure SetHost(const AValue: String); function GetPort: Integer; procedure SetPortI(const AValue: Integer); function GetTimeout: Integer; procedure SetTimeout(const AValue: Integer); // other function DoTracingChanged: Boolean; override; function OperationAllowed: Boolean; override; public procedure Initialize; override; destructor Destroy; override; property Sender: TFDMoniRemoteSender read FSender; end; var FClients: TList; {-------------------------------------------------------------------------------} { TFDMoniRemoteClientAdapterList } {-------------------------------------------------------------------------------} function TFDMoniRemoteClientAdapterList.GetUniqueHandle: LongWord; begin Result := LongWord(AtomicIncrement(FNextHandle)); end; {-------------------------------------------------------------------------------} { TFDMoniRemoteSender } {-------------------------------------------------------------------------------} constructor TFDMoniRemoteSender.Create(AClient: TFDMoniRemoteClient); begin inherited Create; FClient := AClient; FStream := TFDMoniRemoteStream.Create; FHost := '127.0.0.1'; FPort := C_FD_MonitorPort; FTimeout := C_FD_MonitorTimeout; Priority := tpHighest; end; {-------------------------------------------------------------------------------} destructor TFDMoniRemoteSender.Destroy; begin Tracing := False; Sleep(1); FDFreeAndNil(FTCPClient); FDFreeAndNil(FStream); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteSender.DoDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin if Assigned(FOnDisconnect) then FOnDisconnect(Sender); end; {-------------------------------------------------------------------------------} function TFDMoniRemoteSender.GetTracing: Boolean; begin Result := (FTCPClient <> nil) and FTCPClient.Active; end; {-------------------------------------------------------------------------------} {$IFDEF MSWINDOWS} var GWSAData: TWSAData; GWSAFailed: Boolean; GWSAInitialized: Boolean; function TFDMoniRemoteSender.IsMonitorRunning: Boolean; var iSock: TSocket; rAddr: TSockAddrIn; prHost: PHostEnt; pCh: {$IFDEF NEXTGEN} MarshaledAString {$ELSE} PAnsiChar {$ENDIF}; begin Result := False; if not GWSAInitialized then begin GWSAFailed := WSAStartup($0101, GWSAData) <> 0; GWSAInitialized := True; end; if GWSAFailed then Exit; try iSock := socket(PF_INET, SOCK_STREAM, IPPROTO_IP); if iSock <> INVALID_SOCKET then begin rAddr.sin_family := PF_INET; rAddr.sin_addr.s_addr := INADDR_ANY; rAddr.sin_port := 0; if bind(iSock, rAddr, SizeOf(rAddr)) <> SOCKET_ERROR then begin rAddr.sin_family := PF_INET; prHost := gethostbyname({$IFNDEF NEXTGEN} PAnsiChar {$ENDIF}(TFDEncoder.Enco(FHost, ecANSI))); if prHost <> nil then begin pCh := prHost^.h_addr_list^; rAddr.sin_addr.S_un_b.s_b1 := pCh[0]; rAddr.sin_addr.S_un_b.s_b2 := pCh[1]; rAddr.sin_addr.S_un_b.s_b3 := pCh[2]; rAddr.sin_addr.S_un_b.s_b4 := pCh[3]; rAddr.sin_port := htons(FPort); if connect(iSock, rAddr, SizeOf(rAddr)) <> SOCKET_ERROR then Result := True; end; end; shutdown(iSock, 2); closesocket(iSock); end; except // no exceptions visible end; end; {$ENDIF} {$IFDEF POSIX} function TFDMoniRemoteSender.IsMonitorRunning: Boolean; var iSock: TSocket; rAddr: TSockAddr; rHost: THostEntry; sb: TFDByteString; begin Result := False; try iSock := fpSocket(PF_INET, SOCK_STREAM, IPPROTO_IP); if iSock <> -1 then begin rAddr.sin_family := PF_INET; rAddr.sin_addr.s_addr := INADDR_ANY; rAddr.sin_port := 0; if fpBind(iSock, @rAddr, SizeOf(rAddr)) = 0 then begin rAddr.sin_family := PF_INET; sb := TFDEncoder.Enco(FHost, ecANSI); if GetHostByName(sb, rHost) or ResolveHostByName(sb, rHost) then begin rAddr.sin_addr := rHost.Addr; rAddr.sin_port := htons(FPort); if fpConnect(iSock, @rAddr, SizeOf(rAddr)) = 0 then Result := True; end; end; fpShutdown(iSock, 2); CloseSocket(iSock); end; except // no exceptions visible end; end; {$ENDIF} {-------------------------------------------------------------------------------} procedure TFDMoniRemoteSender.SetTracing(const AValue: Boolean); begin if Tracing <> AValue then if AValue then begin if IsMonitorRunning then try FTCPClient := TClientSocket.Create(nil); FTCPClient.Host := FHost; FTCPClient.Port := FPort; FTCPClient.ClientType := ctBlocking; FTCPClient.OnDisconnect := DoDisconnect; // ScktComp does not support timeout // FTCPClient.ConnectTimeout := FTimeout; FTCPClient.Open; except FDFreeAndNil(FTCPClient); raise; end end else begin try while FStream.IsOpen do Sleep(1); FTCPClient.Close; except // no exceptions visible end; FDFreeAndNil(FTCPClient); end; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteSender.DoAction; var oItem: TFDMoniRemoteClientQueueItem; begin oItem := TFDMoniRemoteClientQueueItem(GetQueue.GetItem); if oItem <> nil then try FStream.Open(FTCPClient.Socket, omWrite); try FStream.WriteInteger(S_FD_MsgEvent, Integer(oItem.FEvent)); FStream.WriteBeginBlock(C_FD_Mon_PacketBodyBlockID); case oItem.FEvent of ptConnectClient: begin FStream.WriteLongWord(S_FD_MsgProcessId, oItem.FProcessID); FStream.WriteLongWord(S_FD_MsgMonitorId, oItem.FMonitorID); FStream.WriteInteger(S_FD_MsgVersion, FClient.FPackVersion); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); FStream.WriteString(S_FD_MsgText, oItem.FMessage); end; ptDisConnectClient: begin FStream.WriteLongWord(S_FD_MsgProcessId, oItem.FProcessID); FStream.WriteLongWord(S_FD_MsgMonitorId, oItem.FMonitorID); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); end; ptRegisterAdapter: begin FStream.WriteLongWord(S_FD_MsgAdapterHandle, oItem.FHandle); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); FStream.WriteString(S_FD_MsgText, oItem.FPath); end; ptUnRegisterAdapter: begin FStream.WriteLongWord(S_FD_MsgAdapterHandle, oItem.FHandle); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); end; ptUpdateAdapter: begin FStream.WriteLongWord(S_FD_MsgAdapterHandle, oItem.FHandle); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); FStream.WriteBlob(S_FD_MsgArgs, oItem.FArgs); end; ptNotify: begin FStream.WriteLongWord(S_FD_MsgAdapterHandle, oItem.FHandle); FStream.WriteInteger(S_FD_MsgNotifyKind, Integer(oItem.FKind)); FStream.WriteInteger(S_FD_MsgNotifyStep, Integer(oItem.FStep)); FStream.WriteLongWord(S_FD_MsgTime, oItem.FTime); FStream.WriteString(S_FD_MsgText, oItem.FMessage); FStream.WriteBlob(S_FD_MsgArgs, oItem.FArgs); end; end; FStream.WriteEndBlock; finally try if (FStream <> nil) and GetTracing then FStream.Close; except if FTCPClient <> nil then FClient.SetTracing(False); raise; end; end; finally FDFree(oItem); end; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteSender.GetQueue: TFDMoniRemoteQueue; begin Result := FClient.FQueue; end; {-------------------------------------------------------------------------------} { TFDMoniRemoteClient } {-------------------------------------------------------------------------------} var FDMonitorLastID: Integer = 0; procedure TFDMoniRemoteClient.Initialize; begin inherited Initialize; FSender := TFDMoniRemoteSender.Create(Self); FSender.Host := '127.0.0.1'; FSender.Port := C_FD_MonitorPort; FSender.Timeout := C_FD_MonitorTimeout; FSender.OnDisconnect := DoDisconnected; FQueue := TFDMoniRemoteQueue.Create(FSender); FAdapterList := TFDMoniRemoteClientAdapterList.Create; FPackVersion := C_FD_Mon_PacketVersion; {$IFDEF MSWINDOWS} FProcessID := GetCurrentProcessId; {$ENDIF} {$IFDEF POSIX} FProcessID := GetProcessId; {$ENDIF} FMonitorID := AtomicIncrement(FDMonitorLastID); if FClients <> nil then FClients.Add(Self); end; {-------------------------------------------------------------------------------} destructor TFDMoniRemoteClient.Destroy; begin if FClients <> nil then FClients.Remove(Self); FDestroying := True; SetTracing(False); FDFreeAndNil(FQueue); FDFreeAndNil(FSender); FDFreeAndNil(FAdapterList); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.DoDisconnected(Sender: TObject); begin FDisconnecting := True; SetTracing(False); end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.BuildItem(AEventKind: TFDMoniRemoteQueueEventKind): TFDMoniRemoteClientQueueItem; begin Result := TFDMoniRemoteClientQueueItem.Create; Result.FProcessID := FProcessID; Result.FMonitorID := FMonitorID; Result.FEvent := AEventKind; Result.FTime := TThread.GetTickCount(); end; {-------------------------------------------------------------------------------} {$WARNINGS OFF} function TFDMoniRemoteClient.DoTracingChanged: Boolean; var oItem: TFDMoniRemoteClientQueueItem; iStartTime: Cardinal; begin Result := True; if GetTracing then begin FSender.Tracing := True; if FSender.Tracing then begin if FSender.Suspended then FSender.Resume; oItem := BuildItem(ptConnectClient); oItem.FMessage := ParamStr(0) + ';' + GetName; FQueue.PostItem(oItem); end else begin Result := False; if not FSender.Suspended then FSender.Suspend; end; end else begin FQueue.Clear; if FSender.Tracing then begin oItem := BuildItem(ptDisConnectClient); FQueue.PostItem(oItem); iStartTime := TThread.GetTickCount(); while (FQueue.Count > 0) and FSender.Tracing do begin Sleep(10); if FDTimeout(iStartTime, GetTimeout) then FQueue.Clear; end; end; FAdapterList.Clear; FSender.Tracing := False; if not FDestroying and not FDisconnecting and not FSender.Suspended then FSender.Suspend; end; end; {$WARNINGS ON} {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.OperationAllowed: Boolean; begin Result := (FClients <> nil); end; {-------------------------------------------------------------------------------} type __TInterfacedObject = class(TInterfacedObject) end; procedure TFDMoniRemoteClient.Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String; const AArgs: array of const); var oItem: TFDMoniRemoteClientQueueItem; hHandle: LongWord; oMAIntf: IFDMoniAdapter; iRefCount: Integer; sClassName, sName: String; begin if GetTracing and (AKind in GetEventKinds) then begin hHandle := 0; if (ASender <> nil) and (ASender is TInterfacedObject) then begin iRefCount := __TInterfacedObject(ASender).FRefCount; __TInterfacedObject(ASender).FRefCount := 2; try if Supports(ASender, IFDMoniAdapter, oMAIntf) then begin hHandle := oMAIntf.GetHandle; oMAIntf := nil; end; finally __TInterfacedObject(ASender).FRefCount := iRefCount; end; end; oItem := BuildItem(ptNotify); oItem.FKind := AKind; oItem.FStep := AStep; oItem.FHandle := hHandle; oItem.FMessage := AMsg; oItem.SetArgs(AArgs); FQueue.PostItem(oItem); if GetOutputHandler <> nil then begin GetObjectNames(ASender, sClassName, sName); GetOutputHandler.HandleOutput(sClassName, sName, AMsg); end; end; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.RegisterAdapter(const AAdapter: IFDMoniAdapter): LongWord; var oItem: TFDMoniRemoteClientQueueItem; sPath: string; oObj: IFDStanObject; begin if GetTracing then begin oObj := AAdapter as IFDStanObject; sPath := ''; repeat if sPath <> '' then sPath := '.' + sPath; sPath := oObj.Name + sPath; oObj := oObj.Parent; until oObj = nil; Result := FAdapterList.FindByPath(sPath); if Result = 0 then begin Result := FAdapterList.GetUniqueHandle; oItem := BuildItem(ptRegisterAdapter); oItem.FPath := sPath; oItem.FHandle := Result; FQueue.PostItem(oItem); end; end else Result := 0; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.UnRegisterAdapter(const AAdapter: IFDMoniAdapter); var oItem: TFDMoniRemoteClientQueueItem; hHandle: LongWord; begin if GetTracing then begin hHandle := AAdapter.GetHandle; if hHandle <> 0 then begin FAdapterList.RemoveAdapter(hHandle); oItem := BuildItem(ptUnRegisterAdapter); oItem.FHandle := hHandle; FQueue.PostItem(oItem); end; end; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.AdapterChanged(const AAdapter: IFDMoniAdapter); var oItem: TFDMoniRemoteClientQueueItem; hHandle: LongWord; V: Variant; i: Integer; sName: String; vValue: Variant; eKind: TFDMoniAdapterItemKind; begin if GetTracing then begin hHandle := AAdapter.GetHandle; if hHandle <> 0 then begin oItem := BuildItem(ptUpdateAdapter); oItem.FHandle := hHandle; V := VarArrayCreate([0, AAdapter.ItemCount * 3 - 1], varVariant); for i := 0 to AAdapter.ItemCount - 1 do begin AAdapter.GetItem(i, sName, vValue, eKind); V[i * 3 + 0] := sName; V[i * 3 + 1] := vValue; V[i * 3 + 2] := Byte(eKind); end; oItem.SetArgs(V); FQueue.PostItem(oItem); end; end; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.GetHost: String; begin Result := FSender.Host; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.SetHost(const AValue: String); begin FSender.Host := AValue; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.GetPort: Integer; begin Result := FSender.Port; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.SetPortI(const AValue: Integer); begin FSender.Port := AValue; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClient.GetTimeout: Integer; begin Result := FSender.Timeout; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClient.SetTimeout(const AValue: Integer); begin FSender.Timeout := AValue; end; {-------------------------------------------------------------------------------} { TFDMoniRemoteClientLink } {-------------------------------------------------------------------------------} constructor TFDMoniRemoteClientLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FRemoteClient := MoniClient as IFDMoniRemoteClient; Host := '127.0.0.1'; Port := C_FD_MonitorPort; Timeout := C_FD_MonitorTimeout; end; {-------------------------------------------------------------------------------} destructor TFDMoniRemoteClientLink.Destroy; begin FRemoteClient := nil; inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClientLink.GetMoniClient: IFDMoniClient; var oRemClient: IFDMoniRemoteClient; begin FDCreateInterface(IFDMoniRemoteClient, oRemClient); Result := oRemClient as IFDMoniClient; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClientLink.GetHost: String; begin Result := RemoteClient.Host; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClientLink.SetHost(const AValue: String); begin RemoteClient.Host := AValue; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClientLink.IsHS: Boolean; begin Result := FDMoniRemoteIsLocalHost(GetHost); end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClientLink.GetPort: Integer; begin Result := RemoteClient.Port; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClientLink.SetPortI(const AValue: Integer); begin RemoteClient.Port := AValue; end; {-------------------------------------------------------------------------------} function TFDMoniRemoteClientLink.GetTimeout: Integer; begin Result := RemoteClient.Timeout; end; {-------------------------------------------------------------------------------} procedure TFDMoniRemoteClientLink.SetTimeout(const AValue: Integer); begin RemoteClient.Timeout := AValue; end; {-------------------------------------------------------------------------------} procedure StopAllClients; var i: Integer; oClient: TFDMoniRemoteClient; begin for i := 0 to FClients.Count - 1 do begin oClient := TFDMoniRemoteClient(FClients[i]); oClient.FDestroying := True; oClient.SetTracing(False); end; end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization {$IFDEF MSWINDOWS} GWSAFailed := False; GWSAInitialized := False; {$ENDIF} FClients := TList.Create; oFact := TFDSingletonFactory.Create(TFDMoniRemoteClient, IFDMoniRemoteClient); finalization StopAllClients; FDFreeAndNil(FClients); {$IFDEF MSWINDOWS} if GWSAInitialized then WSACleanup; {$ENDIF} FDReleaseFactory(oFact); end.
{ *********************************************************************** } { } { SdCadMath unit } { } { Copyright (c) 2003 SD Software Corporation } { } {This unit is math unit for the project} { *********************************************************************** } unit SdCadMath; interface uses SysUtils,Math,public_unit; //取得样品数所对应的舍弃值的临界值 //公式:f(x)= (x-x1)/(x0-x1)*y0+(x-x0)/(x1-x0)*y1 function GetCriticalValue(aSampleNum: integer): double; //取得样品数所对应的标准值 //公式:f= 1- (1.704/sqrt(样本数) + 4.678/sqr(样本数)) *变异系数))) function GetBiaoZhunZhi(aSampleNum: integer; BianYiXiShu: double; PingJunZhi: double): double; //传进TAnalyzeResult变量,计算它的平均值、标准差、变异系数等特征值。 procedure GetTeZhengShu(var aAnalyzeResult : TAnalyzeResult; Flags: TTongJiFlags); //传进TAnalyzeResult变量,计算它的平均值、标准差、变异系数等特征值。 //此函数是为了物理力学统计时,静探数据不进行剔除,做了改动。2005/07/11 yys edit procedure GetTeZhengShuWLLX(var aAnalyzeResult : TAnalyzeResult); { *********************************************************************** } { 土分析分层总表,天然状态的基本物理指标计算和计算求得的可塑性指标的计算 } { *********************************************************************** } {GetGanMiDu: return干密度,AHanShuiLiang含水量,AShiMiDu湿密度, 干密度=湿密度/(1+0.01*含水量) } function GetGanMiDu(const AHanShuiLiang: double; const AShiMiDu: double): double; {GetKongXiBi: return孔隙比,ATuLiBiZhong土粒比重,AGanMiDu干密度,AShuiMiDu水的比重, 孔隙比=(土粒比重*水的比重)/干密度-1 } function GetKongXiBi(const ATuLiBiZhong: double; const AGanMiDu: double; const AShuiMiDu: double=1): double; {GetKongXiDu: return孔隙度,AKongXiBi孔隙比, 孔隙度=(100*孔隙比)/(1+孔隙比) } function GetKongXiDu(const AKongXiBi: double): double; {GetBaoHeDu: return饱合度,AHanShuiLiang含水量,ATuLiBiZhong土粒比重,AKongXiBi孔隙比, 饱合度=含水量*土粒比重/孔隙比} function GetBaoHeDu(const AHanShuiLiang: double; const ATuLiBiZhong: double; const AKongXiBi: double): double; {GetSuXingZhiShu: return塑性指数,AYeXian液限,ASuXian塑限, 塑性指数=液限-塑限} function GetSuXingZhiShu(const AYeXian: double; const ASuXian: double): double; {GetYeXingZhiShu: return液性指数,AHanShuiLiang含水量,ASuXian塑限,AYeXian液限, 液性指数=(含水量-塑限)/(液限-塑限)} function GetYeXingZhiShu(const AHanShuiLiang: double; const ASuXian: double;const AYeXian: double ): double; function getYaSuoXiShu(kxb_0,kxb_1,yali_0,yali_1:double):Double; function getYaSuoMoLiang(ChuShi_Kxb,YaSuoXiShu_i:double):Double; {******************************************************************} {**********数值算法************************************************} {******************************************************************} {XianXingChaZhi: 线形插值 公式:f(x)= (x-x1)/(x0-x1)*y0+(x-x0)/(x1-x0)*y1} function XianXingChaZhi(x0, y0, x1, y1, x: double): double; {ShuangXianXingChaZhi: 线形插值 公式:f(x)= (x-x1)/(x0-x1)*y0+(x-x0)/(x1-x0)*y1} function ShuangXianXingChaZhi(x0, y0, x1, y1, zx0y0,zx0y1, zx1y0, zx1y1, x, y: double): double; implementation uses MainDM; function GetGanMiDu(const AHanShuiLiang: double; const AShiMiDu: double): double; begin try result:= AShiMiDu / (1 + 0.01 * AHanShuiLiang); except result:= 0; end; end; function GetKongXiBi(const ATuLiBiZhong: double; const AGanMiDu: double; const AShuiMiDu: double=1): double; begin result:= ATuLiBiZhong * AShuiMiDu / AGanMiDu - 1; end; function GetKongXiDu(const AKongXiBi: double): double; begin result:=100 * AKongXiBi / (1 + AKongXiBi); end; function GetBaoHeDu(const AHanShuiLiang: double; const ATuLiBiZhong: double; const AKongXiBi: double): double; begin result:= AHanShuiLiang * ATuLiBiZhong / AKongXiBi; if result>100 then result:= 100; end; function GetSuXingZhiShu(const AYeXian: double; const ASuXian: double): double; begin result:= AYeXian - ASuXian; end; function GetYeXingZhiShu(const AHanShuiLiang: double; const ASuXian: double;const AYeXian: double ): double; begin result:= (AHanShuiLiang - ASuXian) / (AYeXian - ASuXian); end; function XianXingChaZhi(x0, y0, x1, y1, x: double): double; begin result:= (x - x1) / (x0 - x1) * y0 + (x - x0) / (x1-x0) * y1; end; function ShuangXianXingChaZhi(x0, y0, x1, y1, zx0y0,zx0y1, zx1y0, zx1y1, x, y: double): double; var tmpz0,tmpz1: double; begin tmpz0:= XianXingChaZhi(x0, zx0y0, x1, zx1y0, x); tmpz1:= XianXingChaZhi(x0, zx0y1, x1, zx1y1, x); result:= XianXingChaZhi(y0, tmpz0, y1, tmpz1, y); end; //取得样品数所对应的舍弃值的临界值 //公式:f(x)= (x-x1)/(x0-x1)*y0+(x-x0)/(x1-x0)*y1 function GetCriticalValue(aSampleNum: integer): double; var iNum: integer; x0,y0,x1,y1,tmpX,tmpY: double; begin x0:=0; y0:=0; with MainDataModule.qrySectionTotal do begin close; sql.Clear; sql.Add('SELECT yangpinshu,zhixinshuiping95 FROM CriticalValue'); open; iNum:= 0; while not eof do begin inc(iNum); tmpX:= FieldbyName('yangpinshu').AsInteger; tmpY:= FieldbyName('zhixinshuiping95').AsFloat; if aSampleNum= tmpX then begin result:= tmpY; close; exit; end; if iNum=1 then begin x0:= tmpX; y0:= tmpY; if aSampleNum<x0 then begin result:= tmpY; close; exit; end; end else begin if (aSampleNum<tmpX) then begin x1:=tmpX; y1:=tmpY; result:= StrToFloat(formatfloat('0.00',XianXingChaZhi(x0, y0, x1, y1, aSampleNum))); close; exit; end else begin x0:= tmpX; y0:= tmpY; end; end; next; end; close; end; result:= y0; end; //取得样品数所对应的标准值 //公式:f= 1- (1.704/sqrt(样本数) + 4.678/sqr(样本数)) *变异系数))) function GetBiaoZhunZhi(aSampleNum: integer; BianYiXiShu: double; PingJunZhi: double): double; begin result := (1- (1.704/sqrt(aSampleNum) + 4.678/sqr(aSampleNum)) * BianYiXiShu )* PingJunZhi; end; //传进TAnalyzeResult变量,计算它的平均值、标准差、变异系数等特征值。 procedure GetTeZhengShu(var aAnalyzeResult : TAnalyzeResult; Flags: TTongJiFlags); var i,iCount,iFirst,iMax:integer; dTotal,dValue,dTotalFangCha,dCriticalValue:double; strValue: string; //计算临界值 function CalculateCriticalValue(aValue, aPingjunZhi, aBiaoZhunCha: double): double; begin if aBiaoZhunCha = 0 then begin result:= 0; exit; end; result := (aValue - aPingjunZhi) / aBiaoZhunCha; end; begin iMax:=0; dTotal:= 0; iFirst:= 0; dTotalFangCha:=0; //yys 2005/06/15 // aAnalyzeResult.PingJunZhi := 0; // aAnalyzeResult.BiaoZhunCha := 0; // aAnalyzeResult.BianYiXiShu := 0; // aAnalyzeResult.MaxValue := 0; // aAnalyzeResult.MinValue := 0; // aAnalyzeResult.SampleNum := 0; aAnalyzeResult.PingJunZhi := -1; aAnalyzeResult.BiaoZhunCha := -1; aAnalyzeResult.BianYiXiShu := -1; aAnalyzeResult.MaxValue := -1; aAnalyzeResult.MinValue := -1; aAnalyzeResult.SampleNum := -1; aAnalyzeResult.BiaoZhunZhi := -1; if aAnalyzeResult.lstValues.Count<1 then exit; strValue := ''; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do strValue:=strValue + aAnalyzeResult.lstValues.Strings[i]; strValue := trim(strValue); if strValue='' then exit; //yys 2005/06/15 iCount:= aAnalyzeResult.lstValues.Count; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do begin strValue:=aAnalyzeResult.lstValues.Strings[i]; if strValue='' then begin iCount:=iCount-1; end else begin inc(iFirst); dValue:= StrToFloat(strValue); if iFirst=1 then begin aAnalyzeResult.MinValue:= dValue; aAnalyzeResult.MaxValue:= dValue; iMax := i; end else begin if aAnalyzeResult.MinValue>dValue then begin aAnalyzeResult.MinValue:= dValue; end; if aAnalyzeResult.MaxValue<dValue then begin aAnalyzeResult.MaxValue:= dValue; iMax := i; end; end; dTotal:= dTotal + dValue; end; end; //dTotal:= dTotal - aAnalyzeResult.MinValue - aAnalyzeResult.MaxValue; //iCount := iCount - 2; if iCount>=1 then aAnalyzeResult.PingJunZhi := dTotal/iCount else aAnalyzeResult.PingJunZhi := dTotal; //aAnalyzeResult.lstValues.Strings[iMin]:= ''; //aAnalyzeResult.lstValues.Strings[iMax]:= ''; //iCount:= aAnalyzeResult.lstValues.Count; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do begin strValue:=aAnalyzeResult.lstValues.Strings[i]; if strValue<>'' then begin dValue := StrToFloat(strValue); dTotalFangCha := dTotalFangCha + sqr(dValue-aAnalyzeResult.PingJunZhi); end //else iCount:= iCount -1; end; if iCount>1 then dTotalFangCha:= dTotalFangCha/(iCount-1); aAnalyzeResult.SampleNum := iCount; if iCount >1 then aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha) else aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha); if not iszero(aAnalyzeResult.PingJunZhi) then begin //yys edit 2012/02/24 //勘察院要求变异系统除了原本是3位小数的,其他都按2位小数来做 //aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat( //aAnalyzeResult.FormatString,aAnalyzeResult.BiaoZhunCha / //aAnalyzeResult.PingJunZhi)) if aAnalyzeResult.FormatString<>'0.000' then aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat( '0.00',aAnalyzeResult.BiaoZhunCha / aAnalyzeResult.PingJunZhi)) else aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat('0.00',aAnalyzeResult.BiaoZhunCha / aAnalyzeResult.PingJunZhi)) end else aAnalyzeResult.BianYiXiShu:= 0; if tfTeShuYang in Flags then begin //2011/03/09 勘察院修改要求,所有字段都要加上标准差和变异系数 //aAnalyzeResult.BiaoZhunCha := -1; //aAnalyzeResult.BianYiXiShu := -1; end; //yys edit 2009/12/29工勘院修改要求,只有土样的凝聚力和摩擦角(这两种在另外的函数GetTeZhengShuGuanLian中计算)还有非土样的标贯、静探需要计算标准值,其他都不在计算标准值,同时报表上这些不要计算标准值的要空白显示。 if (iCount>=6) and ((tfJingTan in Flags) or (tfBiaoGuan in Flags) or(tfTeShuYangBiaoZhuZhi in Flags)) then aAnalyzeResult.BiaoZhunZhi := GetBiaoZhunZhi(aAnalyzeResult.SampleNum , aAnalyzeResult.BianYiXiShu, aAnalyzeResult.PingJunZhi); dValue:= CalculateCriticalValue(aAnalyzeResult.MaxValue, aAnalyzeResult.PingJunZhi,aAnalyzeResult.BiaoZhunCha); dCriticalValue := GetCriticalValue(iCount); //2005/07/25 yys edit 土样数据剔除时,到6个样就不再剔除,剔除时要先剔除最大的数据 if tfTuYang in Flags then if (iCount> 6) AND (dValue > dCriticalValue) then begin aAnalyzeResult.lstValues.Strings[iMax]:= ''; if aAnalyzeResult.lstValuesForPrint.Strings[iMax]<>'' then aAnalyzeResult.lstValuesForPrint.Strings[iMax]:= AddFuHao(aAnalyzeResult.lstValuesForPrint.Strings[iMax]); GetTeZhengShu(aAnalyzeResult, Flags); end else if tfJingTan in Flags then //静探不剔除数据 tfOther也不剔除 else if tfBiaoGuan in Flags then if dValue > dCriticalValue then begin aAnalyzeResult.lstValues.Strings[iMax]:= ''; aAnalyzeResult.lstValuesForPrint.Strings[iMax]:= '-' +aAnalyzeResult.lstValuesForPrint.Strings[iMax]; GetTeZhengShu(aAnalyzeResult, Flags); end; //yys 2005/06/15 add, 当一层只有一个样时,标准差和变异系数不能为0,打印报表时要用空格,物理力学表也一样。所以用-1来表示空值,是因为在报表设计时可以通过判断来表示为空。 if iCount=1 then begin //aAnalyzeResult.strBianYiXiShu := 'null'; //aAnalyzeResult.strBiaoZhunCha := 'null'; aAnalyzeResult.BianYiXiShu := -1; aAnalyzeResult.BiaoZhunCha := -1; aAnalyzeResult.BiaoZhunZhi := -1; end else begin //aAnalyzeResult.strBianYiXiShu := FloatToStr(aAnalyzeResult.BianYiXiShu); // aAnalyzeResult.strBiaoZhunCha := FloatToStr(aAnalyzeResult.BiaoZhunCha); end; //yys 2005/06/15 add end; //传进TAnalyzeResult变量,计算它的平均值、标准差、变异系数等特征值。 procedure GetTeZhengShuWLLX(var aAnalyzeResult : TAnalyzeResult); var i,iCount,iFirst:integer; dTotal,dValue,dTotalFangCha:double; strValue: string; //计算临界值 function CalculateCriticalValue(aValue, aPingjunZhi, aBiaoZhunCha: double): double; begin if aBiaoZhunCha = 0 then begin result:= 0; exit; end; result := (aValue - aPingjunZhi) / aBiaoZhunCha; end; begin dTotal:= 0; iFirst:= 0; dTotalFangCha:=0; //yys 2005/06/15 // aAnalyzeResult.PingJunZhi := 0; // aAnalyzeResult.BiaoZhunCha := 0; // aAnalyzeResult.BianYiXiShu := 0; // aAnalyzeResult.MaxValue := 0; // aAnalyzeResult.MinValue := 0; // aAnalyzeResult.SampleNum := 0; aAnalyzeResult.PingJunZhi := -1; aAnalyzeResult.BiaoZhunCha := -1; aAnalyzeResult.BianYiXiShu := -1; aAnalyzeResult.MaxValue := -1; aAnalyzeResult.MinValue := -1; aAnalyzeResult.SampleNum := -1; aAnalyzeResult.BiaoZhunZhi := -1; if aAnalyzeResult.lstValues.Count<1 then exit; strValue := ''; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do strValue:=strValue + aAnalyzeResult.lstValues.Strings[i]; strValue := trim(strValue); if strValue='' then exit; //yys 2005/06/15 iCount:= aAnalyzeResult.lstValues.Count; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do begin strValue:=aAnalyzeResult.lstValues.Strings[i]; if strValue='' then begin iCount:=iCount-1; end else begin inc(iFirst); dValue:= StrToFloat(strValue); if iFirst=1 then begin aAnalyzeResult.MinValue:= dValue; aAnalyzeResult.MaxValue:= dValue; end else begin if aAnalyzeResult.MinValue>dValue then begin aAnalyzeResult.MinValue:= dValue; end; if aAnalyzeResult.MaxValue<dValue then begin aAnalyzeResult.MaxValue:= dValue; end; end; dTotal:= dTotal + dValue; end; end; //dTotal:= dTotal - aAnalyzeResult.MinValue - aAnalyzeResult.MaxValue; //iCount := iCount - 2; if iCount>=1 then aAnalyzeResult.PingJunZhi := dTotal/iCount else aAnalyzeResult.PingJunZhi := dTotal; //aAnalyzeResult.lstValues.Strings[iMin]:= ''; //aAnalyzeResult.lstValues.Strings[iMax]:= ''; //iCount:= aAnalyzeResult.lstValues.Count; for i:= 0 to aAnalyzeResult.lstValues.Count-1 do begin strValue:=aAnalyzeResult.lstValues.Strings[i]; if strValue<>'' then begin dValue := StrToFloat(strValue); dTotalFangCha := dTotalFangCha + sqr(dValue-aAnalyzeResult.PingJunZhi); end //else iCount:= iCount -1; end; if iCount>1 then dTotalFangCha:= dTotalFangCha/(iCount-1); aAnalyzeResult.SampleNum := iCount; if iCount >1 then aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha) else aAnalyzeResult.BiaoZhunCha := sqrt(dTotalFangCha); if not iszero(aAnalyzeResult.PingJunZhi) then aAnalyzeResult.BianYiXiShu := strtofloat(formatfloat(aAnalyzeResult.FormatString,aAnalyzeResult.BiaoZhunCha / aAnalyzeResult.PingJunZhi)) else aAnalyzeResult.BianYiXiShu:= 0; if iCount>=6 then aAnalyzeResult.BiaoZhunZhi := GetBiaoZhunZhi(aAnalyzeResult.SampleNum , aAnalyzeResult.BianYiXiShu, aAnalyzeResult.PingJunZhi); // dValue:= CalculateCriticalValue(aAnalyzeResult.MaxValue, aAnalyzeResult.PingJunZhi,aAnalyzeResult.BiaoZhunCha); // dCriticalValue := GetCriticalValue(iCount); // if dValue > dCriticalValue then // begin // aAnalyzeResult.lstValues.Strings[iMax]:= ''; // GetTeZhengShuWLLX(aAnalyzeResult); // end; //yys 2005/06/15 add, 当一层只有一个样时,标准差和变异系数不能为0,打印报表时要用空格,物理力学表也一样。所以用-1来表示空值,是因为在报表设计时可以通过判断来表示为空。 if iCount=1 then begin //aAnalyzeResult.strBianYiXiShu := 'null'; //aAnalyzeResult.strBiaoZhunCha := 'null'; aAnalyzeResult.BianYiXiShu := -1; aAnalyzeResult.BiaoZhunCha := -1; end else begin //aAnalyzeResult.strBianYiXiShu := FloatToStr(aAnalyzeResult.BianYiXiShu); // aAnalyzeResult.strBiaoZhunCha := FloatToStr(aAnalyzeResult.BiaoZhunCha); end; //yys 2005/06/15 add end; function getYaSuoXiShu(kxb_0,kxb_1,yali_0,yali_1:double):Double; begin Result := (kxb_0-kxb_1)/(yali_1/1000-yali_0/1000); end; function getYaSuoMoLiang(ChuShi_Kxb,YaSuoXiShu_i:double):Double; begin Result := (1+ChuShi_Kxb)/YaSuoXiShu_i; end; end.
PROGRAM RosettaIsaac; USES StrUtils; TYPE iMode = (iEncrypt, iDecrypt); // TASK globals VAR msg : String = 'a Top Secret secret'; key : String = 'this is my secret key'; xctx: String = ''; // XOR ciphertext mctx: String = ''; // MOD ciphertext xptx: String = ''; // XOR decryption (plaintext) mptx: String = ''; // MOD decryption (plaintext) // ISAAC globals VAR // external results randrsl: ARRAY[0 .. 255] OF Cardinal; randcnt: Cardinal; // internal state mm: ARRAY[0 .. 255] OF Cardinal; aa: Cardinal = 0; bb: Cardinal = 0; cc: Cardinal = 0; PROCEDURE Isaac; VAR i, x, y: Cardinal; BEGIN 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 END; // Isaac PROCEDURE Mix(VAR a, b, c, d, e, f, g, h: Cardinal); 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; // Mix PROCEDURE iRandInit(flag: Boolean); VAR i, a, b, c, d, e, f, g, h: Cardinal; 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 IF flag THEN BEGIN // use all the information in the seed 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]; END; 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; IF flag THEN BEGIN // 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; END; Isaac(); // fill in the first set of results randcnt := 0; // prepare to use the first set of results END; // iRandInit // Seed ISAAC with a given string. // The string can be any size. The first 256 values will be used. PROCEDURE iSeed(seed: String; flag: Boolean); VAR i, m: Cardinal; BEGIN FOR i := 0 TO 255 DO mm[i] := 0; m := Length(seed) - 1; FOR i := 0 TO 255 DO BEGIN // in case seed has less than 256 elements IF i > m THEN randrsl[i] := 0 // Pascal strings are 1-based ELSE randrsl[i] := Ord(seed[i + 1]); END; // initialize ISAAC with seed iRandInit(flag); END; // iSeed // Get a random 32-bit value 0..MAXINT FUNCTION iRandom: Cardinal; 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 iRandA: Byte; BEGIN iRandA := iRandom MOD 95 + 32; END; // Convert an ASCII string to a hexadecimal string FUNCTION Ascii2Hex(s: String): String; VAR i: Cardinal; BEGIN Ascii2Hex := ''; FOR i := 1 TO Length(s) DO Ascii2Hex += Dec2Numb(Ord(s[i]), 2, 16); END; // Ascii2Hex // XOR encrypt on random stream. Output: ASCII string FUNCTION Vernam(msg: String): String; VAR i: Cardinal; BEGIN Vernam := ''; FOR i := 1 to Length(msg) DO Vernam += Chr(iRandA XOR Ord(msg[i])); END; // Vernam // Get position of the letter in chosen alphabet FUNCTION LetterNum(letter, start: Char): Byte; BEGIN LetterNum := (Ord(letter) - Ord(start)); END; // LetterNum // Caesar-shift a character <shift> places: Generalized Vigenere FUNCTION Caesar(m: iMode; ch: Char; shift, modulo: Integer; start: Char): Char; VAR n: Integer; BEGIN IF m = iDecrypt THEN shift := -shift; n := LetterNum(ch, start) + shift; n := n MOD modulo; IF n < 0 THEN n += modulo; Caesar := Chr(Ord(start) + n); END; // Caesar // Vigenere MOD 95 encryption & decryption. Output: ASCII string FUNCTION Vigenere(msg: String; m: iMode): String; VAR i: Cardinal; BEGIN Vigenere := ''; FOR i := 1 to Length(msg) DO Vigenere += Caesar(m, msg[i], iRandA, 95, ' '); END; // Vigenere BEGIN // 1) seed ISAAC with the key iSeed(key, true); // 2) Encryption // a) XOR (Vernam) xctx := Vernam(msg); // b) MOD (Vigenere) mctx := Vigenere(msg, iEncrypt); // 3) Decryption iSeed(key, true); // a) XOR (Vernam) xptx := Vernam(xctx); // b) MOD (Vigenere) mptx := Vigenere(mctx, iDecrypt); // program output Writeln('Message: ', msg); Writeln('Key : ', key); Writeln('XOR : ', Ascii2Hex(xctx)); Writeln('MOD : ', Ascii2Hex(mctx)); Writeln('XOR dcr: ', xptx); Writeln('MOD dcr: ', mptx); END.
unit IdIMAP4Server; interface uses Classes, IdGlobal, IdTCPServer; const IMAPCommands: array[1..25] of string = ({ Client Commands - Any State} 'CAPABILITY', 'NOOP', 'LOGOUT', { Client Commands - Non Authenticated State} 'AUTHENTICATE', 'LOGIN', { Client Commands - Authenticated State} 'SELECT', 'EXAMINE', 'CREATE', 'DELETE', 'RENAME', 'SUBSCRIBE', 'UNSUBSCRIBE', 'LIST', 'LSUB', 'STATUS', 'APPEND', { Client Commands - Selected State} 'CHECK', 'CLOSE', 'EXPUNGE', 'SEARCH', 'FETCH', 'STORE', 'COPY', 'UID', { Client Commands - Experimental/ Expansion} 'X'); type TCommandEvent = procedure(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean) of object; TIdIMAP4Server = class(TIdTCPServer) protected fOnCommandCAPABILITY: TCommandEvent; fONCommandNOOP: TCommandEvent; fONCommandLOGOUT: TCommandEvent; fONCommandAUTHENTICATE: TCommandEvent; fONCommandLOGIN: TCommandEvent; fONCommandSELECT: TCommandEvent; fONCommandEXAMINE: TCommandEvent; fONCommandCREATE: TCommandEvent; fONCommandDELETE: TCommandEvent; fONCommandRENAME: TCommandEvent; fONCommandSUBSCRIBE: TCommandEvent; fONCommandUNSUBSCRIBE: TCommandEvent; fONCommandLIST: TCommandEvent; fONCommandLSUB: TCommandEvent; fONCommandSTATUS: TCommandEvent; fONCommandAPPEND: TCommandEvent; fONCommandCHECK: TCommandEvent; fONCommandCLOSE: TCommandEvent; fONCommandEXPUNGE: TCommandEvent; fONCommandSEARCH: TCommandEvent; fONCommandFETCH: TCommandEvent; fONCommandSTORE: TCommandEvent; fONCommandCOPY: TCommandEvent; fONCommandUID: TCommandEvent; fONCommandX: TCommandEvent; fOnCommandError: TCommandEvent; procedure DoCommandCAPABILITY(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandNOOP(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandLOGOUT(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandAUTHENTICATE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandLOGIN(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandSELECT(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandEXAMINE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandCREATE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandDELETE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandRENAME(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandSUBSCRIBE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandUNSUBSCRIBE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandLIST(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandLSUB(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandSTATUS(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandAPPEND(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandCHECK(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandCLOSE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandEXPUNGE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandSEARCH(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandFETCH(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandSTORE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandCOPY(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandUID(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandX(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); procedure DoCommandError(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); function DoExecute(Thread: TIdPeerThread): Boolean; override; public constructor Create(AOwner: TComponent); override; published property ONCommandCAPABILITY: TCommandEvent read fOnCommandCAPABILITY write fOnCommandCAPABILITY; property ONCommandNOOP: TCommandEvent read fONCommandNOOP write fONCommandNOOP; property ONCommandLOGOUT: TCommandEvent read fONCommandLOGOUT write fONCommandLOGOUT; property ONCommandAUTHENTICATE: TCommandEvent read fONCommandAUTHENTICATE write fONCommandAUTHENTICATE; property ONCommandLOGIN: TCommandEvent read fONCommandLOGIN write fONCommandLOGIN; property ONCommandSELECT: TCommandEvent read fONCommandSELECT write fONCommandSELECT; property OnCommandEXAMINE: TCommandEvent read fOnCommandEXAMINE write fOnCommandEXAMINE; property ONCommandCREATE: TCommandEvent read fONCommandCREATE write fONCommandCREATE; property ONCommandDELETE: TCommandEvent read fONCommandDELETE write fONCommandDELETE; property OnCommandRENAME: TCommandEvent read fOnCommandRENAME write fOnCommandRENAME; property ONCommandSUBSCRIBE: TCommandEvent read fONCommandSUBSCRIBE write fONCommandSUBSCRIBE; property ONCommandUNSUBSCRIBE: TCommandEvent read fONCommandUNSUBSCRIBE write fONCommandUNSUBSCRIBE; property ONCommandLIST: TCommandEvent read fONCommandLIST write fONCommandLIST; property OnCommandLSUB: TCommandEvent read fOnCommandLSUB write fOnCommandLSUB; property ONCommandSTATUS: TCommandEvent read fONCommandSTATUS write fONCommandSTATUS; property OnCommandAPPEND: TCommandEvent read fOnCommandAPPEND write fOnCommandAPPEND; property ONCommandCHECK: TCommandEvent read fONCommandCHECK write fONCommandCHECK; property OnCommandCLOSE: TCommandEvent read fOnCommandCLOSE write fOnCommandCLOSE; property ONCommandEXPUNGE: TCommandEvent read fONCommandEXPUNGE write fONCommandEXPUNGE; property OnCommandSEARCH: TCommandEvent read fOnCommandSEARCH write fOnCommandSEARCH; property ONCommandFETCH: TCommandEvent read fONCommandFETCH write fONCommandFETCH; property OnCommandSTORE: TCommandEvent read fOnCommandSTORE write fOnCommandSTORE; property OnCommandCOPY: TCommandEvent read fOnCommandCOPY write fOnCommandCOPY; property ONCommandUID: TCommandEvent read fONCommandUID write fONCommandUID; property OnCommandX: TCommandEvent read fOnCommandX write fOnCommandX; property OnCommandError: TCommandEvent read fOnCommandError write fOnCommandError; property DefaultPort default IdPORT_IMAP4; end; implementation uses SysUtils; const cCAPABILITY = 1; cNOOP = 2; cLOGOUT = 3; cAUTHENTICATE = 4; cLOGIN = 5; cSELECT = 6; cEXAMINE = 7; cCREATE = 8; cDELETE = 9; cRENAME = 10; cSUBSCRIBE = 11; cUNSUBSCRIBE = 12; cLIST = 13; cLSUB = 14; cSTATUS = 15; cAPPEND = 16; cCHECK = 17; cCLOSE = 18; cEXPUNGE = 19; cSEARCH = 20; cFETCH = 21; cSTORE = 22; cCOPY = 23; cUID = 24; cXCmd = 25; constructor TIdIMAP4Server.Create(AOwner: TComponent); begin inherited; DefaultPort := IdPORT_IMAP4; end; function TIdIMAP4Server.DoExecute(Thread: TIdPeerThread): Boolean; var RcvdStr, ArgStr, sTag, sCmd: string; cmdNum: Integer; Handled: Boolean; function GetFirstTokenDeleteFromArg(var s1: string; const sDelim: string): string; var nPos: Integer; begin nPos := IndyPos(sDelim, s1); if nPos = 0 then begin nPos := Length(s1) + 1; end; Result := Copy(s1, 1, nPos - 1); Delete(s1, 1, nPos); S1 := Trim(S1); end; begin result := true; while Thread.Connection.Connected do begin Handled := False; RcvdStr := Thread.Connection.ReadLn; ArgStr := RcvdStr; sTag := UpperCase(GetFirstTokenDeleteFromArg(ArgStr, CHAR32)); sCmd := UpperCase(GetFirstTokenDeleteFromArg(ArgStr, CHAR32)); CmdNum := Succ(PosInStrArray(Uppercase(sCmd), IMAPCommands)); case CmdNum of cCAPABILITY: DoCommandCAPABILITY(Thread, sTag, ArgStr, Handled); cNOOP: DoCommandNOOP(Thread, sTag, ArgStr, Handled); cLOGOUT: DoCommandLOGOUT(Thread, sTag, ArgStr, Handled); cAUTHENTICATE: DoCommandAUTHENTICATE(Thread, sTag, ArgStr, Handled); cLOGIN: DoCommandLOGIN(Thread, sTag, ArgStr, Handled); cSELECT: DoCommandSELECT(Thread, sTag, ArgStr, Handled); cEXAMINE: DoCommandEXAMINE(Thread, sTag, ArgStr, Handled); cCREATE: DoCommandCREATE(Thread, sTag, ArgStr, Handled); cDELETE: DoCommandDELETE(Thread, sTag, ArgStr, Handled); cRENAME: DoCommandRENAME(Thread, sTag, ArgStr, Handled); cSUBSCRIBE: DoCommandSUBSCRIBE(Thread, sTag, ArgStr, Handled); cUNSUBSCRIBE: DoCommandUNSUBSCRIBE(Thread, sTag, ArgStr, Handled); cLIST: DoCommandLIST(Thread, sTag, ArgStr, Handled); cLSUB: DoCommandLSUB(Thread, sTag, ArgStr, Handled); cSTATUS: DoCommandSTATUS(Thread, sTag, ArgStr, Handled); cAPPEND: DoCommandAPPEND(Thread, sTag, ArgStr, Handled); cCHECK: DoCommandCHECK(Thread, sTag, ArgStr, Handled); cCLOSE: DoCommandCLOSE(Thread, sTag, ArgStr, Handled); cEXPUNGE: DoCommandEXPUNGE(Thread, sTag, ArgStr, Handled); cSEARCH: DoCommandSEARCH(Thread, sTag, ArgStr, Handled); cFETCH: DoCommandFETCH(Thread, sTag, ArgStr, Handled); cSTORE: DoCommandSTORE(Thread, sTag, ArgStr, Handled); cCOPY: DoCommandCOPY(Thread, sTag, ArgStr, Handled); cUID: DoCommandUID(Thread, sTag, ArgStr, Handled); else begin if (Length(SCmd) > 0) and (UpCase(SCmd[1]) = 'X') then begin DoCommandX(Thread, sTag, ArgStr, Handled); end else begin DoCommandError(Thread, sTag, ArgStr, Handled); end; end; end; end; end; procedure TIdIMAP4Server.DoCommandCapability(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fOnCommandCAPABILITY) then begin OnCommandCAPABILITY(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandNOOP(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandNOOP) then begin OnCommandNOOP(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandLOGOUT(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandLOGOUT) then begin OnCommandLOGOUT(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandAUTHENTICATE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandAUTHENTICATE) then begin OnCommandAUTHENTICATE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandLOGIN(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandLOGIN) then begin OnCommandLOGIN(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandSELECT(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandSELECT) then begin OnCommandSELECT(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandEXAMINE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandEXAMINE) then begin OnCommandEXAMINE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandCREATE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandCREATE) then begin OnCommandCREATE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandDELETE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandDELETE) then begin OnCommandDELETE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandRENAME(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandRENAME) then begin OnCommandRENAME(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandSUBSCRIBE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandSUBSCRIBE) then begin OnCommandSUBSCRIBE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandUNSUBSCRIBE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandUNSUBSCRIBE) then begin OnCommandUNSUBSCRIBE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandLIST(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandLIST) then begin OnCommandLIST(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandLSUB(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandLSUB) then begin OnCommandLSUB(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandSTATUS(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandSTATUS) then begin OnCommandSTATUS(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandAPPEND(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandAPPEND) then begin OnCommandAPPEND(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandCHECK(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandCHECK) then begin OnCommandCHECK(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandCLOSE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandCLOSE) then begin OnCommandCLOSE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandEXPUNGE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandEXPUNGE) then begin OnCommandEXPUNGE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandSEARCH(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandSEARCH) then begin OnCommandSEARCH(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandFETCH(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandFETCH) then begin OnCommandFETCH(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandSTORE(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandSTORE) then begin OnCommandSTORE(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandCOPY(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandCOPY) then begin OnCommandCOPY(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandUID(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandUID) then begin OnCommandUID(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandX(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandX) then begin OnCommandX(Thread, Tag, CmdStr, Handled); end; end; procedure TIdIMAP4Server.DoCommandError(Thread: TIdPeerThread; const Tag, CmdStr: string; var Handled: Boolean); begin if Assigned(fONCommandError) then begin OnCommandError(Thread, Tag, CmdStr, Handled); end; end; end.
unit range_expr_5; interface implementation var G1, G2: Boolean; function InRange(Value: Int32; LoBound, HiBound: Int32): Boolean; begin Result := Value in LoBound..HiBound; end; procedure Test; begin G1 := InRange(6, 0, 5); G1 := InRange(2, 1, 6); end; initialization Test(); finalization Assert(G1 = True); Assert(G2 = False); end.
Unit BaseObject_f_MeasuringSystem; Interface Uses BaseObject_c; // Function BaseObjectMeasuringSystemAngleToInternalUnit(Angle: Double): TBaseObjectDataContainerS; Function BaseObjectMeasuringSystemMilliMeterToInternalUnit(MilliMeter: Double): TBaseObjectDataContainerS; Function BaseObjectMeasuringSystemOhmMeterToInternalUnit(OhmMeter: Double): TBaseObjectDataContainerS; Function BaseObjectMeasuringSystemRelativePermittivityUnitToInternalUnit(RelativePermittivity: Double): TBaseObjectDataContainerS; // Implementation Uses BaseObject_c_MeasuringSystem; // Function BaseObjectMeasuringSystemAngleToInternalUnit(Angle: Double): TBaseObjectDataContainerS; Begin If (Angle >= 0) Then Begin While (Angle >= 180) Do Begin Angle := Angle - 360; End; End Else Begin While (Angle < -180) Do Begin Angle := Angle + 360; End; End; result := Round(Angle * coBaseObjectMeasuringSystemInternalUnitsPerOneDegree); End; // Function BaseObjectMeasuringSystemMilliMeterToInternalUnit(MilliMeter: Double): TBaseObjectDataContainerS; Begin result := Round(MilliMeter * coBaseObjectMeasuringSystemInternalUnitsPerOneMeter); End; // Function BaseObjectMeasuringSystemOhmMeterToInternalUnit(OhmMeter: Double): TBaseObjectDataContainerS; Begin result := Round(OhmMeter * coBaseObjectMeasuringSystemInternalUnitsPerOneOhmMeter); End; // Function BaseObjectMeasuringSystemRelativePermittivityUnitToInternalUnit(RelativePermittivity: Double): TBaseObjectDataContainerS; Begin result := Round(RelativePermittivity * coBaseObjectMeasuringSystemInternalUnitsPerOneRelativePermittivityUnit); End; // 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 //------------------------------------------------------------------------------ //单元说明: // EasyPlate程序的服务端单元 //主要实现: // 服务端数据模块 //+ 2011-01-07 此模块要在程序初始化或单元初始化时手工添加创建 //-----------------------------------------------------------------------------} unit untRDMEasyPlateServer; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr, DBClient, EasyPlateServer_TLB, StdVcl, DB, ADODB, Provider, MConnect, ObjBrkr, IniFiles, untEasyUtilRWIni, ActiveX, Forms, SyncObjs, AppEvnts; type TRDMEasyPlateServer = class(TRemoteDataModule, IRDMEasyPlateServer) EasyRDMADOConn: TADOConnection; EasyRDMQry: TADOQuery; EasyRDMDsp: TDataSetProvider; EasyRDMCds: TClientDataSet; EasyRDMDsp_Update: TDataSetProvider; EasyRDMQry_Update: TADOQuery; EasyRDMCds_Update: TClientDataSet; EasyRDMDsp_WhereAll: TDataSetProvider; EasyRDMQry_WhereAll: TADOQuery; EasyRDMCds_WhereAll: TClientDataSet; dspTable: TDataSetProvider; cdsTable: TClientDataSet; QryTable: TADOQuery; ApplicationEvents1: TApplicationEvents; cdsError: TClientDataSet; cdsSaveDetailMessage: TClientDataSet; procedure RemoteDataModuleCreate(Sender: TObject); procedure RemoteDataModuleDestroy(Sender: TObject); procedure EasyRDMDspUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); procedure EasyRDMDspBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); procedure EasyRDMQryPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure EasyRDMQryEditError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure EasyRDMQryDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); procedure ApplicationEvents1Exception(Sender: TObject; E: Exception); private { Private declarations } // FTableName, FConnectString: string; //服务器地址、用户名、密码、数据库、端口 FDBHost, FDBUserName, FDBPassWord, FDBDataBase, FDBPort : string; //读取配置文件信息 procedure LoadConnectString; //打开ADOConnection function OpenEasyADOConnection(): Integer; procedure SetDBDataBase(const Value: string); procedure SetDBHost(const Value: string); procedure SetDBPassWord(const Value: string); procedure SetDBPort(const Value: string); procedure SetDBUserName(const Value: string); // 手工加入 function InnerGetData(strSQL: String): OleVariant; function InnerPostData(Delta: OleVariant; out ErrorCode: Integer): OleVariant; //获取当前操作时间 function GetOperTime: string; protected class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override; function EasyGetRDMData(const ASQL: WideString): OleVariant; safecall; function EasySaveRDMData(const ATableName: WideString; ADelta: OleVariant; const AKeyField: WideString; out AErrorCode: SYSINT): OleVariant; safecall; function EasySaveRDMDatas(ATableNameOLE, ADeltaOLE, AKeyFieldOLE, ACodeErrorOLE: OleVariant): OleVariant; safecall; function EasyGetRDMDatas(ASQLOLE: OleVariant): OleVariant; safecall; public { Public declarations } Params : OleVariant; OwnerData: OleVariant; //服务器地址、用户名、密码、数据库、端口 property EasyDBHost: string read FDBHost write SetDBHost; property EasyDBUserName: string read FDBUserName write SetDBUserName; property EasyDBPassWord: string read FDBPassWord write SetDBPassWord; property EasyDBDataBase: string read FDBDataBase write SetDBDataBase; property EasyDBPort: string read FDBPort write SetDBPort; procedure AddExecLog(ALogStr: string; AType: Integer = 0); end; var { Need a reference to the ClassFactory so the pooler can create instances of the class. } RDMFactory: TComponentFactory; RDMEasyPlateServer: TRDMEasyPlateServer; implementation uses untEasyPlateServerMain, Variants, untEasyUtilMethod, untEasyUtilConst; {$R *.DFM} var TableCachePath: WideString; class procedure TRDMEasyPlateServer.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); begin if Register then begin inherited UpdateRegistry(Register, ClassID, ProgID); EnableSocketTransport(ClassID); EnableWebTransport(ClassID); end else begin DisableSocketTransport(ClassID); DisableWebTransport(ClassID); inherited UpdateRegistry(Register, ClassID, ProgID); end; end; procedure TRDMEasyPlateServer.RemoteDataModuleCreate(Sender: TObject); var TmpPath: WideString; begin //调整查询缓存大小 EasyRDMQry.CacheSize :=1000; //设置EasyRDMDsp可远程执行SQL语句 EasyRDMDsp.Options := EasyRDMDsp.Options + [poAllowCommandText]; //DataProvider只按主键更新 EasyRDMDsp.UpdateMode := upWhereKeyOnly; //先初始化数据库配置 LoadConnectString; //打开数据连接 OpenEasyADOConnection(); PostMessage(frmEasyPlateServerMain.Handle, WM_USER + 99, 0, 0); //表缓存路径 TmpPath := ExtractFilePath(Application.ExeName) + 'Cache\Table\'; if not DirectoryExists(TmpPath) then ForceDirectories(TmpPath); TableCachePath := TmpPath; end; procedure TRDMEasyPlateServer.SetDBDataBase(const Value: string); begin FDBDataBase := Value; end; procedure TRDMEasyPlateServer.SetDBHost(const Value: string); begin FDBHost := Value; end; procedure TRDMEasyPlateServer.SetDBPassWord(const Value: string); begin FDBPassWord := Value; end; procedure TRDMEasyPlateServer.SetDBPort(const Value: string); begin FDBPort := Value; end; procedure TRDMEasyPlateServer.SetDBUserName(const Value: string); begin FDBUserName := Value; end; function TRDMEasyPlateServer.OpenEasyADOConnection(): Integer; begin Result := 0; if EasyRDMADOConn.Connected then EasyRDMADOConn.Close; EasyRDMADOConn.LoginPrompt := False; EasyRDMADOConn.ConnectionString := ''; begin EasyRDMADOConn.ConnectionString := FConnectString; try EasyRDMADOConn.Open; EasyDBHost := EasyRDMADOConn.Properties.Item['Data Source'].Value; EasyDBDataBase := EasyRDMADOConn.Properties.Item['Initial Catalog'].Value; EasyDBUserName := EasyRDMADOConn.Properties.Item['User ID'].Value; except on e: Exception do begin Application.MessageBox(PChar(EASY_DB_CONNECT_ERROR + e.Message), EASY_SYS_ERROR, MB_OK + MB_ICONERROR); Application.Terminate; end; end; end; end; procedure TRDMEasyPlateServer.RemoteDataModuleDestroy(Sender: TObject); begin if EasyRDMADOConn.Connected then EasyRDMADOConn.Close; PostMessage(frmEasyPlateServerMain.Handle, WM_USER + 100, 0, 0); end; function TRDMEasyPlateServer.EasyGetRDMData(const ASQL: WideString): OleVariant; begin if frmEasyPlateServerMain.mmDetailLog.Checked then AddExecLog(ASQL, 1); Result := Self.InnerGetData(ASQL); end; { 这里每个表都必须提供相应的主键字段名. } function TRDMEasyPlateServer.EasySaveRDMData(const ATableName: WideString; ADelta: OleVariant; const AKeyField: WideString; out AErrorCode: SYSINT): OleVariant; var KeyField: TField; I, J: Integer; TmpMessage: WideString; begin //执行之前检查要更新的字段是否存在 EasyRDMCds.Data := ADelta; if EasyRDMCds.IsEmpty then Exit; KeyField := EasyRDMCds.FindField(AKeyField); if KeyField=nil then begin frmEasyPlateServerMain.mmErrorLog.Lines.Add('主键字段:' + AKeyField + '未提供'); Exit; end; { TODO : 表结构如果在缓存目录中存在就从缓存中更新 } // if FileExists(TableCachePath + ATableName + '.xml') then // EasyRDMQry.LoadFromFile(TableCachePath + ATableName + '.xml') // else begin EasyRDMQry.SQL.Text := 'SELECT * FROM ' + ATableName + ' WHERE 1 > 2'; EasyRDMQry.Open; end; with EasyRDMQry.FieldByName(AKeyField) do ProviderFlags := ProviderFlags + [pfInKey]; EasyRDMDsp.UpdateMode := upWhereKeyOnly; //输出详细执行信息 if frmEasyPlateServerMain.mmDetailLog.Checked then begin cdsSaveDetailMessage.Data := ADelta; AddExecLog(' 操作表:' + ATableName + ' 主键:' + AKeyField); for I := 0 to cdsSaveDetailMessage.RecordCount - 1 do begin TmpMessage := ''; for J := 0 to cdsSaveDetailMessage.FieldCount - 1 do begin if not cdsSaveDetailMessage.Fields[J].IsBlob then TmpMessage := TmpMessage + ',' + cdsSaveDetailMessage.Fields[J].AsString else TmpMessage := TmpMessage + ',Blob'; end; AddExecLog(TmpMessage); cdsSaveDetailMessage.Next; end; end; Result := InnerPostData(ADelta, AErrorCode); end; function TRDMEasyPlateServer.InnerGetData(strSQL: String): OleVariant; var I: Integer; begin // 必须是CLOSE状态, 否则报错. if EasyRDMQry.Active then EasyRDMQry.Active := False; Result := Self.AS_GetRecords('EasyRDMDsp', -1, I, ResetOption+MetaDataOption, strSQL, Params, OwnerData); end; function TRDMEasyPlateServer.InnerPostData(Delta: OleVariant; out ErrorCode: Integer): OleVariant; begin Result := Self.AS_ApplyUpdates('EasyRDMDsp', Delta, 0, ErrorCode, OwnerData); end; // ATableNameOLE、AKeyFieldOLE的值数量一定相同而且一定要表与主键要一一对应 function TRDMEasyPlateServer.EasySaveRDMDatas(ATableNameOLE, ADeltaOLE, AKeyFieldOLE, ACodeErrorOLE: OleVariant): OleVariant; var I, ErrorCode: Integer; CanCommit: Boolean; begin CanCommit := True; if EasyRDMADOConn.InTransaction then EasyRDMADOConn.RollbackTrans; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(AKeyFieldOLE, 1) then begin AddExecLog('表数量<>主健数量', 1); Exit; end; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(ADeltaOLE, 1) then begin AddExecLog('表数量<>提交数据集数量', 1); Exit; end; if VarArrayHighBound(ATableNameOLE, 1) <> VarArrayHighBound(ACodeErrorOLE, 1) then begin AddExecLog('表数量<>错误返回数量', 1); Exit; end; EasyRDMADOConn.BeginTrans; AddExecLog('BeginTrans'); try for I := VarArrayLowBound(ATableNameOLE, 1) to VarArrayHighBound(ATableNameOLE, 1) do begin Result := EasySaveRDMData(ATableNameOLE[I], ADeltaOLE[I], AKeyFieldOLE[I], ErrorCode); ACodeErrorOLE[I] := ErrorCode; end; for I := VarArrayLowBound(ACodeErrorOLE, 1) to VarArrayHighBound(ACodeErrorOLE, 1) do begin if ACodeErrorOLE[I] <> 0 then CanCommit := False; end; if CanCommit then begin EasyRDMADOConn.CommitTrans; AddExecLog('CommitTrans'); end else begin EasyRDMADOConn.RollbackTrans; AddExecLog('RollbackTrans'); end; except on e:Exception do begin EasyRDMADOConn.RollbackTrans; AddExecLog('RollbackTrans:' + e.Message); end; end; end; procedure TRDMEasyPlateServer.EasyRDMDspUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); begin with frmEasyPlateServerMain do mmErrorLog.Lines.Add(GetLocalTime + ' ' + E.Message); end; //执行之前检查要更新的字段是否存在 procedure TRDMEasyPlateServer.EasyRDMDspBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); function FindField(AQuery: TADOQuery; AFieldName: string): Boolean; var I: Integer; begin Result := False; for I := 0 to AQuery.FieldCount - 1 do begin if AQuery.Fields[I].FieldName = AFieldName then begin Result := True; Break; end; end; end; var I: Integer; TmpString: string; begin TmpString := ''; for I := 0 to DeltaDS.FieldCount - 1 do begin if not FindField(EasyRDMQry, DeltaDS.Fields[I].FieldName) then begin DeltaDS.FieldByName(DeltaDS.Fields[I].FieldName).ProviderFlags := []; end; TmpString := DeltaDS.Fields[I].AsString + ';'; end; case UpdateKind of ukInsert: begin AddExecLog('Insert'); end; ukModify: begin AddExecLog('Modify'); end; ukDelete: begin AddExecLog('Delete'); end; end; end; function TRDMEasyPlateServer.GetOperTime: string; begin Result := FormatDateTime('YYYY-MM-DD HH:NN:SS', Now); end; procedure TRDMEasyPlateServer.AddExecLog(ALogStr: string; AType: Integer = 0); begin if AType = 0 then frmEasyPlateServerMain.mmExecLog.Lines.Add(GetOperTime + ' ' + ALogStr) else frmEasyPlateServerMain.mmErrorLog.Lines.Add(GetOperTime + ' ' + ALogStr); end; function TRDMEasyPlateServer.EasyGetRDMDatas( ASQLOLE: OleVariant): OleVariant; var ACount, I: Integer; begin ACount := VarArrayHighBound(ASQLOLE, 1); Result := VarArrayCreate([0, ACount], varVariant); for I := VarArrayLowBound(ASQLOLE, 1) to VarArrayHighBound(ASQLOLE, 1) do Result[I] := EasyGetRDMData(ASQLOLE[I]); end; procedure TRDMEasyPlateServer.LoadConnectString; var AList: TStrings; ATmpMMStream, ADestMMStream: TMemoryStream; AFile: string; begin AFile := ExtractFilePath(Application.ExeName) + 'ConnectString.dll'; AList := TStringList.Create; if FileExists(AFile) then begin ATmpMMStream := TMemoryStream.Create; ADestMMStream := TMemoryStream.Create; try ATmpMMStream.LoadFromFile(AFile); DeCompressFile_Easy(ATmpMMStream, ADestMMStream, AFile); AList.LoadFromStream(ADestMMStream); FConnectString := AList.Values['CONNECTSTRING']; finally ATmpMMStream.Free; ADestMMStream.Free; end; end; AList.Free; end; procedure TRDMEasyPlateServer.EasyRDMQryPostError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin AddExecLog('Post:' + e.Message, 1); end; procedure TRDMEasyPlateServer.EasyRDMQryEditError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin AddExecLog('Edit:' + e.Message, 1); end; procedure TRDMEasyPlateServer.EasyRDMQryDeleteError(DataSet: TDataSet; E: EDatabaseError; var Action: TDataAction); begin AddExecLog('Delete:' + e.Message, 1); end; procedure TRDMEasyPlateServer.ApplicationEvents1Exception(Sender: TObject; E: Exception); begin AddExecLog(GetOperTime + ' ' + e.Message, 1); end; initialization //ciInternal--对象不受外部影响 RDMFactory := TComponentFactory.Create(ComServer, TRDMEasyPlateServer, Class_RDMEasyPlateServer, ciMultiInstance, tmApartment); //如果是Vista或Win7需要执行此句,在此全部执行 tmApartment ComServer.UpdateRegistry(True);//加入此名,可正常注入系统 end.
PROGRAM UnitTest; USES StringSetUnit; FUNCTION IntToString(x: INTEGER): STRING; VAR s: STRING; BEGIN (* IntToString *) Str(x, s); IntToString := s; END; (* IntToString *) VAR s1, t: StringSet; s2: StringSetObj; i: INTEGER; BEGIN (* UnitTest *) New(s1, Init(5)); s2.Init(5); FOR i := 1 TO 5 DO BEGIN s1^.Add(IntToString(i)); s2.Add(IntToString(i+3)); END; (* FOR *) s1^.Test; s2.Test; WriteLn('Removing 1, 5, 7: '); s1^.Remove('1'); s1^.Remove('5'); s1^.Remove('7'); WriteLn('Removed 1, 5, 7: '); s1^.Test; t := Difference(s1, @s2); WriteLn('Difference:'); t^.Test; Dispose(s1, Done); s2.Done; Dispose(t, Done); END. (* UnitTest *)
unit IdLogBase; interface uses Classes, IdIntercept, IdSocketHandle; const ID_LOGBASE_Active = False; ID_LOGBASE_LogTime = True; type TIdLogBase = class(TIdConnectionIntercept) protected FActive: Boolean; FLogTime: Boolean; procedure Log(AText: string); virtual; abstract; procedure SetActive(const AValue: Boolean); virtual; public procedure Connect(ABinding: TIdSocketHandle); override; constructor Create(AOwner: TComponent); override; procedure DataReceived(var ABuffer; const AByteCount: integer); override; procedure DataSent(var ABuffer; const AByteCount: integer); override; procedure Disconnect; override; procedure DoLog(AText: string); virtual; published property Active: Boolean read FActive write SetActive default ID_LOGBASE_Active; property LogTime: Boolean read FLogTime write FLogTime default ID_LOGBASE_LogTime; end; implementation uses IdGlobal, IdResourceStrings, SysUtils; procedure TIdLogBase.Connect(ABinding: TIdSocketHandle); begin inherited; DoLog(RSLogConnected); end; constructor TIdLogBase.Create(AOwner: TComponent); begin inherited; FActive := ID_LOGBASE_Active; FLogTime := ID_LOGBASE_LogTime; end; procedure TIdLogBase.DataReceived(var ABuffer; const AByteCount: integer); var s: string; begin inherited; SetString(s, PChar(@ABuffer), AByteCount); DoLog(RSLogRecV + s); end; procedure TIdLogBase.DataSent(var ABuffer; const AByteCount: integer); var s: string; begin inherited; SetString(s, PChar(@ABuffer), AByteCount); DoLog(RSLogSent + s); end; procedure TIdLogBase.Disconnect; begin DoLog(RSLogDisconnected); inherited; end; procedure TIdLogBase.DoLog(AText: string); begin if Active then begin if LogTime then begin AText := DateTimeToStr(Now) + ': ' + AText; {Do not localize} end; Log(StringReplace(AText, EOL, RSLogEOL, [rfReplaceAll])); end; end; procedure TIdLogBase.SetActive(const AValue: Boolean); begin FActive := AValue; end; end.
unit TrazMedLib_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 17244 $ // File generated on 18/04/2012 10:31:30 from Type Library described below. // ************************************************************************ // // Type Lib: C:\Documents and Settings\amiranda\Mis documentos\RAD Studio\Projects\TrazMedLib\TrazMedLib (1) // LIBID: {476EC915-3ADA-4454-AFC9-C38597F708AE} // LCID: 0 // Helpfile: // HelpString: // DepndLst: // (1) v2.0 stdole, (C:\WINDOWS\system32\stdole2.tlb) // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Windows, ActiveX, Classes, Graphics, OleServer, StdVCL, Variants; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions TrazMedLibMajorVersion = 1; TrazMedLibMinorVersion = 0; LIBID_TrazMedLib: TGUID = '{476EC915-3ADA-4454-AFC9-C38597F708AE}'; IID_ITrazaMed: TGUID = '{C2126B36-6E99-4E14-8A64-062DF54BC99B}'; CLASS_TrazaMed: TGUID = '{88050DA1-B1C1-4FB6-ACAD-4A84D0052946}'; IID_ImedicamentosDTO: TGUID = '{42FDFC37-FD0D-4D1F-927F-B0C57A6AF4E9}'; CLASS_medicamentosDTO: TGUID = '{7F43C0C1-B342-409B-B703-54BF1D0C1D58}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// ITrazaMed = interface; ITrazaMedDisp = dispinterface; ImedicamentosDTO = interface; ImedicamentosDTODisp = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// TrazaMed = ITrazaMed; medicamentosDTO = ImedicamentosDTO; // *********************************************************************// // Interface: ITrazaMed // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {C2126B36-6E99-4E14-8A64-062DF54BC99B} // *********************************************************************// ITrazaMed = interface(IDispatch) ['{C2126B36-6E99-4E14-8A64-062DF54BC99B}'] procedure Reset; safecall; function sendCancelacTransacc(id_transaccion: Integer): OLE_CANCELBOOL; safecall; procedure AgregaMedicamento(const medicamentoDTO: ImedicamentosDTO); safecall; function SendMedicamentos: OLE_CANCELBOOL; safecall; procedure AgregaMedicamentosDHSerie; safecall; procedure sendMedicamentosDHSerie; safecall; function Get_XMLRequest: WideString; safecall; function Get_XMLResponse: WideString; safecall; function Get_Errores: WideString; safecall; function Get_usuario: WideString; safecall; procedure Set_usuario(const Value: WideString); safecall; function Get_password: WideString; safecall; procedure Set_password(const Value: WideString); safecall; property XMLRequest: WideString read Get_XMLRequest; property XMLResponse: WideString read Get_XMLResponse; property Errores: WideString read Get_Errores; property usuario: WideString read Get_usuario write Set_usuario; property password: WideString read Get_password write Set_password; end; // *********************************************************************// // DispIntf: ITrazaMedDisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {C2126B36-6E99-4E14-8A64-062DF54BC99B} // *********************************************************************// ITrazaMedDisp = dispinterface ['{C2126B36-6E99-4E14-8A64-062DF54BC99B}'] procedure Reset; dispid 205; function sendCancelacTransacc(id_transaccion: Integer): OLE_CANCELBOOL; dispid 206; procedure AgregaMedicamento(const medicamentoDTO: ImedicamentosDTO); dispid 201; function SendMedicamentos: OLE_CANCELBOOL; dispid 202; procedure AgregaMedicamentosDHSerie; dispid 208; procedure sendMedicamentosDHSerie; dispid 207; property XMLRequest: WideString readonly dispid 203; property XMLResponse: WideString readonly dispid 204; property Errores: WideString readonly dispid 209; property usuario: WideString dispid 210; property password: WideString dispid 211; end; // *********************************************************************// // Interface: ImedicamentosDTO // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {42FDFC37-FD0D-4D1F-927F-B0C57A6AF4E9} // *********************************************************************// ImedicamentosDTO = interface(IDispatch) ['{42FDFC37-FD0D-4D1F-927F-B0C57A6AF4E9}'] function Get_f_evento: WideString; safecall; procedure Set_f_evento(const Value: WideString); safecall; function Get_h_evento: WideString; safecall; procedure Set_h_evento(const Value: WideString); safecall; function Get_gln_origen: WideString; safecall; procedure Set_gln_origen(const Value: WideString); safecall; function Get_cuit_origen: WideString; safecall; procedure Set_cuit_origen(const Value: WideString); safecall; function Get_gln_destino: WideString; safecall; procedure Set_gln_destino(const Value: WideString); safecall; function Get_cuit_destino: WideString; safecall; procedure Set_cuit_destino(const Value: WideString); safecall; function Get_n_remito: WideString; safecall; procedure Set_n_remito(const Value: WideString); safecall; function Get_n_factura: WideString; safecall; procedure Set_n_factura(const Value: WideString); safecall; function Get_vencimiento: WideString; safecall; procedure Set_vencimiento(const Value: WideString); safecall; function Get_gtin: WideString; safecall; procedure Set_gtin(const Value: WideString); safecall; function Get_lote: WideString; safecall; procedure Set_lote(const Value: WideString); safecall; function Get_numero_serial: WideString; safecall; procedure Set_numero_serial(const Value: WideString); safecall; function Get_id_evento: Integer; safecall; procedure Set_id_evento(Value: Integer); safecall; function Get_apellido: WideString; safecall; procedure Set_apellido(const Value: WideString); safecall; function Get_nombres: WideString; safecall; procedure Set_nombres(const Value: WideString); safecall; function Get_n_documento: WideString; safecall; procedure Set_n_documento(const Value: WideString); safecall; function Get_sexo: WideString; safecall; procedure Set_sexo(const Value: WideString); safecall; function Get_Tipo_documento: Integer; safecall; procedure Set_Tipo_documento(Value: Integer); safecall; function Get_direccion: WideString; safecall; procedure Set_direccion(const Value: WideString); safecall; function Get_localidad: WideString; safecall; procedure Set_localidad(const Value: WideString); safecall; function Get_numero: WideString; safecall; procedure Set_numero(const Value: WideString); safecall; function Get_piso: WideString; safecall; procedure Set_piso(const Value: WideString); safecall; function Get_dpto: WideString; safecall; procedure Set_dpto(const Value: WideString); safecall; function Get_n_postal: WideString; safecall; procedure Set_n_postal(const Value: WideString); safecall; function Get_Telefono: WideString; safecall; procedure Set_Telefono(const Value: WideString); safecall; function Get_id_obra_social: Integer; safecall; procedure Set_id_obra_social(Value: Integer); safecall; function Get_provincia: WideString; safecall; procedure Set_provincia(const Value: WideString); safecall; function Get_fecha_nacimiento: WideString; safecall; procedure Set_fecha_nacimiento(const Value: WideString); safecall; property f_evento: WideString read Get_f_evento write Set_f_evento; property h_evento: WideString read Get_h_evento write Set_h_evento; property gln_origen: WideString read Get_gln_origen write Set_gln_origen; property cuit_origen: WideString read Get_cuit_origen write Set_cuit_origen; property gln_destino: WideString read Get_gln_destino write Set_gln_destino; property cuit_destino: WideString read Get_cuit_destino write Set_cuit_destino; property n_remito: WideString read Get_n_remito write Set_n_remito; property n_factura: WideString read Get_n_factura write Set_n_factura; property vencimiento: WideString read Get_vencimiento write Set_vencimiento; property gtin: WideString read Get_gtin write Set_gtin; property lote: WideString read Get_lote write Set_lote; property numero_serial: WideString read Get_numero_serial write Set_numero_serial; property id_evento: Integer read Get_id_evento write Set_id_evento; property apellido: WideString read Get_apellido write Set_apellido; property nombres: WideString read Get_nombres write Set_nombres; property n_documento: WideString read Get_n_documento write Set_n_documento; property sexo: WideString read Get_sexo write Set_sexo; property Tipo_documento: Integer read Get_Tipo_documento write Set_Tipo_documento; property direccion: WideString read Get_direccion write Set_direccion; property localidad: WideString read Get_localidad write Set_localidad; property numero: WideString read Get_numero write Set_numero; property piso: WideString read Get_piso write Set_piso; property dpto: WideString read Get_dpto write Set_dpto; property n_postal: WideString read Get_n_postal write Set_n_postal; property Telefono: WideString read Get_Telefono write Set_Telefono; property id_obra_social: Integer read Get_id_obra_social write Set_id_obra_social; property provincia: WideString read Get_provincia write Set_provincia; property fecha_nacimiento: WideString read Get_fecha_nacimiento write Set_fecha_nacimiento; end; // *********************************************************************// // DispIntf: ImedicamentosDTODisp // Flags: (4416) Dual OleAutomation Dispatchable // GUID: {42FDFC37-FD0D-4D1F-927F-B0C57A6AF4E9} // *********************************************************************// ImedicamentosDTODisp = dispinterface ['{42FDFC37-FD0D-4D1F-927F-B0C57A6AF4E9}'] property f_evento: WideString dispid 201; property h_evento: WideString dispid 202; property gln_origen: WideString dispid 203; property cuit_origen: WideString dispid 204; property gln_destino: WideString dispid 205; property cuit_destino: WideString dispid 206; property n_remito: WideString dispid 207; property n_factura: WideString dispid 208; property vencimiento: WideString dispid 209; property gtin: WideString dispid 210; property lote: WideString dispid 211; property numero_serial: WideString dispid 212; property id_evento: Integer dispid 213; property apellido: WideString dispid 214; property nombres: WideString dispid 215; property n_documento: WideString dispid 216; property sexo: WideString dispid 217; property Tipo_documento: Integer dispid 218; property direccion: WideString dispid 219; property localidad: WideString dispid 220; property numero: WideString dispid 221; property piso: WideString dispid 222; property dpto: WideString dispid 223; property n_postal: WideString dispid 224; property Telefono: WideString dispid 225; property id_obra_social: Integer dispid 226; property provincia: WideString dispid 227; property fecha_nacimiento: WideString dispid 228; end; // *********************************************************************// // The Class CoTrazaMed provides a Create and CreateRemote method to // create instances of the default interface ITrazaMed exposed by // the CoClass TrazaMed. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoTrazaMed = class class function Create: ITrazaMed; class function CreateRemote(const MachineName: string): ITrazaMed; end; // *********************************************************************// // The Class ComedicamentosDTO provides a Create and CreateRemote method to // create instances of the default interface ImedicamentosDTO exposed by // the CoClass medicamentosDTO. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// ComedicamentosDTO = class class function Create: ImedicamentosDTO; class function CreateRemote(const MachineName: string): ImedicamentosDTO; end; implementation uses ComObj; class function CoTrazaMed.Create: ITrazaMed; begin Result := CreateComObject(CLASS_TrazaMed) as ITrazaMed; end; class function CoTrazaMed.CreateRemote(const MachineName: string): ITrazaMed; begin Result := CreateRemoteComObject(MachineName, CLASS_TrazaMed) as ITrazaMed; end; class function ComedicamentosDTO.Create: ImedicamentosDTO; begin Result := CreateComObject(CLASS_medicamentosDTO) as ImedicamentosDTO; end; class function ComedicamentosDTO.CreateRemote(const MachineName: string): ImedicamentosDTO; begin Result := CreateRemoteComObject(MachineName, CLASS_medicamentosDTO) as ImedicamentosDTO; end; end.
unit NtUtils.Tokens.Impersonate; interface { NOTE: All functions here support pseudo-handles on input on all OS versions } uses NtUtils.Exceptions, NtUtils.Objects; // Save current impersonation token before operations that can alter it function NtxBackupImpersonation(hThread: THandle): IHandle; procedure NtxRestoreImpersonation(hThread: THandle; hxToken: IHandle); // Set thread token function NtxSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus; function NtxSetThreadTokenById(TID: NativeUInt; hToken: THandle): TNtxStatus; // Set thread token and make sure it was not duplicated to Identification level function NtxSafeSetThreadToken(hThread: THandle; hToken: THandle; SkipInputLevelCheck: Boolean = False): TNtxStatus; function NtxSafeSetThreadTokenById(TID: NativeUInt; hToken: THandle; SkipInputLevelCheck: Boolean = False): TNtxStatus; // Impersonate the token of any type on the current thread function NtxImpersonateAnyToken(hToken: THandle): TNtxStatus; // Assign primary token to a process function NtxAssignPrimaryToken(hProcess: THandle; hToken: THandle): TNtxStatus; function NtxAssignPrimaryTokenById(PID: NativeUInt; hToken: THandle): TNtxStatus; implementation uses Winapi.WinNt, Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntpsapi, Ntapi.ntseapi, NtUtils.Tokens, NtUtils.Processes, NtUtils.Threads, NtUtils.Tokens.Query; { Impersonation } function NtxBackupImpersonation(hThread: THandle): IHandle; var Status: NTSTATUS; begin // Open the thread's token Status := NtxOpenThreadToken(Result, hThread, TOKEN_IMPERSONATE).Status; if Status = STATUS_NO_TOKEN then Result := nil else if not NT_SUCCESS(Status) then begin // Most likely the token is here, but we can't access it. Although we can // make a copy via direct impersonation, I am not sure we should do it. // Currently, just clear the token as most of Winapi functions do in this // situation Result := nil; if hThread = NtCurrentThread then ENtError.Report(Status, 'NtxBackupImpersonation'); end; end; procedure NtxRestoreImpersonation(hThread: THandle; hxToken: IHandle); begin // Try to establish the previous token if not Assigned(hxToken) or not NtxSetThreadToken(hThread, hxToken.Handle).IsSuccess then NtxSetThreadToken(hThread, 0); end; function NtxSetThreadToken(hThread: THandle; hToken: THandle): TNtxStatus; var hxToken: IHandle; begin // Handle pseudo-handles as well Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_IMPERSONATE); if Result.IsSuccess then Result := NtxThread.SetInfo(hThread, ThreadImpersonationToken, hxToken.Handle); // TODO: what about inconsistency with NtCurrentTeb.IsImpersonating ? end; function NtxSetThreadTokenById(TID: NativeUInt; hToken: THandle): TNtxStatus; var hxThread: IHandle; begin Result := NtxOpenThread(hxThread, TID, THREAD_SET_THREAD_TOKEN); if Result.IsSuccess then Result := NtxSetThreadToken(hxThread.Handle, hToken); end; { Some notes about safe impersonation... Usually, the system establishes the exact token we passed to the system call as an impersonation token for the target thread. However, in some cases it duplicates the token or adjusts it a bit. * Anonymous up to identification-level tokens do not require any special treatment - you can impersonate any of them without limitations. As for impersonation- and delegation-level tokens: * If the target process does not have SeImpersonatePrivilege, some security contexts can't be impersonated by its threads. The system duplicates such tokens to identification level which fails all further access checks for the target thread. Unfortunately, the result of NtSetInformationThread does not provide any information whether it happened. The goal is to detect and avoid such situations since we should consider such impersonations as failed. * Also, if the trust level of the target process is lower than the trust level specified in the token, the system duplicates the token removing the trust label; as for the rest, the impersonations succeeds. This scenario does not allow us to determine whether the impersonation was successful by simply comparing the source and the actually set tokens. Duplication does not necessarily means failed impersonation. NtxSafeSetThreadToken sets the token, queries what was actually set, and checks the impersonation level. Anything but success causes the routine to undo its work. Note: The security context of the target thread is not guaranteed to return to its previous state. It might happen if the target thread is impersonating a token that the caller can't open. In this case after the failed call the target thread will have no token. To address this issue the caller can make a copy of the target thread's token by using NtImpersonateThread. See implementation of NtxDuplicateEffectiveToken for more details. Other possible implementations: * Since NtImpersonateThread fails with BAD_IMPERSONATION_LEVEL when we request Impersonation-level token while the thread's token is Identification or less. We can use this behaviour to determine which level the target token is. } function NtxSafeSetThreadToken(hThread: THandle; hToken: THandle; SkipInputLevelCheck: Boolean): TNtxStatus; var hxBackupToken, hxActuallySetToken, hxToken: IHandle; Stats: TTokenStatistics; begin // No need to use safe impersonation to revoke tokens if hToken = 0 then Exit(NtxSetThreadToken(hThread, hToken)); // Make sure to handle pseudo-tokens as well Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_IMPERSONATE or TOKEN_QUERY); if not Result.IsSuccess then Exit; if not SkipInputLevelCheck then begin // Determine the impersonation level of the token Result := NtxToken.Query(hxToken.Handle, TokenStatistics, Stats); if not Result.IsSuccess then Exit; // Anonymous up to Identification do not require any special treatment if (Stats.TokenType <> TokenImpersonation) or (Stats.ImpersonationLevel < SecurityImpersonation) then Exit(NtxSetThreadToken(hThread, hxToken.Handle)); end; // Backup old state hxBackupToken := NtxBackupImpersonation(hThread); // Set the token Result := NtxSetThreadToken(hThread, hxToken.Handle); if not Result.IsSuccess then Exit; // Read it back for further checks Result := NtxOpenThreadToken(hxActuallySetToken, hThread, TOKEN_QUERY); // Determine the actual impersonation level if Result.IsSuccess then begin Result := NtxToken.Query(hxActuallySetToken.Handle, TokenStatistics, Stats); if Result.IsSuccess and (Stats.ImpersonationLevel < SecurityImpersonation) then begin // Fail. SeImpersonatePrivilege on the target process can help Result.Location := 'NtxSafeSetThreadToken'; Result.LastCall.ExpectedPrivilege := SE_IMPERSONATE_PRIVILEGE; Result.Status := STATUS_PRIVILEGE_NOT_HELD; end; end; // Reset on failure if not Result.IsSuccess then NtxRestoreImpersonation(hThread, hxBackupToken); end; function NtxSafeSetThreadTokenById(TID: NativeUInt; hToken: THandle; SkipInputLevelCheck: Boolean): TNtxStatus; var hxThread: IHandle; begin Result := NtxOpenThread(hxThread, TID, THREAD_QUERY_LIMITED_INFORMATION or THREAD_SET_THREAD_TOKEN); if Result.IsSuccess then Result := NtxSafeSetThreadToken(hxThread.Handle, hToken, SkipInputLevelCheck); end; function NtxImpersonateAnyToken(hToken: THandle): TNtxStatus; var hxToken, hxImpToken: IHandle; begin Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_IMPERSONATE); if not Result.IsSuccess then Exit; // Try to impersonate (in case it is an impersonation-type token) Result := NtxSetThreadToken(NtCurrentThread, hxToken.Handle); if Result.Matches(STATUS_BAD_TOKEN_TYPE, 'NtSetInformationThread') then begin // Nope, it is a primary token, duplicate it Result := NtxDuplicateToken(hxImpToken, hToken, TOKEN_IMPERSONATE, TokenImpersonation, SecurityImpersonation); // Impersonate, second attempt if Result.IsSuccess then Result := NtxSetThreadToken(NtCurrentThread, hxImpToken.Handle); end; end; function NtxAssignPrimaryToken(hProcess: THandle; hToken: THandle): TNtxStatus; var hxToken: IHandle; AccessToken: TProcessAccessToken; begin // Manage pseudo-tokens Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_ASSIGN_PRIMARY); if Result.IsSuccess then begin AccessToken.Thread := 0; // Looks like the call ignores it AccessToken.Token := hxToken.Handle; Result := NtxProcess.SetInfo(hProcess, ProcessAccessToken, AccessToken); end; end; function NtxAssignPrimaryTokenById(PID: NativeUInt; hToken: THandle): TNtxStatus; var hxProcess: IHandle; begin Result := NtxOpenProcess(hxProcess, PID, PROCESS_SET_INFORMATION); if not Result.IsSuccess then Exit; Result := NtxAssignPrimaryToken(hxProcess.Handle, hToken); end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP client-side invoker } { } { Copyright (c) 2000 Inprise Corporation } { } {*******************************************************} unit SOAPConn; interface uses SysUtils, Variants, Classes, Midas, DBClient, SOAPHTTPTrans, Rio, SOAPHTTPClient, SOAPMidas; type { TSoapConnection } TSoapConnection = class(TCustomRemoteServer) private FRIO: THTTPRIO; FURL: string; { Old-style (D6) interface holder - hardcoded to IAppServer only } FAppServer: IAppServer; { New IAppServerSOAP (or derived via FSOAPServerIID) interface } FSOAPServer: IAppServerSOAP; FUseSOAPAdapter: Boolean; FSOAPServerIID: String; FOnAfterExecute: TAfterExecuteEvent; FOnBeforeExecute: TBeforeExecuteEvent; FHTTPRIO: THTTPRIO; function GetAgent: string; function GetPassword: string; function GetProxy: string; function GetProxyByPass: string; function GetUserName: string; procedure SetAgent(const Value: string); procedure SetPassword(const Value: string); procedure SetProxy(const Value: string); procedure SetProxyByPass(const Value: string); procedure SetURL(const Value: string); procedure SetUserName(const Value: string); protected procedure DoConnect; override; function GetConnected: Boolean; override; function GetServerList: OleVariant; override; procedure DoDisconnect; override; procedure GetProviderNames(Proc: TGetStrProc); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetUseSoapAdapter(Value: Boolean); procedure SetSOAPServerIID(const IID: String); function GetSOAPServerIID: TGUID; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function GetServer: IAppServer; override; function GetSOAPServer: IAppServerSOAP; { Give access to underlying RIO } property RIO: THTTPRIO read FHTTPRIO; published property Agent: string read GetAgent write SetAgent; { Publish standard DataSnap Connection properties} property Connected; property AfterConnect; property BeforeConnect; property AfterDisconnect; property BeforeDisconnect; property Password: string read GetPassword write SetPassword; property Proxy: string read GetProxy write SetProxy; property ProxyByPass: string read GetProxyByPass write SetProxyByPass; property URL: string read FURL write SetURL; property SOAPServerIID: String read FSOAPServerIID write SetSOAPServerIID; property UserName: string read GetUserName write SetUserName; property UseSOAPAdapter: Boolean read FUseSOAPAdapter write SetUseSOAPAdapter; property OnAfterExecute: TAfterExecuteEvent read FOnAfterExecute write FOnAfterExecute; property OnBeforeExecute: TBeforeExecuteEvent read FOnBeforeExecute write FOnBeforeExecute; end; implementation uses {$IFDEF MSWINDOWS}Windows, ComObj{$ENDIF}{$IFDEF LINUX}Libc{$ENDIF}, InvokeRegistry, SOAPConst, Types; type { Adapter class that allows local access to IAppServer when a remote SOAP server exposes IAppServerSOAP IOW: This class provides a local implementation of IAppServer that talks IAppServerSOAP to a SOAP Service } TSOAPAppServerAdapter = class(TInterfacedObject, IAppServer) private FSOAPServer: IAppServerSOAP; {$IFDEF MSWINDOWS} function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override; {$ENDIF} public constructor Create(const AppServerSOAP: IAppServerSOAP); { IAppServer } function AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; function AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant): OleVariant; safecall; function AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; function AS_GetProviderNames: OleVariant; safecall; function AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall; function AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall; procedure AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant); safecall; { IDispatch: NOTE Methods of IDispatch are not exposed via SOAP } function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; end; constructor TSOAPAppServerAdapter.Create(const AppServerSOAP: IAppServerSOAP); begin inherited Create; FSOAPServer := AppServerSOAP; end; function TSOAPAppServerAdapter.AS_ApplyUpdates(const ProviderName: WideString; Delta: OleVariant; MaxErrors: Integer; out ErrorCount: Integer; var OwnerData: OleVariant): OleVariant; safecall; begin Result := FSOAPServer.SAS_ApplyUpdates(ProviderName, Delta, MaxErrors, ErrorCount, OwnerData); end; function TSOAPAppServerAdapter.AS_GetRecords(const ProviderName: WideString; Count: Integer; out RecsOut: Integer; Options: Integer; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant): OleVariant; safecall; begin Result := FSOAPServer.SAS_GetRecords(ProviderName, Count, RecsOut, Options, CommandText, Params, OwnerData); end; function TSOAPAppServerAdapter.AS_DataRequest(const ProviderName: WideString; Data: OleVariant): OleVariant; safecall; begin Result := FSOAPServer.SAS_DataRequest(ProviderName, Data); end; function TSOAPAppServerAdapter.AS_GetProviderNames: OleVariant; safecall; var Names: TWideStringDynArray; I, Count: Integer; begin VarClear(Result); Names := FSOAPServer.SAS_GetProviderNames; if Length(Names) > 0 then begin Count := Length(Names); Result := VarArrayCreate([0, Count-1], varVariant); for I := 0 to Length(Names)-1 do Result[I] := Variant(Names[I]); end end; function TSOAPAppServerAdapter.AS_GetParams(const ProviderName: WideString; var OwnerData: OleVariant): OleVariant; safecall; begin Result := FSOAPServer.SAS_GetParams(ProviderName, OwnerData); end; function TSOAPAppServerAdapter.AS_RowRequest(const ProviderName: WideString; Row: OleVariant; RequestType: Integer; var OwnerData: OleVariant): OleVariant; safecall; begin Result := FSOAPServer.SAS_RowRequest(ProviderName, Row, RequestType, OwnerData); end; procedure TSOAPAppServerAdapter.AS_Execute(const ProviderName: WideString; const CommandText: WideString; var Params: OleVariant; var OwnerData: OleVariant); safecall; begin FSOAPServer.SAS_Execute(ProviderName, CommandText, Params, OwnerData); end; function TSOAPAppServerAdapter.GetTypeInfoCount(out Count: Integer): HResult; stdcall; begin Result := E_NOTIMPL; end; function TSOAPAppServerAdapter.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; begin Result := E_NOTIMPL; end; function TSOAPAppServerAdapter.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; begin Result := E_NOTIMPL; end; function TSOAPAppServerAdapter.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; begin Result := E_NOTIMPL; end; {$IFDEF MSWINDOWS} function TSOAPAppServerAdapter.SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; begin Result := HandleSafeCallException(ExceptObject, ExceptAddr, IAppServer, '', ''); end; {$ENDIF} { TSoapConnection } constructor TSoapConnection.Create(AOwner: TComponent); begin inherited Create(AOwner); RPR; { FUseSOAPAdapter should be disabled when talking to SOAP Services that only expose IAppServer - i.e. Delphi/6 & Kylix servers - until these are updated } FUseSOAPAdapter := True; { We'll assume IAppServerSOAP as the default interface of Servers } FSOAPServerIID := Format(SSOAPServerIIDFmt, ['IAppServerSOAP', GUIDToString(IAppServerSOAP)]); { do not localize } end; destructor TSoapConnection.Destroy; begin inherited; end; procedure TSoapConnection.DoDisconnect; begin inherited; { Clean link to remote SOAP Server } FAppServer := nil; FSOAPServer := nil; if Assigned(FRIO) then FRIO := nil; end; procedure TSoapConnection.SetUseSoapAdapter(Value: Boolean); begin if FUseSOAPAdapter <> Value then begin Connected := False; FUseSOAPAdapter := Value; end; end; procedure TSoapConnection.GetProviderNames(Proc: TGetStrProc); var List: Variant; I: Integer; begin Connected := True; VarClear(List); try List := FAppServer.AS_GetProviderNames; except { Assume any errors means the list is not available. } end; if VarIsArray(List) and (VarArrayDimCount(List) = 1) then for I := VarArrayLowBound(List, 1) to VarArrayHighBound(List, 1) do Proc(List[I]); end; function TSoapConnection.GetServer: IAppServer; begin Connected := True; Result := FAppServer; end; { Provides direct access to the underlying SOAP Server that implements IAppServer } function TSoapConnection.GetSOAPServer: IAppServerSOAP; begin Result := FSOAPServer; end; function TSoapConnection.GetServerList: OleVariant; begin end; procedure TSoapConnection.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; end; procedure TSoapConnection.DoConnect; var Res: HResult; Info: Pointer; begin if (URL = '') then raise Exception.Create(SNoURL); if not Assigned(FRIO) then try FRIO := THTTPRIO.Create(nil); if FUseSOAPAdapter then begin { Make sure this interface has been registered } { If you've selected an interface other than IAppServer(SOAP) then you need to make sure that you import the WSDL of the Service exposing that interface and that you include the resulting unit in your project } Info := InvRegistry.GetInterfaceTypeInfo(GetSOAPServerIID); if Info = nil then raise Exception.CreateFmt(SSOAPInterfaceNotRegistered, [FSOAPServerIID]); Res := FRIO.QueryInterface(GetSOAPServerIID, FSOAPServer); if Res <> 0 then raise Exception.CreateFmt(SSOAPInterfaceNotRemotable, [FSOAPServerIID]); { FSOAPServer := FRIO as IAppServerSOAP; } FAppServer := TSOAPAppServerAdapter.Create(FSOAPServer); end else FAppServer := FRIO as IAppServer; if Assigned(FOnAfterExecute) then FRIO.OnAfterExecute := FOnAfterExecute; if Assigned(FOnBeforeExecute) then FRIO.OnBeforeExecute := FOnBeforeExecute; FRIO.URL := FURL; except Connected := False; end; end; function TSoapConnection.GetConnected: Boolean; begin Result := Assigned(FRIO) and (Assigned(FRIO.HTTPWebNode)); end; function TSoapConnection.GetAgent: string; begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then Result := FRIO.HTTPWebNode.Agent; end; function TSoapConnection.GetPassword: string; begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then Result := FRIO.HTTPWebNode.Password; end; function TSoapConnection.GetProxy: string; begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then Result := FRIO.HTTPWebNode.Proxy; end; function TSoapConnection.GetProxyByPass: string; begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then Result := FRIO.HTTPWebNode.ProxyByPass; end; function TSoapConnection.GetUserName: string; begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then Result := FRIO.HTTPWebNode.Username; end; procedure TSoapConnection.SetURL(const Value: string); begin if Value <> FURL then begin FURL := Value; Connected := False; end; end; procedure TSoapConnection.SetAgent(const Value: string); begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then FRIO.HTTPWebNode.Agent := Value else if not (csLoading in ComponentState) then raise Exception.Create(SNoURL); end; procedure TSoapConnection.SetPassword(const Value: string); begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then FRIO.HTTPWebNode.Password := Value else if not (csLoading in ComponentState) then raise Exception.Create(SNoURL); end; procedure TSoapConnection.SetProxy(const Value: string); begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then FRIO.HTTPWebNode.Proxy := Value else if not (csLoading in ComponentState) then raise Exception.Create(SNoURL); end; procedure TSoapConnection.SetProxyByPass(const Value: string); begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then FRIO.HTTPWebNode.ProxyByPass := Value else if not (csLoading in ComponentState) then raise Exception.Create(SNoURL); end; procedure TSoapConnection.SetUserName(const Value: string); begin if Assigned(FRIO) and Assigned(FRIO.HTTPWebNode) then FRIO.HTTPWebNode.UserName := Value else if not (csLoading in ComponentState) then raise Exception.Create(SNoURL); end; procedure TSoapConnection.SetSOAPServerIID(const IID: String); begin FSOAPServerIID := IID; end; function TSoapConnection.GetSOAPServerIID: TGUID; var StrIID: String; Idx: Integer; begin StrIID := FSOAPServerIID; Idx := Pos('{', StrIID); { Do not localize } if Idx > -1 then StrIID := Copy(StrIID, Idx, MaxInt); Idx := Pos('}', StrIID); { Do not localize } if Idx > -1 then StrIID := Copy(StrIID, 0, Idx); Result := StringToGUID(StrIID); end; end.