text
stringlengths
14
6.51M
unit ccGlobal; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TLenUnits = (lu_nm, lu_Microns, lu_cm, lu_m); TAreaUnits = (au_nm2, au_Microns2, au_cm2, au_m2); TVolumeUnits = (vu_nm3, vu_Microns3, vu_cm3, vu_m3); TCapaUnits = (cu_aF, cu_fF, cu_pF, cu_nF, cu_F); TEFieldUnits = (eu_mV_nm, eu_V_micron, eu_kV_cm, eu_MV_m, eu_V_m); TTempUnits = (tuK, tuC); TMaterial = (mSi, mGaAs, mGe, mInP); const CapaExpFormat = '0.000E+00'; CapaStdFormat = '0.000'; CapaPerAreaFormat = '0.000E+00'; CapaPerLengthFormat = '0.000E+00'; ConcFormat = '0.00E+00'; LenStdFormat = '0.00'; AreaStdFormat = '0.00E+00'; eps0 = 8.854187817E-12; // F/m q = 1.60217733E-19; // C kB = 1.380658E-23; // Boltzmann constant (J/k) Pi = 3.1415926535897932384626; TwoPi = 6.2831853071795864769253; // 2*Pi LenFactor : array[TLenUnits] of double = ( 1E-9, 1E-6, 1E-2, 1.0); AreaFactor : array[TAreaUnits] of double = ( 1E-18, 1E-12, 1E-4, 1.0); VolumeFactor : array[TVolumeUnits] of double = ( 1E-27, 1E-18, 1E-6, 1.0); CapaFactor : array[TCapaUnits] of double = ( 1E-18, 1E-15, 1E-12, 1E-9, 1.0 ); EFieldFactor : array[TEFieldUnits] of double = ( 1E-3/1E-9, 1.0/1E-6, 1E3/1E-2, 1E6/1, 1.0 ); MaterialEps : array [TMaterial] of double = (11.9*eps0, 12.4*eps0, 16.0*eps0, 12.5*eps0); ni : array [TMaterial] of double = (9.65e9, 2.25e6, 2e13, 1.3e7); // 1/cm3 implementation end.
unit UDM; interface uses System.SysUtils, System.Classes, Data.DBXDataSnap, IPPeerClient, Data.DBXCommon, Datasnap.DBClient, Datasnap.DSConnect, Data.DB, Data.SqlExpr, FMX.Graphics, System.IOUtils, UClass; type TDM = class(TDataModule) SQLConnection1: TSQLConnection; DSProviderConnection1: TDSProviderConnection; Book_List: TClientDataSet; procedure SQLConnection1BeforeConnect(Sender: TObject); procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); private { Private declarations } public { Public declarations } procedure AppendMode; procedure EditMode; procedure SetImage(ABitmap: TBitmap); procedure SaveItem; procedure CancelItem; procedure DeleteItem; end; var DM: TDM; Demo:TServerMethods1Client; implementation { %CLASSGROUP 'FMX.Controls.TControl' } {$R *.dfm} procedure TDM.AppendMode; begin Book_List.append; end; procedure TDM.CancelItem; begin if Book_List.UpdateStatus = TUpdateStatus.usInserted then Book_List.cancel; end; procedure TDM.DataModuleCreate(Sender: TObject); begin demo:= TServerMethods1Client.Create(SQLConnection1.DBXConnection); end; procedure TDM.DataModuleDestroy(Sender: TObject); begin demo.Free; end; procedure TDM.DeleteItem; begin Book_List.delete; Book_List.applyupdates(-1); Book_List.refresh; end; procedure TDM.EditMode; begin Book_List.edit; end; procedure TDM.SaveItem; begin if Book_List.UpdateStatus = TUpdateStatus.usInserted then Book_List.fieldbyname('book_seq').AsInteger := 0; Book_List.post; Book_List.applyupdates(-1); Book_List.refresh; end; procedure TDM.SetImage(ABitmap: TBitmap); var Thumbnail: TBitmap; ImgStream, ThumbStream: TMemoryStream; begin ImgStream := TMemoryStream.Create; ThumbStream := TMemoryStream.Create; try ABitmap.SaveToStream(ImgStream); Thumbnail := ABitmap.CreateThumbnail(100, 100); Thumbnail.SaveToStream(ThumbStream); (Book_List.fieldbyname('BOOK_IMAGE') as TBlobField) .LoadFromStream(ImgStream); (Book_List.fieldbyname('BOOK_THUMB') as TBlobField) .LoadFromStream(ThumbStream); finally ImgStream.Free; ThumbStream.Free; end; end; procedure TDM.SQLConnection1BeforeConnect(Sender: TObject); begin {$IFNDEF MSWINDOWS} SQLConnection1.Params.Values['Database'] := TPath.Combine(TPath.GetDocumentsPath, 'BOOKLOG.GDB'); {$ENDIF} end; end.
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit ATSynEdit_Cmp_AcpFiles; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StrUtils, Graphics, ATSynEdit; procedure DoEditorCompletionAcp(AEdit: TATSynEdit; const AFilenameAcp: string; ACaseSens: boolean); implementation uses ATStringProc, ATSynEdit_Carets, ATSynEdit_Cmp_Form; procedure SReplaceAllPercentChars(var S: string); var i: byte; begin for i in [$20..$2F, ord('|')] do SReplaceAll(S, '%'+IntToHex(i, 2), Chr(i)); end; type { TAcp } TAcp = class private ListAcpType: TStringlist; ListAcpText: TStringlist; ListAcpDesc: TStringlist; FLexerWordChars: string; procedure DoLoadAcpFile(const fn: string; IsPascal: boolean); procedure DoOnGetCompleteProp(Sender: TObject; AContent: TStringList; out ACharsLeft, ACharsRight: integer); function GetActualNonWordChars: UnicodeString; public Ed: TATSynEdit; CaseSens: boolean; constructor Create; virtual; destructor Destroy; override; end; var Acp: TAcp = nil; //parse control string from .acp file (starts with #) procedure SParseString_AcpControlLine(const s: string; var WordChars: string; var IsBracketSep: boolean); var n: Integer; begin if SBeginsWith(s, '#chars') then begin WordChars:= ''; IsBracketSep:= true; n:= Pos(' ', s); if n>0 then begin WordChars:= Copy(s, n+1, MaxInt); IsBracketSep:= Pos('(', WordChars)=0; end; end; end; //parse string from .acp file procedure SParseString_AcpStd( const S: string; IsBracketSep: boolean; out SType, SId, SPar, SHint: string); const cMaxHintLen = 300; var a, b, c: Integer; begin SType:= ''; SId:= ''; SPar:= ''; SHint:= ''; if Trim(s)='' then Exit; a:= PosEx(' ', s, 1); b:= PosEx(' ', s, a+1); if b=0 then b:= Length(s)+1; if IsBracketSep then begin c:= PosEx('(', s, a+1); if (c<b) and (c<>0) then b:= c; end; c:= PosEx('|', s, b); if c=0 then c:= MaxInt div 2; SType:= Copy(s, 1, a-1); SId:= Copy(s, a+1, b-a-1); SPar:= Copy(s, b, c-b); SHint:= Copy(s, c+1, cMaxHintLen); SReplaceAllPercentChars(SId); SReplaceAllPercentChars(SPar); SReplaceAll(SPar, ';', ','); //Pascal lexer has ";" param separator SReplaceAll(SPar, '[,', ',['); //for optional params end; procedure TAcp.DoLoadAcpFile(const fn: string; IsPascal: boolean); var List: TStringList; s, SType, SText, SPar, SHint: string; IsBracketSep: boolean; i: Integer; begin ListAcpType.Clear; ListAcpText.Clear; ListAcpDesc.Clear; FLexerWordChars:= ''; IsBracketSep:= true; List:= TStringList.Create; try List.LoadFromFile(fn); for i:= 0 to List.Count-1 do begin s:= List[i]; if s='' then Continue; if s[1]='#' then begin SParseString_AcpControlLine(s, FLexerWordChars, IsBracketSep); Continue; end; SParseString_AcpStd(s, IsBracketSep, SType, SText, SPar, SHint); if SText<>'' then begin if IsPascal then begin SDeleteFrom(SText, ':'); if Pos('):', SPar)>0 then begin SDeleteFrom(SPar, '):'); SPar:= SPar+')'; end; end; ListAcpType.Add(SType); ListAcpText.Add(SText); ListAcpDesc.Add(SPar+CompletionOps.HintSep+SHint); end; end; finally FreeAndNil(List); end; end; procedure SDeleteOneChar(var S: UnicodeString; ch: WideChar); var N: integer; begin N:= Pos(ch, S); if N>0 then Delete(S, N, 1); end; function TAcp.GetActualNonWordChars: UnicodeString; var i: integer; begin Result:= Ed.OptNonWordChars; for i:= 1 to Length(FLexerWordChars) do SDeleteOneChar(Result, FLexerWordChars[i]); end; procedure TAcp.DoOnGetCompleteProp(Sender: TObject; AContent: TStringList; out ACharsLeft, ACharsRight: integer); var Caret: TATCaretItem; s_word_w: atString; s_type, s_text, s_desc, s_word: string; n: integer; ok: boolean; begin AContent.Clear; ACharsLeft:= 0; ACharsRight:= 0; Caret:= Ed.Carets[0]; EditorGetCurrentWord(Ed, Caret.PosX, Caret.PosY, GetActualNonWordChars, s_word_w, ACharsLeft, ACharsRight); s_word:= Utf8Encode(s_word_w); for n:= 0 to ListAcpText.Count-1 do begin s_type:= ''; s_text:= ''; s_desc:= ''; if n<ListAcpType.Count then s_type:= ListAcpType[n]; if n<ListAcpText.Count then s_text:= ListAcpText[n]; if n<ListAcpDesc.Count then s_desc:= ListAcpDesc[n]; if s_word<>'' then begin if CaseSens then ok:= SBeginsWith(s_text, s_word) else ok:= SBeginsWith(UpperCase(s_text), UpperCase(s_word)); if not ok then Continue; end; AContent.Add(s_type+'|'+s_text+'|'+s_desc); end; end; constructor TAcp.Create; begin inherited; ListAcpType:= TStringlist.create; ListAcpText:= TStringlist.create; ListAcpDesc:= TStringlist.create; end; destructor TAcp.Destroy; begin FreeAndNil(ListAcpType); FreeAndNil(ListAcpText); FreeAndNil(ListAcpDesc); inherited; end; procedure DoEditorCompletionAcp(AEdit: TATSynEdit; const AFilenameAcp: string; ACaseSens: boolean); var bPascal: boolean; begin if not FileExists(AFilenameAcp) then exit; bPascal:= Pos('Pascal', ExtractFileName(AFilenameAcp))>0; Acp.DoLoadAcpFile(AFilenameAcp, bPascal); Acp.Ed:= AEdit; Acp.CaseSens:= ACaseSens; EditorShowCompletionListbox(AEdit, @Acp.DoOnGetCompleteProp); end; initialization Acp:= TAcp.Create; finalization FreeAndNil(Acp); end.
{(*} (*------------------------------------------------------------------------------ Delphi Code formatter source code The Original Code is frClarify.pas, released April 2000. 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 ------------------------------------------------------------------------------*) {*)} unit frClarify; {$I JcfGlobal.inc} interface uses { delphi } Classes, Controls, Forms, StdCtrls, ExtCtrls, { local} frmBaseSettingsFrame; type TfClarify = class(TfrSettingsFrame) rgRunOnceOffs: TRadioGroup; mFileExtensions: TMemo; Label1: TLabel; private public constructor Create(AOwner: TComponent); override; procedure Read; override; procedure Write; override; end; implementation {$ifdef FPC} {$R *.lfm} {$else} {$R *.dfm} {$endif} uses JcfSettings, JcfHelp, SetClarify; constructor TfClarify.Create(AOwner: TComponent); begin inherited; fiHelpContext := HELP_CLARIFY; end; {------------------------------------------------------------------------------- worker procs } procedure TfClarify.Read; begin with JcfFormatSettings.Clarify do begin rgRunOnceOffs.ItemIndex := Ord(OnceOffs); mFileExtensions.Lines.Assign(FileExtensions); end; end; procedure TfClarify.Write; begin with JcfFormatSettings.Clarify do begin OnceOffs := TOnceOffsOption(rgRunOnceOffs.ItemIndex); FileExtensions.Assign(mFileExtensions.Lines); FileExtensions.Sort; end; end; {------------------------------------------------------------------------------- event handlers } end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 10/26/2004 10:49:20 PM JPMugaas Updated ref. Rev 1.4 2004.02.03 5:44:30 PM czhower Name changes Rev 1.3 1/21/2004 4:04:08 PM JPMugaas InitComponent Rev 1.2 10/24/2003 02:54:58 PM JPMugaas These should now work with the new code. Rev 1.1 2003.10.24 10:38:30 AM czhower UDP Server todos Rev 1.0 11/13/2002 08:02:44 AM JPMugaas } unit IdSystatUDPServer; { Indy Systat Client TIdSystatUDPServer Copyright (C) 2002 Winshoes Working Group Original author J. Peter Mugaas 2002-August-13 Based on RFC 866 Note that this protocol is officially called Active User. } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdGlobal, IdSocketHandle, IdUDPBase, IdUDPServer; type TIdUDPSystatEvent = procedure (ABinding: TIdSocketHandle; AResults : TStrings) of object; type TIdSystatUDPServer = class(TIdUDPServer) protected FOnSystat : TIdUDPSystatEvent; procedure DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); override; procedure InitComponent; override; published property OnSystat : TIdUDPSystatEvent read FOnSystat write FOnSystat; property DefaultPort default IdPORT_SYSTAT; end; implementation uses SysUtils; { According to the "Programming UNIX Sockets in C - Frequently Asked Questions" This has to do with the maximum size of a datagram on the two machines involved. This depends on the sytems involved, and the MTU (Maximum Transmission Unit). According to "UNIX Network Programming", all TCP/IP implementations must support a minimum IP datagram size of 576 bytes, regardless of the MTU. Assuming a 20 byte IP header and 8 byte UDP header, this leaves 548 bytes as a safe maximum size for UDP messages. The maximum size is 65516 bytes. Some platforms support IP fragmentation which will allow datagrams to be broken up (because of MTU values) and then re-assembled on the other end, but not all implementations support this. URL: http://www.manualy.sk/sock-faq/unix-socket-faq-5.html } const Max_UDPPacket = 548; Max_Line_Len = Max_UDPPacket - 2; //EOL deliniator { TIdSystatUDPServer } procedure TIdSystatUDPServer.InitComponent; begin inherited; DefaultPort := IdPORT_SYSTAT; end; procedure TIdSystatUDPServer.DoUDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var s, s2 : String; LResults : TStrings; i : Integer; function MaxLenStr(const AStr : String): String; begin Result := AStr; if Length(Result)>Max_Line_Len then begin SetLength(Result, Max_Line_Len); end; end; begin inherited DoUDPRead(AThread, AData, ABinding); if Assigned(FOnSystat) then begin LResults := TStringList.Create; try FOnSystat(ABinding, LResults); with ABinding do begin s := ''; for i := 0 to LResults.Count - 1 do begin {enure that one line will never exceed the maximum packet size } s2 := s + EOL + MaxLenStr(LResults[i]); if Length(s2) > Max_UDPPacket then begin s := TrimLeft(s); SendTo(PeerIP, PeerPort, ToBytes(s)); s := MaxLenStr(LResults[i]); end else begin s := s2; end; end; if s <> '' then begin s := TrimLeft(s); SendTo(PeerIP, PeerPort, ToBytes(s)); end; end; finally FreeAndNil(LResults); end; end; end; end.
unit NetComRegister; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // NetCom7 Package // 13 Dec 2010, 12/8/2020 // // Written by Demos Bill // VasDemos@yahoo.co.uk // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// interface uses WinApi.Windows, System.Classes, System.SysUtils, ToolsAPI, DesignIntf, DesignEditors, ncSockets, ncSources, ncCommandHandlers, ncDBSrv, ncDBCnt; type TncTCPSocketDefaultEditor = class(TDefaultEditor) public procedure EditProperty(const Prop: IProperty; var Continue: Boolean); override; end; TncSourceDefaultEditor = class(TDefaultEditor) public procedure EditProperty(const Prop: IProperty; var Continue: Boolean); override; end; procedure Register; implementation procedure Register; begin RegisterComponents('NetCom7', [TncTCPServer, TncTCPClient, TncServerSource, TncClientSource, TncCommandHandler, TncDBServer, TncDBDataset]); RegisterComponentEditor(TncTCPServer, TncTCPSocketDefaultEditor); RegisterComponentEditor(TncTCPClient, TncTCPSocketDefaultEditor); RegisterComponentEditor(TncServerSource, TncSourceDefaultEditor); RegisterComponentEditor(TncClientSource, TncSourceDefaultEditor); UnlistPublishedProperty(TncDBDataset, 'Connection'); UnlistPublishedProperty(TncDBDataset, 'ConnectionString'); // RegisterPropertyEditor(TypeInfo(string), TncDBDataset, 'ConnectionString', nil); ForceDemandLoadState(dlDisable); end; function GetVersion(aMinor: Boolean = True; aRelease: Boolean = True; aBuild: Boolean = True): string; var VerInfoSize: DWORD; VerInfo: Pointer; VerValueSize: DWORD; VerValue: PVSFixedFileInfo; Dummy: DWORD; strBuffer: array [0 .. MAX_PATH] of Char; begin GetModuleFileName(hInstance, strBuffer, MAX_PATH); VerInfoSize := GetFileVersionInfoSize(strBuffer, Dummy); if VerInfoSize <> 0 then begin GetMem(VerInfo, VerInfoSize); try GetFileVersionInfo(strBuffer, 0, VerInfoSize, VerInfo); VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize); with VerValue^ do begin Result := IntToStr(dwFileVersionMS shr 16); // Major always there if aMinor then Result := Result + '.' + IntToStr(dwFileVersionMS and $FFFF); if aRelease then Result := Result + '.' + IntToStr(dwFileVersionLS shr 16); if aBuild then Result := Result + '.' + IntToStr(dwFileVersionLS and $FFFF); end; finally FreeMem(VerInfo, VerInfoSize); end; end else Result := '1.0.0.0'; end; const ICON_SPLASH = 'TNCICON'; ICON_ABOUT = 'TNCICON'; var AboutBoxServices: IOTAAboutBoxServices = nil; AboutBoxIndex: Integer = 0; resourcestring resPackageName = 'NetCom7 Network Communications Framework'; resLicence = 'Full Edition for RAD Studio'; resAboutCopyright = 'Copyright © 2020 Bill Demos (VasDemos@yahoo.co.uk)'; resAboutDescription = 'Netcom7 Communicatios Framework enables you to use communication components with the ease of use of the Delphi programming language. Create and handle client/server sockets, sources and DB elements with no single line of API calls.'; procedure RegisterSplashScreen; var SplashScreenHandle: HBitmap; begin SplashScreenHandle := LoadBitmap(hInstance, ICON_SPLASH); try SplashScreenServices.AddPluginBitmap(resPackageName + ' ' + GetVersion, SplashScreenHandle, False, resLicence); finally DeleteObject(SplashScreenHandle); end; end; procedure RegisterAboutBox; var ProductImage: HBitmap; begin Supports(BorlandIDEServices, IOTAAboutBoxServices, AboutBoxServices); ProductImage := LoadBitmap(FindResourceHInstance(hInstance), ICON_ABOUT); AboutBoxIndex := AboutBoxServices.AddPluginInfo(resPackageName + GetVersion, resAboutCopyright + #13#10 + resAboutDescription, ProductImage, False, resLicence); end; procedure UnregisterAboutBox; begin if (AboutBoxIndex <> 0) and Assigned(AboutBoxServices) then begin AboutBoxServices.RemovePluginInfo(AboutBoxIndex); AboutBoxIndex := 0; AboutBoxServices := nil; end; end; { TncTCPSocketDefaultEditor } procedure TncTCPSocketDefaultEditor.EditProperty(const Prop: IProperty; var Continue: Boolean); begin if CompareText(Prop.GetName, 'ONREADDATA') = 0 then begin Prop.Edit; Continue := False; end else inherited; end; { TncCustomPeerSourceDefaultEditor } procedure TncSourceDefaultEditor.EditProperty(const Prop: IProperty; var Continue: Boolean); begin if CompareText(Prop.GetName, 'ONHANDLECOMMAND') = 0 then begin Prop.Edit; Continue := False; end else inherited; end; initialization RegisterSplashScreen; RegisterAboutBox; finalization UnregisterAboutBox; end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLImageUtils<p> Main purpose is as a fallback in cases where there is no other way to process images.<p> <b>Historique : </b><font size=-1><ul> <li>07/09/11 - Yar - Bugfixed memory overrun in Build2DMipmap (thanks to benok1) <li>09/04/11 - Yar - Added AlphaGammaBrightCorrection <li>08/04/11 - Yar - Complete Build2DMipmap <li>07/11/10 - YP - Inline removed from local functions with external var access (Fixes error E2449) <li>04/11/10 - DaStr - Added $I GLScene.inc <li>22/10/10 - Yar - Created </ul></font> } unit GLImageUtils; // DONE: ConvertImage // TODO: Complite InfToXXX // DONE: S3TC decompression // DONE: LATC decompression // DONE: RGTC decompression // TODO: BPTC decompression // TODO: S3TC compression // TODO: LATC compression // TODO: RGTC compression // TODO: BPTC compression // DONE: ResizeImage // DONE: Build2DMipmap // TODO: Build3DMipmap interface {$I GLScene.inc} uses System.SysUtils, System.Classes, System.Math, GLCrossPlatform, OpenGLTokens, GLTextureFormat, GLVectorGeometry; var vImageScaleFilterWidth: Integer = 5; // Relative sample radius for filtering type TIntermediateFormat = record R, G, B, A: Single; end; TPointerArray = array of Pointer; PRGBA32F = ^TIntermediateFormat; TIntermediateFormatArray = array [0 .. MaxInt div (2 * SizeOf(TIntermediateFormat))] of TIntermediateFormat; PIntermediateFormatArray = ^TIntermediateFormatArray; TU48BitBlock = array [0 .. 3, 0 .. 3] of Byte; T48BitBlock = array [0 .. 3, 0 .. 3] of SmallInt; EGLImageUtils = class(Exception); TImageFilterFunction = function(Value: Single): Single; TImageAlphaProc = procedure(var AColor: TIntermediateFormat); function ImageBoxFilter(Value: Single): Single; function ImageTriangleFilter(Value: Single): Single; function ImageHermiteFilter(Value: Single): Single; function ImageBellFilter(Value: Single): Single; function ImageSplineFilter(Value: Single): Single; function ImageLanczos3Filter(Value: Single): Single; function ImageMitchellFilter(Value: Single): Single; procedure ImageAlphaFromIntensity(var AColor: TIntermediateFormat); procedure ImageAlphaSuperBlackTransparent(var AColor: TIntermediateFormat); procedure ImageAlphaLuminance(var AColor: TIntermediateFormat); procedure ImageAlphaLuminanceSqrt(var AColor: TIntermediateFormat); procedure ImageAlphaOpaque(var AColor: TIntermediateFormat); procedure ImageAlphaTopLeftPointColorTransparent(var AColor: TIntermediateFormat); procedure ImageAlphaInverseLuminance(var AColor: TIntermediateFormat); procedure ImageAlphaInverseLuminanceSqrt(var AColor: TIntermediateFormat); procedure ImageAlphaBottomRightPointColorTransparent(var AColor: TIntermediateFormat); procedure ConvertImage(const ASrc: Pointer; const ADst: Pointer; ASrcColorFormat, ADstColorFormat: TGLEnum; ASrcDataType, ADstDataType: TGLEnum; AWidth, AHeight: Integer); procedure RescaleImage(const ASrc: Pointer; const ADst: Pointer; AColorFormat: TGLEnum; ADataType: TGLEnum; AFilter: TImageFilterFunction; ASrcWidth, ASrcHeight, ADstWidth, ADstHeight: Integer); procedure Build2DMipmap(const ASrc: Pointer; const ADst: TPointerArray; AColorFormat: TGLEnum; ADataType: TGLEnum; AFilter: TImageFilterFunction; ASrcWidth, ASrcHeight: Integer); procedure AlphaGammaBrightCorrection(const ASrc: Pointer; AColorFormat: TGLEnum; ADataType: TGLEnum; ASrcWidth, ASrcHeight: Integer; anAlphaProc: TImageAlphaProc; ABrightness: Single; AGamma: Single); implementation resourcestring strInvalidType = 'Invalid data type'; const cSuperBlack: TIntermediateFormat = (R: 0.0; G: 0.0; B: 0.0; A: 0.0); type TConvertToImfProc = procedure(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); TConvertFromInfProc = procedure(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); procedure Swap(var A, B: Integer); {$IFDEF GLS_INLINE} inline; {$ENDIF} var C: Integer; begin C := A; A := B; B := C; end; {$IFDEF GLS_REGIONS}{$REGION 'OpenGL format image to RGBA Float'}{$ENDIF} procedure UnsupportedToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); begin raise EGLImageUtils.Create('Unimplemented type of conversion'); end; procedure UbyteToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^; Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure Ubyte332ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; c0, c1, c2, c3: Byte; n: Integer; procedure GetChannel; begin c0 := pSource^; c1 := $E0 and c0; c2 := $E0 and (c0 shl 3); c3 := $C0 and (c0 shl 6); Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGB: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; end; GL_BGR: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure Ubyte233RToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; c0, c1, c2, c3: Byte; n: Integer; procedure GetChannel; begin c0 := pSource^; c3 := $E0 and c0; c2 := $E0 and (c0 shl 3); c1 := $C0 and (c0 shl 6); Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGB: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; end; GL_BGR: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ByteToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PShortInt; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^; Inc(pSource); end; begin pSource := PShortInt(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShortToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PWord; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^ / $100; Inc(pSource); end; begin pSource := PWord(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ShortToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PSmallInt; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^ / $100; Inc(pSource); end; begin pSource := PSmallInt(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UIntToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PLongWord; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^ / $1000000; Inc(pSource); end; begin pSource := PLongWord(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure IntToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PLongInt; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^ / $1000000; Inc(pSource); end; begin pSource := PLongInt(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure FloatToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PSingle; n: Integer; c0: Single; function GetChannel: Single; begin Result := pSource^ * 255.0; Inc(pSource); end; begin pSource := PSingle(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure HalfFloatToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PHalfFloat; n: Integer; c0: Single; function GetChannel: Single; begin Result := HalfToFloat(pSource^) * 255.0; Inc(pSource); end; begin pSource := PHalfFloat(ASource); case AColorFormat of {$INCLUDE ImgUtilCaseGL2Imf.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UInt8888ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; n: Integer; c0, c1, c2, c3: Byte; procedure GetChannel; begin c0 := pSource^; Inc(pSource); c1 := pSource^; Inc(pSource); c2 := pSource^; Inc(pSource); c3 := pSource^; Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c0; ADest[n].G := c1; ADest[n].B := c2; ADest[n].A := c3; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c0; ADest[n].G := c1; ADest[n].R := c2; ADest[n].A := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UInt8888RevToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; n: Integer; c0, c1, c2, c3: Byte; procedure GetChannel; begin c3 := pSource^; Inc(pSource); c2 := pSource^; Inc(pSource); c1 := pSource^; Inc(pSource); c0 := pSource^; Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c0; ADest[n].G := c1; ADest[n].B := c2; ADest[n].A := c3; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c0; ADest[n].G := c1; ADest[n].R := c2; ADest[n].A := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort4444ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; n: Integer; c0, c1, c2, c3, c4: Byte; procedure GetChannel; begin c0 := pSource^; c3 := $F0 and (c0 shl 4); c4 := $F0 and c0; Inc(pSource); c0 := pSource^; c1 := $F0 and (c0 shl 4); c2 := $F0 and c0; Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort4444RevToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PByte; n: Integer; c0, c1, c2, c3, c4: Byte; procedure GetChannel; begin c0 := pSource^; c1 := $F0 and (c0 shl 4); c2 := $F0 and c0; Inc(pSource); c0 := pSource^; c3 := $F0 and (c0 shl 4); c4 := $F0 and c0; Inc(pSource); end; begin pSource := PByte(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort565ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PWord; n: Integer; c0: Word; c1, c2, c3: Byte; procedure GetChannel; begin c0 := pSource^; c3 := (c0 and $001F) shl 3; c2 := (c0 and $07E0) shr 3; c1 := (c0 and $F800) shr 8; Inc(pSource); end; begin pSource := PWord(ASource); case AColorFormat of GL_RGB, GL_RGB_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; end; GL_BGR, GL_BGR_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort565RevToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PWord; n: Integer; c0: Word; c1, c2, c3: Byte; procedure GetChannel; begin c0 := pSource^; c1 := (c0 and $001F) shl 3; c2 := (c0 and $07E0) shr 3; c3 := (c0 and $F800) shr 8; Inc(pSource); end; begin pSource := PWord(ASource); case AColorFormat of GL_RGB, GL_RGB_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; end; GL_BGR, GL_BGR_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort5551ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PWord; n: Integer; c0: Word; c1, c2, c3, c4: Byte; procedure GetChannel; begin c0 := pSource^; c4 := (c0 and $001F) shl 3; c3 := (c0 and $03E0) shr 2; c2 := (c0 and $7C00) shr 7; c1 := (c0 and $8000) shr 8; Inc(pSource); end; begin pSource := PWord(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UShort5551RevToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PWord; n: Integer; c0: Word; c1, c2, c3, c4: Byte; procedure GetChannel; begin c0 := pSource^; c1 := (c0 and $001F) shl 3; c2 := (c0 and $03E0) shr 2; c3 := (c0 and $7C00) shr 7; c4 := (c0 and $8000) shr 8; Inc(pSource); end; begin pSource := PWord(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1; ADest[n].G := c2; ADest[n].B := c3; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1; ADest[n].G := c2; ADest[n].R := c3; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UInt_10_10_10_2_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PLongWord; n: Integer; c0: LongWord; c1, c2, c3, c4: Word; procedure GetChannel; begin c0 := pSource^; c1 := (c0 and $000003FF) shl 6; c2 := (c0 and $000FFC00) shr 4; c3 := (c0 and $3FF00000) shr 14; c4 := (c0 and $C0000000) shr 16; Inc(pSource); end; begin pSource := PLongWord(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1 / $100; ADest[n].G := c2 / $100; ADest[n].B := c3 / $100; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1 / $100; ADest[n].G := c2 / $100; ADest[n].R := c3 / $100; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; procedure UInt_10_10_10_2_Rev_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pSource: PLongWord; n: Integer; c0: LongWord; c1, c2, c3, c4: Word; procedure GetChannel; begin c0 := pSource^; c1 := (c0 and $000003FF) shl 6; c2 := (c0 and $000FFC00) shr 4; c3 := (c0 and $3FF00000) shr 14; c4 := (c0 and $C0000000) shr 16; Inc(pSource); end; begin pSource := PLongWord(ASource); case AColorFormat of GL_RGBA, GL_RGBA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].R := c1 / $100; ADest[n].G := c2 / $100; ADest[n].B := c3 / $100; ADest[n].A := c4; end; GL_BGRA, GL_BGRA_INTEGER: for n := 0 to AWidth * AHeight - 1 do begin GetChannel; ADest[n].B := c1 / $100; ADest[n].G := c2 / $100; ADest[n].R := c3 / $100; ADest[n].A := c4; end; else raise EGLImageUtils.Create(strInvalidType); end; end; {$IFDEF GLS_REGIONS}{$ENDREGION}{$ENDIF} {$IFDEF GLS_REGIONS}{$REGION 'Decompression'}{$ENDIF} procedure DecodeColor565(col: Word; out R, G, B: Byte); begin R := col and $1F; G := (col shr 5) and $3F; B := (col shr 11) and $1F; end; procedure DXT1_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, k, select, offset: Integer; col0, col1: Word; colors: TU48BitBlock; bitmask: Cardinal; temp: PGLubyte; r0, g0, b0, r1, g1, b1: Byte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin col0 := PWord(temp)^; Inc(temp, 2); col1 := PWord(temp)^; Inc(temp, 2); bitmask := PCardinal(temp)^; Inc(temp, 4); DecodeColor565(col0, r0, g0, b0); DecodeColor565(col1, r1, g1, b1); colors[0][0] := r0 shl 3; colors[0][1] := g0 shl 2; colors[0][2] := b0 shl 3; colors[0][3] := $FF; colors[1][0] := r1 shl 3; colors[1][1] := g1 shl 2; colors[1][2] := b1 shl 3; colors[1][3] := $FF; if col0 > col1 then begin colors[2][0] := (2 * colors[0][0] + colors[1][0] + 1) div 3; colors[2][1] := (2 * colors[0][1] + colors[1][1] + 1) div 3; colors[2][2] := (2 * colors[0][2] + colors[1][2] + 1) div 3; colors[2][3] := $FF; colors[3][0] := (colors[0][0] + 2 * colors[1][0] + 1) div 3; colors[3][1] := (colors[0][1] + 2 * colors[1][1] + 1) div 3; colors[3][2] := (colors[0][2] + 2 * colors[1][2] + 1) div 3; colors[3][3] := $FF; end else begin colors[2][0] := (colors[0][0] + colors[1][0]) div 2; colors[2][1] := (colors[0][1] + colors[1][1]) div 2; colors[2][2] := (colors[0][2] + colors[1][2]) div 2; colors[2][3] := $FF; colors[3][0] := (colors[0][0] + 2 * colors[1][0] + 1) div 3; colors[3][1] := (colors[0][1] + 2 * colors[1][1] + 1) div 3; colors[3][2] := (colors[0][2] + 2 * colors[1][2] + 1) div 3; colors[3][3] := 0; end; k := 0; for j := 0 to 3 do begin for i := 0 to 3 do begin select := (bitmask and (3 shl (k * 2))) shr (k * 2); if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].B := colors[select][0]; ADest[offset].G := colors[select][1]; ADest[offset].R := colors[select][2]; ADest[offset].A := colors[select][3]; end; Inc(k); end; end; end; end; end; procedure DXT3_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, k, select: Integer; col0, col1, wrd: Word; colors: TU48BitBlock; bitmask, offset: Cardinal; temp: PGLubyte; r0, g0, b0, r1, g1, b1: Byte; alpha: array [0 .. 3] of Word; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin alpha[0] := PWord(temp)^; Inc(temp, 2); alpha[1] := PWord(temp)^; Inc(temp, 2); alpha[2] := PWord(temp)^; Inc(temp, 2); alpha[3] := PWord(temp)^; Inc(temp, 2); col0 := PWord(temp)^; Inc(temp, 2); col1 := PWord(temp)^; Inc(temp, 2); bitmask := PCardinal(temp)^; Inc(temp, 4); DecodeColor565(col0, r0, g0, b0); DecodeColor565(col1, r1, g1, b1); colors[0][0] := r0 shl 3; colors[0][1] := g0 shl 2; colors[0][2] := b0 shl 3; colors[0][3] := $FF; colors[1][0] := r1 shl 3; colors[1][1] := g1 shl 2; colors[1][2] := b1 shl 3; colors[1][3] := $FF; colors[2][0] := (2 * colors[0][0] + colors[1][0] + 1) div 3; colors[2][1] := (2 * colors[0][1] + colors[1][1] + 1) div 3; colors[2][2] := (2 * colors[0][2] + colors[1][2] + 1) div 3; colors[2][3] := $FF; colors[3][0] := (colors[0][0] + 2 * colors[1][0] + 1) div 3; colors[3][1] := (colors[0][1] + 2 * colors[1][1] + 1) div 3; colors[3][2] := (colors[0][2] + 2 * colors[1][2] + 1) div 3; colors[3][3] := $FF; k := 0; for j := 0 to 3 do begin for i := 0 to 3 do begin select := (bitmask and (3 shl (k * 2))) shr (k * 2); if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].B := colors[select][0]; ADest[offset].G := colors[select][1]; ADest[offset].R := colors[select][2]; ADest[offset].A := colors[select][3]; end; Inc(k); end; end; for j := 0 to 3 do begin wrd := alpha[j]; for i := 0 to 3 do begin if (((4 * x + i) < AWidth) and ((4 * y + j) < AHeight)) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); r0 := wrd and $0F; ADest[offset].A := r0 or (r0 shl 4); end; wrd := wrd shr 4; end; end; end; end; end; procedure DXT5_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, k, select, offset: Integer; col0, col1: Word; colors: TU48BitBlock; bits, bitmask: Cardinal; temp, alphamask: PGLubyte; r0, g0, b0, r1, g1, b1: Byte; alphas: array [0 .. 7] of Byte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin alphas[0] := temp^; Inc(temp); alphas[1] := temp^; Inc(temp); alphamask := temp; Inc(temp, 6); col0 := PWord(temp)^; Inc(temp, 2); col1 := PWord(temp)^; Inc(temp, 2); bitmask := PCardinal(temp)^; Inc(temp, 4); DecodeColor565(col0, r0, g0, b0); DecodeColor565(col1, r1, g1, b1); colors[0][0] := r0 shl 3; colors[0][1] := g0 shl 2; colors[0][2] := b0 shl 3; colors[0][3] := $FF; colors[1][0] := r1 shl 3; colors[1][1] := g1 shl 2; colors[1][2] := b1 shl 3; colors[1][3] := $FF; colors[2][0] := (2 * colors[0][0] + colors[1][0] + 1) div 3; colors[2][1] := (2 * colors[0][1] + colors[1][1] + 1) div 3; colors[2][2] := (2 * colors[0][2] + colors[1][2] + 1) div 3; colors[2][3] := $FF; colors[3][0] := (colors[0][0] + 2 * colors[1][0] + 1) div 3; colors[3][1] := (colors[0][1] + 2 * colors[1][1] + 1) div 3; colors[3][2] := (colors[0][2] + 2 * colors[1][2] + 1) div 3; colors[3][3] := $FF; k := 0; for j := 0 to 3 do begin for i := 0 to 3 do begin select := (bitmask and (3 shl (k * 2))) shr (k * 2); if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].B := colors[select][0]; ADest[offset].G := colors[select][1]; ADest[offset].R := colors[select][2]; end; Inc(k); end; end; if (alphas[0] > alphas[1]) then begin alphas[2] := (6 * alphas[0] + 1 * alphas[1] + 3) div 7; alphas[3] := (5 * alphas[0] + 2 * alphas[1] + 3) div 7; alphas[4] := (4 * alphas[0] + 3 * alphas[1] + 3) div 7; alphas[5] := (3 * alphas[0] + 4 * alphas[1] + 3) div 7; alphas[6] := (2 * alphas[0] + 5 * alphas[1] + 3) div 7; alphas[7] := (1 * alphas[0] + 6 * alphas[1] + 3) div 7; end else begin alphas[2] := (4 * alphas[0] + 1 * alphas[1] + 2) div 5; alphas[3] := (3 * alphas[0] + 2 * alphas[1] + 2) div 5; alphas[4] := (2 * alphas[0] + 3 * alphas[1] + 2) div 5; alphas[5] := (1 * alphas[0] + 4 * alphas[1] + 2) div 5; alphas[6] := 0; alphas[7] := $FF; end; bits := PCardinal(alphamask)^; for j := 0 to 1 do begin for i := 0 to 3 do begin if (((4 * x + i) < AWidth) and ((4 * y + j) < AHeight)) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].A := alphas[bits and 7]; end; bits := bits shr 3; end; end; Inc(alphamask, 3); bits := PCardinal(alphamask)^; for j := 2 to 3 do begin for i := 0 to 3 do begin if (((4 * x + i) < AWidth) and ((4 * y + j) < AHeight)) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].A := alphas[bits and 7]; end; bits := bits shr 3; end; end; end; end; end; procedure Decode48BitBlock(ACode: Int64; out ABlock: TU48BitBlock); overload; var x, y: Byte; begin for y := 0 to 3 do for x := 0 to 3 do begin ABlock[x][y] := Byte(ACode and $03); ACode := ACode shr 2; end; end; procedure Decode48BitBlock(ACode: Int64; out ABlock: T48BitBlock); overload; var x, y: Byte; begin for y := 0 to 3 do for x := 0 to 3 do begin ABlock[x][y] := SmallInt(ACode and $03); ACode := ACode shr 2; end; end; procedure LATC1_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; LUM0, LUM1: Byte; lum: Single; colors: TU48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin LUM0 := temp^; Inc(temp); LUM1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := colors[j, i]; ADest[offset].R := lum; ADest[offset].G := lum; ADest[offset].B := lum; ADest[offset].A := 255.0; end; end; end; end; end; end; procedure SLATC1_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; LUM0, LUM1: SmallInt; lum: Single; colors: T48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin LUM0 := PSmallInt(temp)^; Inc(temp); LUM1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := 2 * colors[j, i]; ADest[offset].R := lum; ADest[offset].G := lum; ADest[offset].B := lum; ADest[offset].A := 127.0; end; end; end; end; end; end; procedure LATC2_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; LUM0, LUM1: Byte; lum: Single; colors: TU48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin LUM0 := temp^; Inc(temp); LUM1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := colors[j][i]; ADest[offset].R := lum; ADest[offset].G := lum; ADest[offset].B := lum; end; end; // for i end; // for j LUM0 := temp^; Inc(temp); LUM1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then ADest[((4 * y + j) * AWidth + (4 * x + i))].A := colors[j][i]; end; end; end; end; end; procedure SLATC2_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; LUM0, LUM1: SmallInt; lum: Single; colors: T48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin LUM0 := PSmallInt(temp)^; Inc(temp); LUM1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := 2 * colors[j][i]; ADest[offset].R := lum; ADest[offset].G := lum; ADest[offset].B := lum; end; end; end; LUM0 := PSmallInt(temp)^; Inc(temp); LUM1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if LUM0 > LUM1 then case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (6 * LUM0 + LUM1) div 7; 3: colors[j, i] := (5 * LUM0 + 2 * LUM1) div 7; 4: colors[j, i] := (4 * LUM0 + 3 * LUM1) div 7; 5: colors[j, i] := (3 * LUM0 + 4 * LUM1) div 7; 6: colors[j, i] := (2 * LUM0 + 5 * LUM1) div 7; 7: colors[j, i] := (LUM0 + 6 * LUM1) div 7; end else case colors[j, i] of 0: colors[j, i] := LUM0; 1: colors[j, i] := LUM1; 2: colors[j, i] := (4 * LUM0 + LUM1) div 5; 3: colors[j, i] := (3 * LUM0 + 2 * LUM1) div 5; 4: colors[j, i] := (2 * LUM0 + 3 * LUM1) div 5; 5: colors[j, i] := (LUM0 + 4 * LUM1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin ADest[((4 * y + j) * AWidth + (4 * x + i))].A := 2 * colors[j][i]; end; end; end; end; end; end; procedure RGTC1_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; RED0, RED1: Byte; lum: Single; colors: TU48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin RED0 := temp^; Inc(temp); RED1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)) * 4; lum := colors[j][i]; ADest[offset].R := lum; ADest[offset].G := 0.0; ADest[offset].B := 0.0; ADest[offset].A := 255.0; end; end; end; end; end; end; procedure SRGTC1_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; RED0, RED1: SmallInt; lum: Single; colors: T48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin RED0 := PSmallInt(temp)^; Inc(temp); RED1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := 2 * colors[j][i]; ADest[offset].R := lum; ADest[offset].G := 0.0; ADest[offset].B := 0.0; ADest[offset].A := 127.0; end; end; end; end; end; end; procedure RGTC2_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; RED0, RED1: Byte; colors: TU48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin RED0 := temp^; Inc(temp); RED1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].R := colors[j][i]; ADest[offset].B := 0.0; end; end; end; RED0 := temp^; Inc(temp); RED1 := temp^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := 0; 7: colors[j, i] := 255; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); ADest[offset].G := colors[j][i]; ADest[offset].A := 255.0; end; end; end; end; end; end; procedure SRGTC2_ToImf(ASource: Pointer; ADest: PIntermediateFormatArray; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var x, y, i, j, offset: Integer; RED0, RED1: SmallInt; lum: Single; colors: T48BitBlock; bitmask: Int64; temp: PGLubyte; begin temp := PGLubyte(ASource); for y := 0 to (AHeight div 4) - 1 do begin for x := 0 to (AWidth div 4) - 1 do begin RED0 := PSmallInt(temp)^; Inc(temp); RED1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := 2 * colors[j][i]; ADest[offset].R := lum; ADest[offset].B := 0.0; end; end; end; RED0 := PSmallInt(temp)^; Inc(temp); RED1 := PSmallInt(temp)^; Inc(temp); bitmask := PInt64(temp)^; Inc(temp, 6); Decode48BitBlock(bitmask, colors); for j := 0 to 3 do begin for i := 0 to 3 do begin if RED0 > RED1 then case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (6 * RED0 + RED1) div 7; 3: colors[j, i] := (5 * RED0 + 2 * RED1) div 7; 4: colors[j, i] := (4 * RED0 + 3 * RED1) div 7; 5: colors[j, i] := (3 * RED0 + 4 * RED1) div 7; 6: colors[j, i] := (2 * RED0 + 5 * RED1) div 7; 7: colors[j, i] := (RED0 + 6 * RED1) div 7; end else case colors[j, i] of 0: colors[j, i] := RED0; 1: colors[j, i] := RED1; 2: colors[j, i] := (4 * RED0 + RED1) div 5; 3: colors[j, i] := (3 * RED0 + 2 * RED1) div 5; 4: colors[j, i] := (2 * RED0 + 3 * RED1) div 5; 5: colors[j, i] := (RED0 + 4 * RED1) div 5; 6: colors[j, i] := -127; 7: colors[j, i] := 127; end; if ((4 * x + i) < AWidth) and ((4 * y + j) < AHeight) then begin offset := ((4 * y + j) * AWidth + (4 * x + i)); lum := 2 * colors[j][i]; ADest[offset].G := lum; ADest[offset].A := 127.0; end; end; end; end; end; end; {$IFDEF GLS_REGIONS}{$ENDREGION 'Decompression'}{$ENDIF} {$IFDEF GLS_REGIONS}{$REGION 'RGBA Float to OpenGL format image'}{$ENDIF} procedure UnsupportedFromImf(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); begin raise EGLImageUtils.Create('Unimplemented type of conversion'); end; procedure ImfToUbyte(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PByte; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, 0.0, 255.0)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PByte(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToByte(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PShortInt; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, -127.0, 127.0)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PShortInt(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToUShort(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PWord; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, 0.0, 65535.0)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PWord(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToShort(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PSmallInt; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, -32767.0, 32767.0)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PSmallInt(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToUInt(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PLongWord; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, 0.0, $FFFFFFFF)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PLongWord(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToInt(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); var pDest: PLongInt; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := Trunc(ClampValue(AValue, -$7FFFFFFF, $7FFFFFFF)); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := Trunc(AValue); Inc(pDest); end; begin pDest := PLongInt(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToFloat(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); const cInv255 = 1.0 / 255.0; var pDest: PSingle; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := AValue * cInv255; Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := AValue * cInv255; Inc(pDest); end; begin pDest := PSingle(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; procedure ImfToHalf(ASource: PIntermediateFormatArray; ADest: Pointer; AColorFormat: TGLEnum; AWidth, AHeight: Integer); const cInv255 = 1.0 / 255.0; var pDest: PHalfFloat; n: Integer; procedure SetChannel(AValue: Single); begin pDest^ := FloatToHalf(AValue * cInv255); Inc(pDest); end; procedure SetChannelI(AValue: Single); begin pDest^ := FloatToHalf(AValue * cInv255); Inc(pDest); end; begin pDest := PHalfFloat(ADest); case AColorFormat of {$INCLUDE ImgUtilCaseImf2GL.inc} else raise EGLImageUtils.Create(strInvalidType); end; end; {$IFDEF GLS_REGIONS}{$ENDREGION 'RGBA Float to OpenGL format image'}{$ENDIF} {$IFDEF GLS_REGIONS}{$REGION 'Compression'}{$ENDIF} { function FloatTo565(const AColor: TIntermediateFormat): Integer; var r, g, b: Integer; begin // get the components in the correct range r := Round( 31.0*AColor.R, 31 ); g := Round( 63.0*AColor.G, 63 ); b := Round( 31.0*AColor.B, 31 ); // pack into a single value Result := ( r shl 11 ) or ( g shl 5 ) or b; end; procedure WriteColourBlock(a, b: Integer; const indices: PByteArray; out block: TU48BitBlock); var I, J: Byte; begin // write the endpoints block[0][0] := a and $ff; block[0][1] := a shr 8; block[0][2] := b and $ff; block[0][3] := b shr 8; // write the indices for i := 0 to 3 do begin J := 4*i; block[1][i] = indices[J+0] or ( indices[J+1] shl 2 ) or ( indices[J+2] shl 4 ) or ( indices[J+3] shl 6 ); end; end; procedure WriteColourBlock3(start, end_: TIntermediateFormat; const indices: PByteArray; out block: TU48BitBlock); var i, a, b: Integer; remapped: array[0..15] of Byte; begin // get the packed values a := FloatTo565( start ); b := FloatTo565( end_ ); // remap the indices if a <= b then begin // use the indices directly for i := 0 to 15 do remapped[i] := indices[i]; end else begin // swap a and b Swap( a, b ); for i := 0 to 15 do begin if indices[i] = 0 then remapped[i] := 1 else if indices[i] = 1 then remapped[i] := 0 else remapped[i] := indices[i]; end; end; // write the block WriteColourBlock( a, b, remapped, block ); end; procedure WriteColourBlock4(start, end_: TIntermediateFormat; const indices: PByteArray; out block: TU48BitBlock); var i, a, b: Integer; remapped: array[0..15] of Byte; begin // get the packed values a := FloatTo565( start ); b := FloatTo565( end_ ); // remap the indices if a < b then begin // swap a and b Swap( a, b ); for i := 0 to 15 do remapped[i] := ( indices[i] xor $01 ) and $03; end else if a = b then begin // use index 0 for i := 0 to 15 do remapped[i] := 0; end else begin // use the indices directly for i := 0 to 15 do remapped[i] := indices[i]; end; // write the block WriteColourBlock( a, b, remapped, block ); end; } {$IFDEF GLS_REGIONS}{$ENDREGION 'Compression'}{$ENDIF} {$IFDEF GLS_REGIONS}{$REGION 'Image filters'}{$ENDIF} function ImageBoxFilter(Value: Single): Single; begin if (Value > -0.5) and (Value <= 0.5) then Result := 1.0 else Result := 0.0; end; function ImageTriangleFilter(Value: Single): Single; begin if Value < 0.0 then Value := -Value; if Value < 1.0 then Result := 1.0 - Value else Result := 0.0; end; function ImageHermiteFilter(Value: Single): Single; begin if Value < 0.0 then Value := -Value; if Value < 1 then Result := (2 * Value - 3) * Sqr(Value) + 1 else Result := 0; end; function ImageBellFilter(Value: Single): Single; begin if Value < 0.0 then Value := -Value; if Value < 0.5 then Result := 0.75 - Sqr(Value) else if Value < 1.5 then begin Value := Value - 1.5; Result := 0.5 * Sqr(Value); end else Result := 0.0; end; function ImageSplineFilter(Value: Single): Single; var temp: Single; begin if Value < 0.0 then Value := -Value; if Value < 1.0 then begin temp := Sqr(Value); Result := 0.5 * temp * Value - temp + 2.0 / 3.0; end else if Value < 2.0 then begin Value := 2.0 - Value; Result := Sqr(Value) * Value / 6.0; end else Result := 0.0; end; function ImageLanczos3Filter(Value: Single): Single; const Radius = 3.0; begin Result := 1; if Value = 0 then Exit; if Value < 0.0 then Value := -Value; if Value < Radius then begin Value := Value * pi; Result := Radius * Sin(Value) * Sin(Value / Radius) / (Value * Value); end else Result := 0.0; end; function ImageMitchellFilter(Value: Single): Single; const B = 1.0 / 3.0; C = 1.0 / 3.0; var temp: Single; begin if Value < 0.0 then Value := -Value; temp := Sqr(Value); if Value < 1.0 then begin Value := (((12.0 - 9.0 * B - 6.0 * C) * (Value * temp)) + ((-18.0 + 12.0 * B + 6.0 * C) * temp) + (6.0 - 2.0 * B)); Result := Value / 6.0; end else if Value < 2.0 then begin Value := (((-B - 6.0 * C) * (Value * temp)) + ((6.0 * B + 30.0 * C) * temp) + ((-12.0 * B - 48.0 * C) * Value) + (8.0 * B + 24.0 * C)); Result := Value / 6.0; end else Result := 0.0; end; const cInvThree = 1.0/3.0; procedure ImageAlphaFromIntensity(var AColor: TIntermediateFormat); begin AColor.A := (AColor.R + AColor.B + AColor.G) * cInvThree; end; procedure ImageAlphaSuperBlackTransparent(var AColor: TIntermediateFormat); begin if (AColor.R = 0.0) and (AColor.B = 0.0) and (AColor.G = 0.0) then AColor.A := 0.0 else AColor.A := 255.0; end; procedure ImageAlphaLuminance(var AColor: TIntermediateFormat); begin AColor.A := (AColor.R + AColor.B + AColor.G) * cInvThree; AColor.R := AColor.A; AColor.G := AColor.A; AColor.B := AColor.A; end; procedure ImageAlphaLuminanceSqrt(var AColor: TIntermediateFormat); begin AColor.A := Sqrt((AColor.R + AColor.B + AColor.G) * cInvThree); end; procedure ImageAlphaOpaque(var AColor: TIntermediateFormat); begin AColor.A := 255.0; end; var vTopLeftColor: TIntermediateFormat; procedure ImageAlphaTopLeftPointColorTransparent(var AColor: TIntermediateFormat); begin if CompareMem(@AColor, @vTopLeftColor, 3*SizeOf(Single)) then AColor.A := 0.0; end; procedure ImageAlphaInverseLuminance(var AColor: TIntermediateFormat); begin AColor.A := 255.0 - (AColor.R + AColor.B + AColor.G) * cInvThree; AColor.R := AColor.A; AColor.G := AColor.A; AColor.B := AColor.A; end; procedure ImageAlphaInverseLuminanceSqrt(var AColor: TIntermediateFormat); begin AColor.A := 255.0 - Sqrt((AColor.R + AColor.B + AColor.G) * cInvThree); end; var vBottomRightColor: TIntermediateFormat; procedure ImageAlphaBottomRightPointColorTransparent(var AColor: TIntermediateFormat); begin if CompareMem(@AColor, @vBottomRightColor, 3*SizeOf(Single)) then AColor.A := 0.0; end; type // Contributor for a pixel TContributor = record pixel: Integer; // Source pixel weight: Single; // Pixel weight end; TContributorList = array [0 .. MaxInt div (2 * SizeOf(TContributor))] of TContributor; PContributorList = ^TContributorList; // List of source pixels contributing to a destination pixel TCList = record n: Integer; p: PContributorList; end; TCListList = array [0 .. MaxInt div (2 * SizeOf(TCList))] of TCList; PCListList = ^TCListList; {$IFDEF GLS_REGIONS}{$ENDREGION 'Image filters'}{$ENDIF} {$IFDEF GLS_REGIONS}{$REGION 'Data type conversion table'}{$ENDIF} type TConvertTableRec = record type_: TGLEnum; proc1: TConvertToImfProc; proc2: TConvertFromInfProc; end; const cConvertTable: array [0 .. 36] of TConvertTableRec = ( (type_: GL_UNSIGNED_BYTE; proc1: UbyteToImf; proc2: ImfToUbyte), (type_: GL_UNSIGNED_BYTE_3_3_2; proc1: Ubyte332ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_BYTE_2_3_3_REV; proc1: Ubyte233RToImf; proc2: UnsupportedFromImf), (type_: GL_BYTE; proc1: ByteToImf; proc2: ImfToByte), (type_: GL_UNSIGNED_SHORT; proc1: UShortToImf; proc2: ImfToUShort), (type_: GL_SHORT; proc1: ShortToImf; proc2: ImfToShort), (type_: GL_UNSIGNED_INT; proc1: UIntToImf; proc2: ImfToUInt), (type_: GL_INT; proc1: IntToImf; proc2: ImfToInt), (type_: GL_FLOAT; proc1: FloatToImf; proc2: ImfToFloat), (type_: GL_HALF_FLOAT; proc1: HalfFloatToImf; proc2: ImfToHalf), (type_: GL_UNSIGNED_INT_8_8_8_8; proc1: UInt8888ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_INT_8_8_8_8_REV; proc1: UInt8888RevToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_4_4_4_4; proc1: UShort4444ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_4_4_4_4_REV; proc1: UShort4444RevToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_5_6_5; proc1: UShort565ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_5_6_5_REV; proc1: UShort565RevToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_5_5_5_1; proc1: UShort5551ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_SHORT_1_5_5_5_REV; proc1: UShort5551RevToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_INT_10_10_10_2; proc1: UInt_10_10_10_2_ToImf; proc2: UnsupportedFromImf), (type_: GL_UNSIGNED_INT_2_10_10_10_REV; proc1: UInt_10_10_10_2_Rev_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RGB_S3TC_DXT1_EXT; proc1: DXT1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; proc1: DXT1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; proc1: DXT3_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; proc1: DXT5_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SRGB_S3TC_DXT1_EXT; proc1: UnsupportedToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; proc1: UnsupportedToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; proc1: UnsupportedToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; proc1: UnsupportedToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_LUMINANCE_LATC1_EXT; proc1: LATC1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT; proc1: SLATC1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; proc1: LATC2_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT; proc1: SLATC2_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_LUMINANCE_ALPHA_3DC_ATI; proc1: UnsupportedToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RED_RGTC1; proc1: RGTC1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SIGNED_RED_RGTC1; proc1: SRGTC1_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_RG_RGTC2; proc1: RGTC2_ToImf; proc2: UnsupportedFromImf), (type_: GL_COMPRESSED_SIGNED_RG_RGTC2; proc1: SRGTC2_ToImf; proc2: UnsupportedFromImf)); {$IFDEF GLS_REGIONS}{$ENDREGION 'Data type conversion table'}{$ENDIF} procedure ConvertImage(const ASrc: Pointer; const ADst: Pointer; ASrcColorFormat, ADstColorFormat: TGLEnum; ASrcDataType, ADstDataType: TGLEnum; AWidth, AHeight: Integer); var ConvertToIntermediateFormat: TConvertToImfProc; ConvertFromIntermediateFormat: TConvertFromInfProc; i, size: Integer; tempBuf: PIntermediateFormatArray; begin if AWidth < 1 then Exit; AHeight := MaxInteger(1, AHeight); // Allocate memory size := AWidth * AHeight * SizeOf(TIntermediateFormat); GetMem(tempBuf, size); FillChar(tempBuf^, size, $00); // Find function to convert external format to intermediate format ConvertToIntermediateFormat := UnsupportedToImf; for i := 0 to high(cConvertTable) do begin if ASrcDataType = cConvertTable[i].type_ then begin ConvertToIntermediateFormat := cConvertTable[i].proc1; break; end; end; try ConvertToIntermediateFormat(ASrc, tempBuf, ASrcColorFormat, AWidth, AHeight); except FreeMem(tempBuf); raise; end; // Find function to convert intermediate format to external format ConvertFromIntermediateFormat := UnsupportedFromImf; for i := 0 to high(cConvertTable) do begin if ADstDataType = cConvertTable[i].type_ then begin ConvertFromIntermediateFormat := cConvertTable[i].proc2; break; end; end; try ConvertFromIntermediateFormat(tempBuf, ADst, ADstColorFormat, AWidth, AHeight); except FreeMem(tempBuf); raise; end; FreeMem(tempBuf); end; procedure RescaleImage( const ASrc: Pointer; const ADst: Pointer; AColorFormat: TGLEnum; ADataType: TGLEnum; AFilter: TImageFilterFunction; ASrcWidth, ASrcHeight, ADstWidth, ADstHeight: Integer); var ConvertToIntermediateFormat: TConvertToImfProc; ConvertFromIntermediateFormat: TConvertFromInfProc; i, j, k, n, size: Integer; tempBuf1, tempBuf2, SourceLine, DestLine: PIntermediateFormatArray; contrib: PCListList; xscale, yscale: Single; // Zoom scale factors width, fscale, weight: Single; // Filter calculation variables center: Single; // Filter calculation variables left, right: Integer; // Filter calculation variables color1, color2: TIntermediateFormat; begin if (ASrcWidth < 1) or (ADstWidth < 1) then Exit; ASrcHeight := MaxInteger(1, ASrcHeight); ADstHeight := MaxInteger(1, ADstHeight); // Allocate memory size := ASrcWidth * ASrcHeight * SizeOf(TIntermediateFormat); GetMem(tempBuf1, size); FillChar(tempBuf1^, size, $00); // Find function to convert external format to intermediate format ConvertToIntermediateFormat := UnsupportedToImf; for i := 0 to high(cConvertTable) do begin if ADataType = cConvertTable[i].type_ then begin ConvertToIntermediateFormat := cConvertTable[i].proc1; ConvertFromIntermediateFormat := cConvertTable[i].proc2; break; end; end; try ConvertToIntermediateFormat(ASrc, tempBuf1, AColorFormat, ASrcWidth, ASrcHeight); except FreeMem(tempBuf1); raise; end; // Rescale if ASrcWidth = 1 then xscale := ADstWidth / ASrcWidth else xscale := (ADstWidth - 1) / (ASrcWidth - 1); if ASrcHeight = 1 then yscale := ADstHeight / ASrcHeight else yscale := (ADstHeight - 1) / (ASrcHeight - 1); // Pre-calculate filter contributions for a row GetMem(contrib, ADstWidth * SizeOf(TCList)); // Horizontal sub-sampling // Scales from bigger to smaller width if xscale < 1.0 then begin width := vImageScaleFilterWidth / xscale; fscale := 1.0 / xscale; for i := 0 to ADstWidth - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(width * 2.0 + 1) * SizeOf(TContributor)); center := i / xscale; left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := AFilter((center - j) / fscale) / fscale; if weight = 0.0 then continue; if (j < 0) then n := -j else if (j >= ASrcWidth) then n := ASrcWidth - j + ASrcWidth - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end else // Horizontal super-sampling // Scales from smaller to bigger width begin for i := 0 to ADstWidth - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(vImageScaleFilterWidth * 2.0 + 1) * SizeOf(TContributor)); center := i / xscale; left := floor(center - vImageScaleFilterWidth); right := ceil(center + vImageScaleFilterWidth); for j := left to right do begin weight := AFilter(center - j); if weight = 0.0 then continue; if (j < 0) then n := -j else if (j >= ASrcWidth) then n := ASrcWidth - j + ASrcWidth - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end; size := ADstWidth * ASrcHeight * SizeOf(TIntermediateFormat); GetMem(tempBuf2, size); // Apply filter to sample horizontally from Src to Work for k := 0 to ASrcHeight - 1 do begin SourceLine := @tempBuf1[k * ASrcWidth]; DestLine := @tempBuf2[k * ADstWidth]; for i := 0 to ADstWidth - 1 do begin color1 := cSuperBlack; for j := 0 to contrib^[i].n - 1 do begin weight := contrib^[i].p^[j].weight; if weight = 0.0 then continue; color2 := SourceLine[contrib^[i].p^[j].pixel]; color1.R := color1.R + color2.R * weight; color1.G := color1.G + color2.G * weight; color1.B := color1.B + color2.B * weight; color1.A := color1.A + color2.A * weight; end; // Set new pixel value DestLine[i] := color1; end; end; // Free the memory allocated for horizontal filter weights for i := 0 to ADstWidth - 1 do FreeMem(contrib^[i].p); FreeMem(contrib); // Pre-calculate filter contributions for a column GetMem(contrib, ADstHeight * SizeOf(TCList)); // Vertical sub-sampling // Scales from bigger to smaller height if yscale < 1.0 then begin width := vImageScaleFilterWidth / yscale; fscale := 1.0 / yscale; for i := 0 to ADstHeight - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(width * 2.0 + 1) * SizeOf(TContributor)); center := i / yscale; left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := AFilter((center - j) / fscale) / fscale; if weight = 0.0 then continue; if (j < 0) then n := -j else if (j >= ASrcHeight) then n := MaxInteger(ASrcHeight - j + ASrcHeight - 1, 0) else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end end else // Vertical super-sampling // Scales from smaller to bigger height begin for i := 0 to ADstHeight - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(vImageScaleFilterWidth * 2.0 + 1) * SizeOf(TContributor)); center := i / yscale; left := floor(center - vImageScaleFilterWidth); right := ceil(center + vImageScaleFilterWidth); for j := left to right do begin weight := AFilter(center - j); if weight = 0.0 then continue; if j < 0 then n := -j else if (j >= ASrcHeight) then n := MaxInteger(ASrcHeight - j + ASrcHeight - 1, 0) else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; end; size := ADstWidth * ADstHeight * SizeOf(TIntermediateFormat); ReallocMem(tempBuf1, size); // Apply filter to sample vertically from Work to Dst for k := 0 to ADstWidth - 1 do begin for i := 0 to ADstHeight - 1 do begin color1 := cSuperBlack; for j := 0 to contrib^[i].n - 1 do begin weight := contrib^[i].p^[j].weight; if weight = 0.0 then continue; color2 := tempBuf2[k + contrib^[i].p^[j].pixel * ADstWidth]; color1.R := color1.R + color2.R * weight; color1.G := color1.G + color2.G * weight; color1.B := color1.B + color2.B * weight; color1.A := color1.A + color2.A * weight; end; tempBuf1[k + i * ADstWidth] := color1; end; end; // Free the memory allocated for vertical filter weights for i := 0 to ADstHeight - 1 do FreeMem(contrib^[i].p); FreeMem(contrib); FreeMem(tempBuf2); // Back to native image format try ConvertFromIntermediateFormat(tempBuf1, ADst, AColorFormat, ADstWidth, ADstHeight); except FreeMem(tempBuf1); raise; end; FreeMem(tempBuf1); end; procedure Div2(var Value: Integer); {$IFDEF GLS_INLINE} inline; {$ENDIF} begin Value := Value div 2; if Value = 0 then Value := 1; end; procedure Build2DMipmap( const ASrc: Pointer; const ADst: TPointerArray; AColorFormat: TGLEnum; ADataType: TGLEnum; AFilter: TImageFilterFunction; ASrcWidth, ASrcHeight: Integer); var ConvertToIntermediateFormat: TConvertToImfProc; ConvertFromIntermediateFormat: TConvertFromInfProc; ADstWidth, ADstHeight: Integer; i, j, k, n, size, level: Integer; tempBuf1, tempBuf2, storePtr, SourceLine, DestLine: PIntermediateFormatArray; contrib: PCListList; xscale, yscale: Single; width, fscale, weight: Single; center: Single; left, right: Integer; color1, color2: TIntermediateFormat; tempW, tempH: Integer; begin if ASrcWidth < 1 then Exit; ASrcHeight := MaxInteger(1, ASrcHeight); // Allocate memory tempW := ASrcWidth; tempH := ASrcHeight; size := 0; for level := 0 to High(ADst) + 1 do begin Inc(size, tempW * tempH * SizeOf(TIntermediateFormat)); Div2(tempW); Div2(tempH); end; GetMem(tempBuf1, size); storePtr := tempBuf1; FillChar(tempBuf1^, size, $00); GetMem(tempBuf2, ASrcWidth * ASrcHeight * SizeOf(TIntermediateFormat)); // Find function to convert external format to intermediate format ConvertToIntermediateFormat := UnsupportedToImf; ConvertFromIntermediateFormat := UnsupportedFromImf; for i := 0 to high(cConvertTable) do begin if ADataType = cConvertTable[i].type_ then begin ConvertToIntermediateFormat := cConvertTable[i].proc1; ConvertFromIntermediateFormat := cConvertTable[i].proc2; break; end; end; try ConvertToIntermediateFormat(ASrc, tempBuf1, AColorFormat, ASrcWidth, ASrcHeight); except FreeMem(tempBuf1); raise; end; contrib := nil; tempW := ASrcWidth; tempH := ADstHeight; try // Downsampling for level := 0 to High(ADst) do begin ADstWidth := ASrcWidth; ADstHeight := ASrcHeight; Div2(ADstWidth); Div2(ADstHeight); xscale := MaxFloat((ADstWidth - 1) / (ASrcWidth - 1), 0.25); yscale := MaxFloat((ADstHeight - 1) / (ASrcHeight - 1), 0.25); // Pre-calculate filter contributions for a row ReallocMem(contrib, ADstWidth * SizeOf(TCList)); // Horizontal sub-sampling // Scales from bigger to smaller width width := vImageScaleFilterWidth / xscale; fscale := 1.0 / xscale; for i := 0 to ADstWidth - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(width * 2.0 + 1.0) * SizeOf(TContributor)); center := i / xscale; left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := AFilter((center - j) / fscale) / fscale; if weight = 0.0 then continue; if (j < 0) then n := -j else if (j >= ASrcWidth) then n := MaxInteger(ASrcWidth - j + ASrcWidth - 1, 0) else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; // Apply filter to sample horizontally from Src to Work for k := 0 to ASrcHeight - 1 do begin SourceLine := @tempBuf1[k * ASrcWidth]; DestLine := @tempBuf2[k * ADstWidth]; for i := 0 to ADstWidth - 1 do begin color1 := cSuperBlack; for j := 0 to contrib^[i].n - 1 do begin weight := contrib^[i].p^[j].weight; if weight = 0.0 then continue; color2 := SourceLine[contrib^[i].p^[j].pixel]; color1.R := color1.R + color2.R * weight; color1.G := color1.G + color2.G * weight; color1.B := color1.B + color2.B * weight; color1.A := color1.A + color2.A * weight; end; // Set new pixel value DestLine[i] := color1; end; end; // Free the memory allocated for horizontal filter weights for i := 0 to ADstWidth - 1 do FreeMem(contrib^[i].p); // Pre-calculate filter contributions for a column ReallocMem(contrib, ADstHeight * SizeOf(TCList)); // Vertical sub-sampling // Scales from bigger to smaller height width := vImageScaleFilterWidth / yscale; fscale := 1.0 / yscale; for i := 0 to ADstHeight - 1 do begin contrib^[i].n := 0; GetMem(contrib^[i].p, Trunc(width * 2.0 + 1) * SizeOf(TContributor)); center := i / yscale; left := floor(center - width); right := ceil(center + width); for j := left to right do begin weight := AFilter((center - j) / fscale) / fscale; if weight = 0.0 then continue; if (j < 0) then n := -j else if (j >= ASrcHeight) then n := MaxInteger(ASrcHeight - j + ASrcHeight - 1, 0) else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; size := ASrcWidth * ASrcHeight * SizeOf(TIntermediateFormat); Inc(PByte(tempBuf1), size); // Apply filter to sample vertically from Work to Dst for k := 0 to ADstWidth - 1 do begin for i := 0 to ADstHeight - 1 do begin color1 := cSuperBlack; for j := 0 to contrib^[i].n - 1 do begin weight := contrib^[i].p^[j].weight; if weight = 0.0 then continue; n := k + contrib^[i].p^[j].pixel * ADstWidth; color2 := tempBuf2[n]; color1.R := color1.R + color2.R * weight; color1.G := color1.G + color2.G * weight; color1.B := color1.B + color2.B * weight; color1.A := color1.A + color2.A * weight; end; tempBuf1[k + i * ADstWidth] := color1; end; end; // Free the memory allocated for vertical filter weights for i := 0 to ADstHeight - 1 do FreeMem(contrib^[i].p); ASrcWidth := ADstWidth; ASrcHeight := ADstHeight; // Back to native image format ConvertFromIntermediateFormat( tempBuf1, ADst[level], AColorFormat, ASrcWidth, ASrcHeight); end; finally if Assigned(contrib) then FreeMem(contrib); FreeMem(tempBuf2); FreeMem(storePtr); end; end; procedure AlphaGammaBrightCorrection( const ASrc: Pointer; AColorFormat: TGLEnum; ADataType: TGLEnum; ASrcWidth, ASrcHeight: Integer; anAlphaProc: TImageAlphaProc; ABrightness: Single; AGamma: Single); var ConvertToIntermediateFormat: TConvertToImfProc; ConvertFromIntermediateFormat: TConvertFromInfProc; tempBuf1: PIntermediateFormatArray; Size, I: Integer; begin if ASrcWidth < 1 then Exit; ASrcHeight := MaxInteger(1, ASrcHeight); Size := ASrcWidth * ASrcHeight; GetMem(tempBuf1, Size * SizeOf(TIntermediateFormat)); // Find function to convert external format to intermediate format ConvertToIntermediateFormat := UnsupportedToImf; ConvertFromIntermediateFormat := UnsupportedFromImf; for i := 0 to high(cConvertTable) do begin if ADataType = cConvertTable[i].type_ then begin ConvertToIntermediateFormat := cConvertTable[i].proc1; ConvertFromIntermediateFormat := cConvertTable[i].proc2; break; end; end; try ConvertToIntermediateFormat( ASrc, tempBuf1, AColorFormat, ASrcWidth, ASrcHeight); vTopLeftColor := tempBuf1[0]; vBottomRightColor := tempBuf1[Size-1]; if Assigned(anAlphaProc) then for I := Size - 1 downto 0 do anAlphaProc(tempBuf1[I]); if ABrightness <> 1.0 then for I := Size - 1 downto 0 do with tempBuf1[I] do begin R := R * ABrightness; G := G * ABrightness; B := B * ABrightness; end; if AGamma <> 1.0 then for I := Size - 1 downto 0 do with tempBuf1[I] do begin R := Power(R, AGamma); G := Power(G, AGamma); B := Power(B, AGamma); end; // Back to native image format ConvertFromIntermediateFormat( tempBuf1, ASrc, AColorFormat, ASrcWidth, ASrcHeight); except FreeMem(tempBuf1); raise; end; FreeMem(tempBuf1); end; end.
unit Test.Devices.Logica.SPT961.Parser; interface uses TestFrameWork, Devices.Logica.SPT961, GMGlobals, Classes, Test.Devices.Base.ReqParser; type TSPT961ReqParserTest = class(TDeviceReqParserTestBase) private reqParser: TSPT961AnswerParser; ResDevNumber: int; ResType: TSPT961AnswerType; ResChn: int; ResPrm: int; ResValue: double; ReqDetails: TRequestDetails; ExtData: string; procedure CheckValue(buf: ArrayOfByte); protected procedure SetUp; override; procedure TearDown; override; function TimeArrayDayTestData: ArrayOfByte; function TimeArrayHourTestData: ArrayOfByte; function GetDevType(): int; override; function GetThreadClass(): TSQLWriteThreadForTestClass; override; published //procedure testArchStructure; procedure TimeArrayDay; procedure TimeArrayHour(); procedure EmptyTimeArray; procedure Value; procedure Thread_Day_FindChn; procedure Thread_Hour_FindChn; end; implementation uses DateUtils, SysUtils, GMConst, Math, GMSqlQuery; type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest); { TLogicaTest } procedure TSPT961ReqParserTest.SetUp; begin inherited; reqParser := TSPT961AnswerParser.Create(); end; procedure TSPT961ReqParserTest.TearDown; begin inherited; reqParser.Free(); end; function TSPT961ReqParserTest.TimeArrayDayTestData(): ArrayOfByte; begin Result := TextNumbersStringToArray( ' FF FF 10 01 00 00 10 1F 16 10 02 09 30 09 37 32 0C' + ' 09 31 34 09 31 30 09 32 30 31 33 09 30 09 30 09 30 0C' + ' 09 39 09 31 30 09 32 30 31 33 09 30 09 30 09 30 0C' + ' 09 30 09 27 43 09 31 34 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 09 30 09 27 43 09 31 33 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 09 30 09 27 43 09 31 32 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 09 30 09 27 43 09 31 31 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 09 30 09 27 43 09 31 30 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 09 30 09 27 43 09 20 39 2D 31 30 2D 31 33 2F 20 30 3A 30 30 3A 30 30 0C' + ' 10 03 A9 92'); end; procedure TSPT961ReqParserTest.TimeArrayDay(); var buf: ArrayOfByte; i: int; dt: Longword; begin buf := TimeArrayDayTestData(); Check(LogicaSPT961_CheckCRC(buf, Length(buf)), 'CRC TimeArray'); Check(reqParser.Parse(buf, Length(buf)), 'Parse TimeArray'); Check(reqParser.ResDevNumber = 0, 'Parse TimeArray - DevNumber <> 0: ' + IntToStr(reqParser.ResDevNumber)); Check(reqParser.ResType = logicaAnswerTimeArray, 'Parse TimeArray - Type mismatch'); Check(reqParser.ResChn = 0, 'Parse TimeArray - Chn <> 0: ' + IntToStr(reqParser.ResChn) ); Check(reqParser.ResPrm = 72, 'Parse TimeArray - Prm <> 72: ' + IntToStr(reqParser.ResPrm) ); Check(reqParser.Archive.Count = 6, 'Parse ParseValue - data count <> 6: ' + IntToStr(reqParser.Archive.Count)); for i := 0 to reqParser.Archive.Count - 1 do begin Check(reqParser.Archive[i].Val.Val = 0, 'Parse ParseValue[' + IntToStr(i) + '] <> 0: ' + MyFloatToStr(reqParser.Archive[i].Val.Val)); dt := LocalToUTC(EncodeDate(2013, 10, 14 - i)); Check(reqParser.Archive[i].Val.UTime = dt, 'Parse ParseValue[' + IntToStr(i) + '].Utime'); end; end; function TSPT961ReqParserTest.TimeArrayHourTestData(): ArrayOfByte; begin Result := TextNumbersStringToArray( 'FF FF 10 01 0B 0B 10 1F 16 10 02 09 30 09 38 32 0C 09 31 34 09 32 09 32 30 31 34 09 31 37 09 39 09 31 37 0C 09 31 34 09 32 09 32 30 31 34 09 30 09 30 09 30 0C 09 32 30 09 27 43 09 31 ' + '34 2D 30 32 2D 31 34 2F 31 37 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 31 35 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 31 34 3A ' + '30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 31 33 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 31 32 3A 30 30 3A 30 30 0C 09 32 30 09 27 ' + '43 09 31 34 2D 30 32 2D 31 34 2F 31 31 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 31 30 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F ' + '20 39 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 38 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 37 3A 30 30 3A 30 30 0C 09 32 ' + '30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 36 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 35 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D ' + '31 34 2F 20 34 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 33 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 32 3A 30 30 3A 30 30 ' + '0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 31 3A 30 30 3A 30 30 0C 09 32 30 09 27 43 09 31 34 2D 30 32 2D 31 34 2F 20 30 3A 30 30 3A 30 30 0C 10 03 75 6D'); end; procedure TSPT961ReqParserTest.TimeArrayHour(); var buf: ArrayOfByte; i: int; dt: Longword; begin buf := TimeArrayHourTestData(); Check(LogicaSPT961_CheckCRC(buf, Length(buf)), 'CRC TimeArray'); Check(reqParser.Parse(buf, Length(buf)), 'Parse TimeArray'); Check(reqParser.ResDevNumber = 11, 'Parse TimeArray - DevNumber <> 11: ' + IntToStr(reqParser.ResDevNumber)); Check(reqParser.ResType = logicaAnswerTimeArray, 'Parse TimeArray - Type mismatch'); Check(reqParser.ResChn = 0, 'Parse TimeArray - Chn <> 0: ' + IntToStr(reqParser.ResChn) ); Check(reqParser.ResPrm = 82, 'Parse TimeArray - Prm <> 82: ' + IntToStr(reqParser.ResPrm) ); Check(reqParser.Archive.Count = 17, 'Parse ParseValue - data count <> 17: ' + IntToStr(reqParser.Archive.Count)); for i := 0 to reqParser.Archive.Count - 1 do begin Check(reqParser.Archive[i].Val.Val = 20, 'Parse ParseValue[' + IntToStr(i) + '] <> 20: ' + MyFloatToStr(reqParser.Archive[i].Val.Val)); // у нас дырка на 16:00, поэтому IfThen(i > 0, 1, 0) dt := LocalToUTC(EncodeDateTime(2014, 02, 14, 17 - i - IfThen(i > 0, 1, 0), 0, 0, 0)); Check(reqParser.Archive[i].Val.UTime = dt, 'Parse ParseValue[' + IntToStr(i) + '].Utime'); end; end; procedure TSPT961ReqParserTest.EmptyTimeArray(); var buf: ArrayOfByte; begin buf := TextNumbersStringToArray( ' FF FF 10 01 00 00 10 1F 16 10 02 09 30 09 37 32 0C 09 32 31 09 30 39 09 32' + ' 30 31 33 09 30 09 30 09 30 0C 09 31 09 30 39 09 32 30 31 33 09 30 09 30 09 30 0C 10 03 E4 EC'); Check(LogicaSPT961_CheckCRC(buf, Length(buf)), 'CRC EmptyTimeArray'); Check(reqParser.Parse(buf, Length(buf)), 'Parse EmptyTimeArray'); Check(reqParser.ResDevNumber = 0, 'Parse EmptyTimeArray - DevNumber <> 0: ' + IntToStr(reqParser.ResDevNumber)); Check(reqParser.ResType = logicaAnswerTimeArray, 'Parse EmptyTimeArray - Type mismatch'); Check(reqParser.ResChn = 0, 'Parse EmptyTimeArray - Chn <> 0: ' + IntToStr(reqParser.ResChn) ); Check(reqParser.ResPrm = 72, 'Parse EmptyTimeArray - Prm <> 72: ' + IntToStr(reqParser.ResPrm) ); Check(reqParser.Archive.Count = 0, 'Parse EmptyTimeArray - data count <> 0: ' + IntToStr(reqParser.Archive.Count)); end; function TSPT961ReqParserTest.GetDevType: int; begin Result := DEVTYPE_SPT_961; end; function TSPT961ReqParserTest.GetThreadClass: TSQLWriteThreadForTestClass; begin Result := TLocalSQLWriteThreadForTest; end; procedure TSPT961ReqParserTest.CheckValue(buf: ArrayOfByte); var r: TRequestDetails; begin Check(LogicaSPT961_CheckCRC(buf, Length(buf)), 'CRC Value'); Check(reqParser.Parse(buf, Length(buf)), 'ParseValue'); Check(reqParser.ResDevNumber = ResDevNumber, 'Parse ParseValue - DevNumber <> 0: ' + IntToStr(reqParser.ResDevNumber)); Check(reqParser.ResType = ResType, 'Parse ParseValue - Type mismatch'); Check(reqParser.ResChn = ResChn, 'Parse ParseValue - Chn <> 0: ' + IntToStr(reqParser.ResChn) ); Check(reqParser.ResPrm = ResPrm, 'Parse ParseValue - Prm <> 63: ' + IntToStr(reqParser.ResPrm) ); Check(reqParser.Value = ResValue, 'Parse ParseValue - Value <> 20: ' + FloatToStr(reqParser.Value) ); Check(reqParser.Archive.Count = 0, 'Parse ParseValue - Arch not empty'); r := ReqDetails; Check(reqParser.CheckInitialRequest(r, ExtData)); Check(not reqParser.CheckInitialRequest(r, '')); r := ReqDetails; r.DevNumber := 80; Check(not reqParser.CheckInitialRequest(r, '')); r := ReqDetails; r.rqtp := rqtSPT961_DAY; Check(not reqParser.CheckInitialRequest(r, '')); end; procedure TSPT961ReqParserTest.Value; var buf: ArrayOfByte; begin ResDevNumber := 0; ResType := logicaAnswerValue; ResChn := 0; ResPrm := 63; ResValue := 20; ReqDetails.DevNumber := ResDevNumber; ReqDetails.rqtp := rqtSPT961; ExtData := '0 63 83 82'; // ответ без "соплей", но с номером ведущего устройства $80 buf := TextNumbersStringToArray('10 01 80 00 10 1F 03 10 02 09 30 09 30 36 33 0C 09 32 30 09 27 43 0C 10 03 D7 E8'); CheckValue(buf); // ответ с соплями и номером 0 buf := TextNumbersStringToArray('FF FF 10 01 00 00 10 1F 03 10 02 09 30 09 30 36 33 0C 09 32 30 09 27 43 0C 10 03 44 79'); CheckValue(buf); // ответ с соплями и номером 11 ResDevNumber := 11; ReqDetails.DevNumber := ResDevNumber; buf := TextNumbersStringToArray('FF FF 10 01 00 0B 10 1F 03 10 02 09 30 09 30 36 33 0C 09 32 30 09 27 43 0C 10 03 AC B2'); CheckValue(buf); // (||Б|||||||2|155||2.874|кгс/cм2|||uЮ) buf := TextNumbersStringToArray('10 01 81 01 10 1F 03 10 02 09 32 09 31 35 35 0C 09 32 2E 38 37 34 09 AA A3 E1 2F 63 AC 32 0C 10 03 75 9E'); ResDevNumber := 1; ResType := logicaAnswerValue; ResChn := 2; ResPrm := 155; ResValue := 2.874; ReqDetails.DevNumber := ResDevNumber; ReqDetails.rqtp := rqtSPT961; ExtData := '2 155 206 205'; CheckValue(buf); end; procedure TSPT961ReqParserTest.Thread_Day_FindChn; var arr: ArrayOfString; begin gbv.SetBufRec(TimeArrayDayTestData()); gbv.ReqDetails.ID_Obj := 2; gbv.ReqDetails.ID_Prm := -1; TLocalSQLWriteThreadForTest(thread).ParseReqDetails_SPT(gbv); check((gbv.ReqDetails.ID_Prm > 1000) and (gbv.ReqDetails.ID_Prm <= 1015), 'ID_Prm'); // в нужный номер не попадем все равно, попадем хотя бы в нужный прибор check(gbv.ReqDetails.rqtp = rqtSPT961_DAY, 'rqtp'); arr := QueryResultArray_FirstRow('select ID_Device, ID_Src, N_Src from Params where ID_Prm = ' + IntToStr(gbv.ReqDetails.ID_Prm)); check(arr[0] = '3', 'ID_Device'); check(arr[1] = '1', 'ID_Src'); check(arr[2] = '2', 'N_Src'); end; procedure TSPT961ReqParserTest.Thread_Hour_FindChn; var arr: ArrayOfString; begin gbv.SetBufRec(TimeArrayHourTestData()); gbv.ReqDetails.ID_Obj := 2; gbv.ReqDetails.ID_Prm := -1; TLocalSQLWriteThreadForTest(thread).ParseReqDetails_SPT(gbv); check((gbv.ReqDetails.ID_Prm > 1015) and (gbv.ReqDetails.ID_Prm <= 1030), 'ID_Prm'); check(gbv.ReqDetails.rqtp = rqtSPT961_HOUR, 'rqtp'); arr := QueryResultArray_FirstRow('select ID_Device, ID_Src, N_Src from Params where ID_Prm = ' + IntToStr(gbv.ReqDetails.ID_Prm)); check(arr[0] = '4', 'ID_Device'); check(arr[1] = '1', 'ID_Src'); check(arr[2] = '1', 'N_Src'); end; initialization RegisterTest('GMIOPSrv/Devices/Logica', TSPT961ReqParserTest.Suite); end.
unit MIRTMainFrm; ///////////////////////////////// // // // Description: MIRT main form // // // ///////////////////////////////// interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, ExtCtrls, ComCtrls, ActnList, ImageResizerUnit; type TfrmMIRTMain = class(TForm) actAddDirectory: TAction; actAddFiles: TAction; actClear: TAction; actCompressionSettings: TAction; actRemoveFiles: TAction; actResize: TAction; actSelectDestination: TAction; actStop: TAction; alActions: TActionList; btnAddDirectory: TButton; btnAddFiles: TButton; btnCompressionSettings: TButton; btnOutputDirectory: TButton; btnRemoveAll: TButton; btnRemoveFiles: TButton; btnResize: TButton; btnStop: TButton; bvlScale: TBevel; cboFiletype: TComboBox; chkOverwrite: TCheckBox; chkRecursive: TCheckBox; dlgOutputSave: TSaveDialog; dlgSourceOpen: TOpenDialog; edOutputDirectory: TEdit; edPrefix: TEdit; edSuffix: TEdit; gbCompression: TGroupBox; gbFileInfo: TGroupBox; gbSizing: TGroupBox; lblDimensions: TLabel; lblDirectory: TLabel; lblFilename: TLabel; lblHeight: TLabel; lblOutputFile: TLabel; lblPrefix: TLabel; lblProgress: TLabel; lblScale: TLabel; lblSourceFile: TLabel; lblSuffix: TLabel; lblWidth: TLabel; lbSource: TListBox; pnlMain: TPanel; pnlProgress: TPanel; prgProgress: TProgressBar; rbConvert: TRadioButton; rbDimensions: TRadioButton; rbEnforceCompression: TRadioButton; rbImageCompression: TRadioButton; rbPreserve: TRadioButton; rbScale: TRadioButton; spnHeight: TSpinEdit; spnScale: TSpinEdit; spnWidth: TSpinEdit; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure actAddFilesExecute(Sender: TObject); procedure actAddDirectoryExecute(Sender: TObject); procedure actRemoveFilesExecute(Sender: TObject); procedure actClearExecute(Sender: TObject); procedure actSelectDestinationExecute(Sender: TObject); procedure actStopExecute(Sender: TObject); procedure actResizeExecute(Sender: TObject); procedure actCompressionSettingsExecute(Sender: TObject); procedure edPrefixChange(Sender: TObject); procedure AcceptFiles(var Msg: TMessage); message WM_DROPFILES; private { Private declarations } FImageResizer: TImageResizer; FJPEGCompression: integer; procedure SetupNotifications; procedure ResetAll; procedure ResetActions; procedure ResetSource; procedure ResetFileInfo; procedure ResetSizing; procedure ResetProgress; procedure ResetCompression; procedure SetLocks(bValue: Boolean); procedure AddMultipleFiles; procedure AddDirectoryBtn; procedure AddDirectory(const sDir: String); procedure DisplayFileName; procedure DisplayDimensions; procedure RemoveFiles; procedure RemoveAllFiles; procedure PrepareProgress; procedure SetDestinationDirectory; procedure SetCompressionSettings; procedure UpdateProgressLoad; procedure UpdateProgressDestination; procedure UpdateProgressSave; procedure StopProcessing; procedure AlertUser; procedure ResizeAll; ///////////////////////// // Notification events // ///////////////////////// procedure OnScaleCalculated(Sender: TObject); procedure OnWidthCalculated(Sender: TObject); procedure OnHeightCalculated(Sender: TObject); procedure OnResizingStarted(Sender: TObject); procedure OnResizingEnded(Sender: TObject); procedure OnDestinationSet(Sender: TObject); procedure OnLoadingFile(Sender: TObject); procedure OnSavingFile(Sender: TObject); public { Public declarations } end; var frmMIRTMain: TfrmMIRTMain; implementation uses ShellAPI, FileCtrl, ResizerCommonTypesUnit, ImageCommonTypesUnit, MIRTErrorLogFrm, ImageFilesUnit, MIRTCompressionSettingsFrm; {$R *.DFM} { TfrmResizerMain } ///////////////////////// // Form Create/Destroy // ///////////////////////// procedure TfrmMIRTMain.FormCreate(Sender: TObject); begin FImageResizer := TImageResizer.Create; //////////////////////////////////////////////////////////////////////// // Check the command line parameters to see if we need the GUI or not // //////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// // We need the GUI, so let's start fresh // /////////////////////////////////////////// ResetAll; SetupNotifications; ////////////////////////////////////////////////////// // Tell Windows we're accepting drag and drop files // ////////////////////////////////////////////////////// DragAcceptFiles(Handle, True); //////////////////////////////////////////////////////////////////////////// // If there were preset values in the command line paramters, accept them // //////////////////////////////////////////////////////////////////////////// ////////////////////////////////////// // NO GUI - Just get some work done // ////////////////////////////////////// end; procedure TfrmMIRTMain.FormDestroy(Sender: TObject); begin if FImageResizer.ContinueProcess then begin // TODO: Come up with something better here // StopProcessing; lblProgress.Font.Color := clRed; lblProgress.Caption := 'Ending process, please wait 5 seconds...'; Sleep(5000); end; // if FImageResizer.ContinueProcess FreeAndNil(FImageResizer); end; //////////////// // Form setup // //////////////// procedure TfrmMIRTMain.SetupNotifications; begin if Assigned(FImageResizer) then begin FImageResizer.OnScaleCalculated := OnScaleCalculated; FImageResizer.OnWidthCalculated := OnWidthCalculated; FImageResizer.OnHeightCalculated := OnHeightCalculated; FImageResizer.OnResizingStarted := OnResizingStarted; FImageResizer.OnResizingEnded := OnResizingEnded; FImageResizer.OnDestinationSet := OnDestinationSet; FImageResizer.OnLoadingFile := OnLoadingFile; FImageResizer.OnSavingFile := OnSavingFile; end; // if Assigned FImageResizer end; procedure TfrmMIRTMain.ResetAll; begin ResetActions; ResetSource; ResetFileInfo; ResetSizing; ResetProgress; ResetCompression; end; procedure TfrmMIRTMain.ResetFileInfo; begin edPrefix.Text := 's_'; edSuffix.Text := ''; edOutputDirectory.Text := ''; rbConvert.Checked := True; chkOverwrite.Checked := False; cboFiletype.ItemIndex := cboFiletype.Items.IndexOf('JPEG'); DisplayFileName; end; procedure TfrmMIRTMain.ResetProgress; begin lblSourceFile.Caption := ''; lblOutputFile.Caption := ''; lblProgress.Caption := ''; lblDimensions.Caption := ''; prgProgress.Min := 0; prgProgress.Max := 100; prgProgress.Position := 0; prgProgress.Step := 1; end; procedure TfrmMIRTMain.ResetCompression; begin rbImageCompression.Checked := True; FJPEGCompression := 80; // arbitrary value, good quality end; procedure TfrmMIRTMain.ResetSizing; begin rbDimensions.Checked := True; spnWidth.Value := 800; spnHeight.Value := 600; spnScale.Value := 1; end; procedure TfrmMIRTMain.ResetSource; begin chkRecursive.Checked := True; lbSource.Clear; end; procedure TfrmMIRTMain.ResetActions; begin SetLocks(False); end; procedure TfrmMIRTMain.SetLocks(bValue: Boolean); begin ///////////////////////////////////////////////// // Sets enabled field for all objects, actions // // True - lock most everything // // False - unlock most everything // ///////////////////////////////////////////////// rbPreserve.Enabled := not bValue; rbConvert.Enabled := not bValue; rbDimensions.Enabled := not bValue; rbScale.Enabled := not bValue; edPrefix.Enabled := not bValue; edSuffix.Enabled := not bValue; edOutputDirectory.Enabled := not bValue; cboFiletype.Enabled := not bValue; chkOverwrite.Enabled := not bValue; spnWidth.Enabled := not bValue; spnHeight.Enabled := not bValue; spnScale.Enabled := not bValue; if FImageResizer.SourceMethod = zsmRecursiveDirectory then begin actAddDirectory.Enabled := False; actAddFiles.Enabled := False; chkRecursive.Enabled := False; end // if FImageResizer.SourceMethod = zsmRecursiveDirectory else begin actAddDirectory.Enabled := not bValue; actAddFiles.Enabled := not bValue; chkRecursive.Enabled := not bValue; end; // if not FImageResizer.SourceMethod = zsmRecursiveDirectory rbImageCompression.Enabled := not bValue; rbEnforceCompression.Enabled := not bValue; actClear.Enabled := not bValue; actRemoveFiles.Enabled := not bValue; actResize.Enabled := not bValue; actSelectDestination.Enabled := not bValue; actCompressionSettings.Enabled := not bValue; actStop.Enabled := bValue; end; /////////////////////////////// // Action / Event processing // /////////////////////////////// procedure TfrmMIRTMain.AddDirectoryBtn; var sDir: String; begin sDir := 'C:\'; if SelectDirectory(sDir, [], 0) then begin AddDirectory(sDir); end; // if SelectDirectory(sDir, [], 0) end; procedure TfrmMIRTMain.AddMultipleFiles; var i: integer; begin dlgSourceOpen.Options := dlgSourceOpen.Options - []; dlgSourceOpen.Options := dlgSourceOpen.Options + [ofAllowMultiSelect, ofFileMustExist]; if dlgSourceOpen.Execute then begin for i := 0 to dlgSourceOpen.Files.Count - 1 do lbSource.Items.Add(dlgSourceOpen.Files[i]); end; // if dlgSourceOpen.Execute actAddDirectory.Enabled := False; actRemoveFiles.Enabled := True; chkRecursive.Enabled := False; end; procedure TfrmMIRTMain.DisplayFileName; begin lblFilename.Caption := edPrefix.Text + 'FileName' + edSuffix.Text; end; procedure TfrmMIRTMain.DisplayDimensions; begin lblDimensions.Caption := IntToStr(FImageResizer.ConvertedWidth) + 'x' + IntToStr(FImageResizer.ConvertedHeight) + ' - 1/' + FloatToStr(FImageResizer.Scale); end; procedure TfrmMIRTMain.RemoveAllFiles; begin lbSource.Clear; actAddFiles.Enabled := True; actAddDirectory.Enabled := True; chkRecursive.Enabled := True; end; procedure TfrmMIRTMain.RemoveFiles; var i: integer; begin if (lbSource.SelCount = lbSource.Items.Count) then RemoveAllFiles else begin if lbSource.SelCount > 0 then begin for i := (lbSource.Items.Count - 1) downto 0 do if lbSource.Selected[i] then lbSource.Items.Delete(i); end; // if lbSource.SelCount > 0 end; // if not (lbSource.SelCount = lbSource.Items.Count) end; procedure TfrmMIRTMain.PrepareProgress; begin prgProgress.Max := FImageResizer.Files.Count; end; procedure TfrmMIRTMain.SetDestinationDirectory; var sDir: String; begin if SelectDirectory(sDir, [sdAllowCreate, sdPerformCreate, sdPrompt], 1000) then edOutputDirectory.Text := sDir; end; procedure TfrmMIRTMain.SetCompressionSettings; var frmCompressionSettings: TfrmCompressionSettings; begin frmCompressionSettings := TfrmCompressionSettings.Create(Self); try frmCompressionSettings.JPEGCompression := FJPEGCompression; if (frmCompressionSettings.ShowModal = mrOK) then begin FJPEGCompression := frmCompressionSettings.JPEGCompression; end; // if frmCompressionSettings.ShowModal finally frmCompressionSettings.Free; end; end; procedure TfrmMIRTMain.UpdateProgressLoad; begin lblSourceFile.Caption := ExtractFileName(FImageResizer.FileName); end; procedure TfrmMIRTMain.UpdateProgressDestination; begin lblOutputFile.Caption := ExtractFileName(FImageResizer.Destination); end; procedure TfrmMIRTMain.UpdateProgressSave; begin prgProgress.StepIt; lblProgress.Caption := IntToStr(prgProgress.Position) + ' of ' + IntToStr(FImageResizer.Files.Count); end; procedure TfrmMIRTMain.StopProcessing; begin FImageResizer.ContinueProcess := False; end; procedure TfrmMIRTMain.AlertUser; var frmErrorLog: TfrmErrorLog; begin frmErrorLog := TfrmErrorLog.Create(Self); try frmErrorLog.SetErrorLogList(FImageResizer.BadFiles); frmErrorLog.ShowModal; finally frmErrorLog.Free; end; // try..finally end; procedure TfrmMIRTMain.AddDirectory(const sDir: String); procedure AdoptFilesList(slList: TStringList); var i: integer; begin if slList.Count > 0 then for i := 0 to slList.Count - 1 do lbSource.Items.Add(slList.Strings[i]); end; // AdoptFilesList begin SetLocks(True); actClear.Execute; FImageResizer.Root := sDir; if chkRecursive.Checked then FImageResizer.SourceMethod := zsmRecursiveDirectory else FImageResizer.SourceMethod := zsmDirectory; FImageResizer.PrepareDirsList; FImageResizer.PrepareFilesList; AdoptFilesList(FimageResizer.Files); actAddFiles.Enabled := False; actAddDirectory.Enabled := False; actRemoveFiles.Enabled := False; chkRecursive.Enabled := False; SetLocks(False); end; procedure TfrmMIRTMain.ResizeAll; function SourceFilesToStringList: TStringList; var slList: TStringList; i: integer; begin if lbSource.Items.Count > 0 then begin slList := TStringList.Create; for i := 0 to lbSource.Items.Count - 1 do slList.Add(lbSource.Items[i]); Result := slList; end // if lbSource.Items.Count > 0 else Result := nil; end; // function SourceFilesToStringList begin ///////////////////////////////////////////////////////// // If we have individual files, we need to put them in // ///////////////////////////////////////////////////////// if actAddFiles.Enabled then begin FImageResizer.SourceMethod := zsmFiles; FImageResizer.Files := SourceFilesToStringList; end; // if actAddFiles.Enabled ///////////////////////////////// // Get the progress bar set up // ///////////////////////////////// ResetProgress; PrepareProgress; ///////////////////// // FileType method // ///////////////////// if rbPreserve.Checked then FImageResizer.FileTypeMethod := zftmPreserve else FImageResizer.FileTypeMethod := zftmConvert; /////////////////////// // FileHandle method // /////////////////////// if chkOverwrite.Checked then FImageResizer.FileHandling := zfhOverwrite else FImageResizer.FileHandling := zfhSkip; FImageResizer.Prefix := edPrefix.Text; FImageResizer.Suffix := edSuffix.Text; // TODO: make this better if CompareText(cboFiletype.Text, 'JPEG') = 0 then FImageResizer.ImageFileType := ziftJPG else FImageResizer.ImageFileType := ziftBMP; FImageResizer.OutputPath := edOutputDirectory.Text; //////////////////// // Scaling method // //////////////////// if rbDimensions.Checked then FImageResizer.ScalingMethod := zsmCalculate else FImageResizer.ScalingMethod := zsmFactor; FImageResizer.Width := spnWidth.Value; FImageResizer.Height := spnHeight.Value; FImageResizer.Scale := spnScale.Value; ////////////////////////// // Compression settings // ////////////////////////// FImageResizer.CompressMethod := rbEnforceCompression.Checked; FImageResizer.JPEGCompression := FJPEGCompression; FImageResizer.ContinueProcess := True; try FImageResizer.ResizeAll; except on E:EInvalidGraphic do begin SetLocks(False); AlertUser; end; // on E:EInvalidGraphic on E:Exception do begin SetLocks(False); AlertUser; Raise; end; // on E:Exception end; // try..except end; ///////////////////////////// // Action / Event handling // ///////////////////////////// procedure TfrmMIRTMain.OnHeightCalculated(Sender: TObject); begin DisplayDimensions; Application.ProcessMessages; end; procedure TfrmMIRTMain.OnWidthCalculated(Sender: TObject); begin DisplayDimensions; Application.ProcessMessages; end; procedure TfrmMIRTMain.OnScaleCalculated(Sender: TObject); begin DisplayDimensions; Application.ProcessMessages; end; procedure TfrmMIRTMain.OnResizingEnded(Sender: TObject); begin SetLocks(False); end; procedure TfrmMIRTMain.OnResizingStarted(Sender: TObject); begin SetLocks(True); end; procedure TfrmMIRTMain.OnDestinationSet(Sender: TObject); begin UpdateProgressDestination; Application.ProcessMessages; end; procedure TfrmMIRTMain.OnLoadingFile(Sender: TObject); begin UpdateProgressLoad; Application.ProcessMessages; end; procedure TfrmMIRTMain.OnSavingFile(Sender: TObject); begin UpdateProgressSave; Application.ProcessMessages; end; procedure TfrmMIRTMain.actAddFilesExecute(Sender: TObject); begin AddMultipleFiles; end; procedure TfrmMIRTMain.actAddDirectoryExecute(Sender: TObject); begin AddDirectoryBtn; end; procedure TfrmMIRTMain.actRemoveFilesExecute(Sender: TObject); begin RemoveFiles; end; procedure TfrmMIRTMain.actClearExecute(Sender: TObject); begin RemoveAllFiles; end; procedure TfrmMIRTMain.actSelectDestinationExecute(Sender: TObject); begin SetDestinationDirectory; end; procedure TfrmMIRTMain.actStopExecute(Sender: TObject); begin StopProcessing; end; procedure TfrmMIRTMain.actResizeExecute(Sender: TObject); begin ResizeAll; end; procedure TfrmMIRTMain.actCompressionSettingsExecute(Sender: TObject); begin SetCompressionSettings; end; procedure TfrmMIRTMain.edPrefixChange(Sender: TObject); begin DisplayFileName; end; procedure TfrmMIRTMain.AcceptFiles(var Msg: TMessage); const MAXFILENAMELEN = 1023; var i, iCount: integer; acFileName: array [0..MAXFILENAMELEN] of char; begin ///////////////////////////////////////////// // Find out how many files we're accepting // ///////////////////////////////////////////// iCount := DragQueryFile(msg.WParam, $FFFFFFFF, acFileName, MAXFILENAMELEN); /////////////////////////////////////////////////// // Query Windows one at a time for the file name // /////////////////////////////////////////////////// for i := 0 to (iCount - 1) do begin DragQueryFile(msg.WParam, i, acFileName, MAXFILENAMELEN); //////////////////////////////////////////////////////////////// // Check to see if what was dropped was a directory or a file // //////////////////////////////////////////////////////////////// if DirectoryExists(String(acFileName)) then /////////////// // Directory // /////////////// AddDirectory(String(acFileName)) else if IsGraphicsFile(String(acFileName)) then /////////////////////////////////////////////////// // TODO: Validate files added are graphics files // /////////////////////////////////////////////////// /////////////////////////////// // Add files to the list box // /////////////////////////////// lbSource.Items.Add(String(acFileName)); end; actAddDirectory.Enabled := False; chkRecursive.Enabled := False; ///////////////////////////////////////////// // Let Windows know that operation is done // ///////////////////////////////////////////// DragFinish(Msg.WParam); end; end.
unit caseof_2; interface implementation function GetID(const Str: string): Int32; begin case Str of 'str1': Result := 1; 'str2': Result := 2; 'str3': Result := 3; else Result := -1; end; end; var G0, G1, G2: Int32; procedure Test; begin G0 := GetID('blabla'); G1 := GetID('str2'); G2 := GetID('str3'); end; initialization Test(); finalization Assert(G0 = -1); Assert(G1 = 2); Assert(G2 = 3); end.
unit HandsetBrand; interface uses HandsetSoft; type THandsetBrand = class private FHandsetSoft: THandsetSoft; FBrand: string; public procedure SetHandsetSoft(HandsetSoft: THandsetSoft; Brand: string); procedure Run; virtual; abstract; end; THandsetBrandN = class(THandsetBrand) public procedure Run; override; end; THandsetBrandM = class(THandsetBrand) public procedure Run; override; end; THandsetBrandS = class(THandsetBrand) public procedure Run; override; end; implementation { THandsetBrand } procedure THandsetBrand.SetHandsetSoft(HandsetSoft: THandsetSoft; Brand: string); begin FHandsetSoft := HandsetSoft; FBrand := Brand; end; { THandsetBrandM } procedure THandsetBrandM.Run; begin FHandsetSoft.Run(FBrand); end; { THandsetBrandN } procedure THandsetBrandN.Run; begin FHandsetSoft.Run(FBrand); end; { THandsetBrandS } procedure THandsetBrandS.Run; begin FHandsetSoft.Run(FBrand); end; end.
unit nearunityunit; interface uses Math, Sysutils, Ap; function Log1P(x : AlglibFloat):AlglibFloat; function ExpM1(x : AlglibFloat):AlglibFloat; function CosM1(x : AlglibFloat):AlglibFloat; implementation function Log1P(x : AlglibFloat):AlglibFloat; var z : AlglibFloat; LP : AlglibFloat; LQ : AlglibFloat; begin z := 1.0+x; if AP_FP_Less(z,0.70710678118654752440) or AP_FP_Greater(z,1.41421356237309504880) then begin Result := Ln(z); Exit; end; z := x*x; LP := 4.5270000862445199635215E-5; LP := LP*x+4.9854102823193375972212E-1; LP := LP*x+6.5787325942061044846969E0; LP := LP*x+2.9911919328553073277375E1; LP := LP*x+6.0949667980987787057556E1; LP := LP*x+5.7112963590585538103336E1; LP := LP*x+2.0039553499201281259648E1; LQ := 1.0000000000000000000000E0; LQ := LQ*x+1.5062909083469192043167E1; LQ := LQ*x+8.3047565967967209469434E1; LQ := LQ*x+2.2176239823732856465394E2; LQ := LQ*x+3.0909872225312059774938E2; LQ := LQ*x+2.1642788614495947685003E2; LQ := LQ*x+6.0118660497603843919306E1; z := -0.5*z+x*(z*LP/LQ); Result := x+z; end; function ExpM1(x : AlglibFloat):AlglibFloat; var r : AlglibFloat; xx : AlglibFloat; EP : AlglibFloat; EQ : AlglibFloat; begin if AP_FP_Less(x,-0.5) or AP_FP_Greater(x,0.5) then begin Result := exp(x)-1.0; Exit; end; xx := x*x; EP := 1.2617719307481059087798E-4; EP := EP*xx+3.0299440770744196129956E-2; EP := EP*xx+9.9999999999999999991025E-1; EQ := 3.0019850513866445504159E-6; EQ := EQ*xx+2.5244834034968410419224E-3; EQ := EQ*xx+2.2726554820815502876593E-1; EQ := EQ*xx+2.0000000000000000000897E0; r := x*EP; r := r/(EQ-r); Result := r+r; end; function CosM1(x : AlglibFloat):AlglibFloat; var xx : AlglibFloat; C : AlglibFloat; begin if AP_FP_Less(x,-0.25*Pi) or AP_FP_Greater(x,0.25*Pi) then begin Result := Cos(x)-1; Exit; end; xx := x*x; C := 4.7377507964246204691685E-14; C := C*xx-1.1470284843425359765671E-11; C := C*xx+2.0876754287081521758361E-9; C := C*xx-2.7557319214999787979814E-7; C := C*xx+2.4801587301570552304991E-5; C := C*xx-1.3888888888888872993737E-3; C := C*xx+4.1666666666666666609054E-2; Result := -0.5*xx+xx*xx*C; end; end.
unit LayoutPersistent; interface type ILayout = interface ['{37C7A7D1-7F08-4D69-BDDE-E500AF42BE6A}'] function GetLayoutName : string; procedure SetLayoutName (const ALayoutName : string); function GetValue (const AValueName) : Variant; procedure SetValue (const AValueName : string; const AValue : Variant); property LayoutName : string read GetLayoutName write SetLayoutName; end; IFormLayout = interface ['{70968724-5020-4E5E-9013-8154C46A5D8C}'] function GetTop : integer; function GetLeft : integer; function GetWidth : integer; function GetHeight : integer; procedure SetTop (const AValue : integer); procedure SetLeft (const AValue : integer); procedure SetWidth (const AValue : integer); procedure SetHeight (const AValue : integer); property Top : integer read GetTop write SetTop; property Left : integer read GetLeft write SetLeft; property Width : integer read GetWidth write SetWidth; property Height : integer read GetHeight write SetHeight; end; ILayoutPersistentManager = interface ['{B910B21F-D2BC-4768-98FE-245A8C7E5200}'] procedure SaveLayout (const Layout : ILayout); procedure ReadLayout (const LayoutName : string; out Layout : ILayout); end; implementation end.
unit filtroRel.DesempenhoAluno; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, unFiltroRelModelo, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, 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; type TfrmFiltroRelDesempAluno = class(TfrmFiltroRelModelo) FDRelatorio: TFDQuery; FDRelatorioIDALUNO: TIntegerField; FDRelatorioNOME: TStringField; FDRelatorioIDALUNO_1: TIntegerField; FDRelatorioIDDISCIPLINA: TIntegerField; FDRelatorioNOTAPRIPER: TBCDField; FDRelatorioNOTASEGPER: TBCDField; FDRelatorioNOTATERPER: TBCDField; FDRelatorioNOTAQUAPER: TBCDField; FDRelatorioNOTATRABPRIPER: TBCDField; FDRelatorioNOTATRABSEGPER: TBCDField; FDRelatorioNOTATRABTERPER: TBCDField; FDRelatorioNOTATRABQUAPER: TBCDField; FDRelatorioDESCRICAO: TStringField; rgResultado: TRadioGroup; FDRelatorioMedia: TCurrencyField; procedure FDRelatorioCalcFields(DataSet: TDataSet); private { Private declarations } procedure Relatorio(aImpresso:boolean = False); override; public { Public declarations } end; var frmFiltroRelDesempAluno: TfrmFiltroRelDesempAluno; implementation {$R *.dfm} uses Dados.Firebird, UnFuncoesAuxiliares, UnMensagem, unConstantes, UnTipos, relatorio.DesempenhoAluno; { TfrmFiltroRelDesempAluno } procedure TfrmFiltroRelDesempAluno.FDRelatorioCalcFields(DataSet: TDataSet); begin inherited; FdRelatorioMedia.AsFloat := getDivisao((FDRelatorioNotaPriPer.AsFloat + FDRelatorioNotaTrabPriPer.AsFloat + FDRelatorioNotaSegPer.AsFloat + FDRelatorioNotaTrabSegPer.AsFloat + FDRelatorioNotaTerPer.AsFloat + FDRelatorioNotaTrabTerPer.AsFloat + FDRelatorioNotaQuaPer.AsFloat + FDRelatorioNotaTrabQuaPer.AsFloat), 8); end; procedure TfrmFiltroRelDesempAluno.Relatorio(aImpresso: boolean); begin inherited; FDRelatorio.Close; FDRelatorio.SQL.Clear; FDRelatorio.SQL.Add(' select a.*, ad.*, d.descricao '); FDRelatorio.SQL.Add(' from aluno a'); FDRelatorio.SQL.Add(' left outer join aluno_disciplina ad on (ad.idaluno = a.idaluno)'); FDRelatorio.SQL.Add(' left outer join disciplina d on (d.iddisciplina = ad.iddisciplina)'); FDRelatorio.SQL.Add(' where 1=1 '); FDRelatorio.SQL.Add(' order by a.nome'); FDRelatorio.Open; FDRelatorio.Filtered := False; if rgResultado.ItemIndex = 1 then begin FDRelatorio.Filter := '((NotaPriPer +'+ ' NotaTrabPriPer+'+ ' NotaSegPer+' + ' NotaTrabSegPer+' + ' NotaTerPer+' + ' NotaTrabTerPer+' + ' NotaQuaPer+' + ' NotaTrabQuaPer)/ 8) >= 7'; FDRelatorio.Filtered := True; end else if rgResultado.ItemIndex = 2 then begin FDRelatorio.Filter := '((NotaPriPer +'+ ' NotaTrabPriPer+'+ ' NotaSegPer+' + ' NotaTrabSegPer+' + ' NotaTerPer+' + ' NotaTrabTerPer+' + ' NotaQuaPer+' + ' NotaTrabQuaPer)/ 8) < 7'; FDRelatorio.Filtered := True; end; if not FDRelatorio.IsEmpty then begin Application.CreateForm(TfrmRelDesempAluno,frmRelDesempAluno); try frmRelDesempAluno.lbTitulo.Caption := 'Desempenho de Alunos'; frmRelDesempAluno.dsLocal.DataSet := FDRelatorio; frmRelDesempAluno.FTipoRel := rgResultado.ItemIndex; if aImpresso then frmRelDesempAluno.RLReport1.Print else frmRelDesempAluno.RLReport1.Preview; finally FreeAndNil(frmRelDesempAluno); end; end else TFrmMensagem.ExibirMensagem('Relatório gerado vazio!' ,tmInformacao); end; end.
{*********************************************} { TeeBI Software Library } { TBIGrid plugin for TeeGrid } { } { https://www.steema.com/product/gridvcl } { } { Copyright (c) 2016-2017 by Steema Software } { All Rights Reserved } {*********************************************} unit VCLBI.Grid.TeeGrid; interface (* This unit connects TBIGrid with TTeeGrid. To activate, simply add this unit to your "uses", or manually set the desired plugin class: TBIGrid.Engine:=TBITeeGridPlugin; TeeGrid provides automatic support for many TeeBI features like column totals, custom cell coloring, column sorting etc. *) uses System.Types, System.UITypes, System.Classes, System.SysUtils, VCL.Controls, Data.DB, BI.DataItem, BI.UI, BI.Grid.Plugin, BI.GridData, VCLTee.Grid, Tee.Grid.Totals; type TBITeeGrid=class(TTeeGrid) private IData : TBIGridData; IDataSource : TDataSource; FHeader : TTotalsHeader; FTotals: TColumnTotals; procedure BindTo(const ADataSet:TDataSet); function GetTotals:Boolean; procedure SetTotals(const Value:Boolean); public Constructor Create(AOwner:TComponent); override; end; TBITeeGridPlugin=class(TBIGridPlugin) private IGrid : TBITeeGrid; protected procedure AutoWidth; override; procedure ChangedAlternate(Sender:TObject); override; function GetCanSort: Boolean; override; function GetDataSource: TDataSource; override; function GetEditorClass:String; override; function GetReadOnly:Boolean; override; function GetSortEnabled: Boolean; override; function GetTotals:Boolean; override; procedure SetDataSource(const Value: TDataSource); override; procedure SetFilters(const Value:Boolean); override; procedure SetOnRowChanged(const AEvent:TNotifyEvent); override; procedure SetPopup(const Value:TObject); override; procedure SetReadOnly(const Value:Boolean); override; procedure SetRowNumber(const Value:Boolean); override; procedure SetSearch(const Value:Boolean); override; procedure SetSortEnabled(const Value: Boolean); override; procedure SetTotals(const Value:Boolean); override; public Constructor Create(const AOwner:TComponent); override; procedure BindTo(const ADataSet:TDataSet); override; procedure Colorize(const AItems:TDataColorizers); override; procedure Duplicates(const AData:TDataItem; const Hide:Boolean); override; function GetControl:TObject; override; function GetObject:TObject; override; end; implementation
unit ServerMain; interface uses System.SysUtils, System.Classes, Datasnap.DSServer, Datasnap.DSAuth, System.JSON; type {$METHODINFO ON} TServerMethods1 = class(TComponent) private { Private declarations } procedure FormatarJSON(const AIDCode: Integer; const AContent: string); public { Public declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; Function Contatos : tjsonarray; Function UpdateContatos : TJSONArray; Function AcceptContatos : TJSONArray; Function CancelContatos (const aid: integer) : tJsonArray; Function Contato (Aid : integer) : tjsonarray; end; Main = class (TServerMethods1); {$METHODINFO OFF} implementation uses System.StrUtils, Data.DBXPlatform, Contatos2.model.interfaces, Contatos2.model.contatos, Web.HTTPApp, Datasnap.DSHTTPWebBroker, Contatos2.entidade.contatos, REST.Json; function TServerMethods1.AcceptContatos: TJSONArray; var modulo : twebmodule; contatos : tcontatos; Contato : iModelContatos; begin modulo := GetDataSnapWebModule; if modulo.Request.Content.IsEmpty then begin Result := TJSONArray.Create('Mensagem', 'Erro!'); FormatarJSON(204, result.ToString); abort; end; Result := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Modulo.Request.Content), 0) as TJSONArray; Contatos := Tcontatos.create; try Contatos.id := Result.Items[0].GetValue<integer>('id'); Contatos.nome := Result.Items[0].GetValue<string>('nome'); contatos.telefone := Result.Items[0].GetValue<string>('fixo'); contatos.Celular := Result.Items[0].GetValue<string>('celular'); Contatos.Email := Result.Items[0].GetValue<string>('email'); Contato := tmodelcontatos.new; if contato.Editar(contatos) = true then begin Result := TJSONArray.Create('Mensagem', 'Ok'); FormatarJSON(200, result.ToString); end else begin Result := TJSONArray.Create('Mensagem', 'Erro!'); FormatarJSON(204, result.ToString); end; finally FreeAndNil(Contatos); end; end; function TServerMethods1.CancelContatos(const aid: integer): tJsonArray; var Contato : iModelContatos; begin Contato := tmodelcontatos.New; if contato.Remover(aid) = true then begin Result := TJSONArray.Create('Mensagem', 'Ok'); FormatarJSON(200, result.ToString); end else begin Result := TJSONArray.Create('Mensagem', 'Erro!'); FormatarJSON(204, result.ToString); end; end; function TServerMethods1.Contato(Aid: integer): tjsonarray; var Contatos : Tcontatos; JsonString : TJSONObject; begin Contatos := tmodelContatos.New.Contato(Aid); JsonString := TJson.ObjectToJsonObject(Contatos); if JsonString <> nil then Begin Result := TJSONArray.Create(JsonString); FormatarJSON(200, Result.ToString); End else begin Result := TJSONArray.Create(TJSONObject.Create(TJSONPair.Create('Mensagem', 'Nenhum contato encontrado.'))); FormatarJSON(203, Result.ToString); end; end; function TServerMethods1.Contatos: tjsonarray; var Contatos : imodelcontatos; begin Contatos := tmodelcontatos.new; if Contatos.JSON.Count > 0 then begin Result := Contatos.JSON; FormatarJSON(200, Result.ToString); end else begin Result := TJSONArray.Create(TJSONObject.Create(TJSONPair.Create('Mensagem', 'Nenhum contato encontrado.'))); FormatarJSON(203, Result.ToString); end; end; function TServerMethods1.EchoString(Value: string): string; begin Result := Value; end; procedure TServerMethods1.FormatarJSON(const AIDCode: Integer; const AContent: string); begin GetInvocationMetadata().ResponseCode := AIDCode; GetInvocationMetadata().ResponseContent := AContent; end; function TServerMethods1.UpdateContatos: TJSONArray; var modulo : twebmodule; contatos : tcontatos; Contato : iModelContatos; begin modulo := GetDataSnapWebModule; if modulo.Request.Content.IsEmpty then begin Result := TJSONArray.Create('Mensagem', 'Erro!'); FormatarJSON(204, result.ToString); abort; end; Result := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Modulo.Request.Content), 0) as TJSONArray; Contatos := Tcontatos.create; try Contatos.nome := Result.Items[0].GetValue<string>('nome'); contatos.telefone := Result.Items[0].GetValue<string>('fixo'); contatos.Celular := Result.Items[0].GetValue<string>('celular'); Contatos.Email := Result.Items[0].GetValue<string>('email'); Contato := tmodelcontatos.new; if contato.Novo(contatos) = true then begin Result := TJSONArray.Create('Mensagem', 'Ok'); FormatarJSON(200, result.ToString); end else begin Result := TJSONArray.Create('Mensagem', 'Erro!'); FormatarJSON(204, result.ToString); end; finally FreeAndNil(Contatos); end; end; function TServerMethods1.ReverseString(Value: string): string; begin Result := System.StrUtils.ReverseString(Value); end; end.
{ $Log: C:\PROGRAM FILES\GP-VERSION LITE\Archives\Reve64\Source\MoveGenerator.paV { { Rev 1.0 28/09/03 20:28:21 Dgrava { Initial Revision } { Rev 1.4 15-6-2003 20:38:28 DGrava Disabled forward pruning. Added Quiescens check. } { Rev 1.3 10-3-2003 21:46:24 DGrava Little enhancements. } { Rev 1.2 20-2-2003 16:38:47 DGrava Forward pruning implemented. Extending capture sequences with conditional defines } { Rev 1.1 6-2-2003 11:48:02 DGrava Introduction of QuickEval component. } { Rev 1.0 24-1-2003 21:12:23 DGrava Eerste Check in. Versie 0.27 } {} unit MoveGenerator; {NOTE Perhaps the movegenerator could be improved by taking up Board[EDGE]. } interface uses ReveTypes; type TMove = record FromSquare : Integer; ToSquare : Integer; end; TExtraMoveInfo = record Promotion : boolean; JumpIndex : Integer; JumpSize : Integer; end; TKilledPiece = record Square : Integer; Piece : Integer; end; TMoveList = record AtMove : Integer; AtJump : Integer; Moves : array [1..512] of TMove; MoveInfo : array [1..512] of TExtraMoveInfo; KilledPieces : array [1..256] of TKilledPiece; end; TJumpList = record AtIndex : Integer; FromSquare : Integer; KilledPieces : array [1..12] of TKilledPiece; end; procedure GenerateMoves( var aMoveList : TMoveList; var aBoard : TBoard; aColor : Integer ); procedure ExecuteMove( var aMoveList : TMoveList; var aBoard : TBoardStruct; aIndex : Integer ); procedure UndoMove( var aMoveList : TMoveList; var aBoard : TBoardStruct; aIndex : Integer ); function FindMove( var aMoveList : TMoveList; aStart : Integer; aEnd : Integer; aFromSquare : Integer; aToSquare : Integer ): Integer; procedure SwapMoves( var aMoveList : TMoveList; aIndex1 : Integer; aIndex2 : Integer ); function IsThreatPresent( var aBoard : TBoard; aColor : Integer ): Boolean; procedure InitializeBoard(var aBoard : TBoardStruct; aColorToMove: Integer); implementation uses SysUtils, HashTable; {for IntToStr in assert message} const EDGE = 0; BOARD_STRUCT : array[1..32, 1..4] of Integer = ( (6,5,0,0), (7,6,0,0), (8,7,0,0), (0,8,0,0), (9,0,1,0), (10,9,2,1), (11,10,3,2), (12,11,4,3), (14,13,6,5), (15,14,7,6), (16,15,8,7), (0,16,0,8), (17,0,9,0), (18,17,10,9), (19,18,11,10), (20,19,12,11), (22,21,14,13), (23,22,15,14), (24,23,16,15), (0,24,0,16), (25,0,17,0), (26,25,18,17), (27,26,19,18), (28,27,20,19), (30,29,22,21), (31,30,23,22), (32,31,24,23), (0,32,0,24), (0,0,25,0), (0,0,26,25), (0,0,27,26), (0,0,28,27) ); function IsThreatPresent( var aBoard : TBoard; aColor : Integer ): Boolean; var square : Integer; startDirection : Integer; direction : Integer; nextSquare : Integer; afterSquare : Integer; begin result := False; {Pseudocode Iterate over board Is there a piece of our color. Can it jump } if aColor = RP_BLACK then begin startDirection := 1; end else begin startDirection := 3; end; for square := 1 to 32 do begin if aBoard[square] = (RP_MAN or aColor) then begin for direction := startDirection to startDirection + 1 do begin nextSquare := BOARD_STRUCT[square, direction]; if ( (nextSquare <> EDGE) and (aBoard[nextSquare] <> RP_FREE) and (aBoard[nextSquare] and aColor = 0) ) then begin afterSquare := BOARD_STRUCT[nextSquare, direction]; if (afterSquare <> EDGE) and (aBoard[afterSquare] = RP_FREE) then begin result := True; Exit; end; end; end; end else if aBoard[square] = (RP_KING or aColor) then begin for direction := 1 to 4 do begin nextSquare := BOARD_STRUCT[square, direction]; if ( (nextSquare <> EDGE) and (aBoard[nextSquare] <> RP_FREE) and (aBoard[nextSquare] and aColor = 0) ) then begin afterSquare := BOARD_STRUCT[nextSquare, direction]; if (afterSquare <> EDGE) and (aBoard[afterSquare] = RP_FREE) then begin result := True; Exit; end; end; end; end; end; // for end; // IsThreatPresent function GenerateManJump( var aMoveList : TMoveList; var aBoard : TBoard; var aJumpList : TJumpList; aSquare : Integer; aColor : Integer ) : boolean; var direction : Integer; startDirection : Integer; nextSquare : Integer; afterSquare : Integer; i : Integer; begin result := True; {Determine startDirection (based on color to move)} if aBoard[aSquare] = (RP_WHITE or RP_MAN) then begin startDirection := 3; end else begin startDirection := 1; end; for direction := startDirection to startDirection + 1 do begin nextSquare := BOARD_STRUCT[aSquare, direction]; {NOTE Check if next square is on the board, if there is a piece on it, if this piece is of a different color and is not already killed. } if ( (nextSquare <> EDGE) and (aBoard[nextSquare] <> RP_FREE) and (aBoard[nextSquare] and aColor = 0) and (aBoard[nextSquare] and RP_KILLED = 0) ) then begin afterSquare := BOARD_STRUCT[nextSquare, direction]; if (afterSquare <> EDGE) and (aBoard[afterSquare] = RP_FREE) then begin { store the information on the jumped piece and its square to the buffer.} with aJumpList do begin KilledPieces[AtIndex].Square := nextSquare; KilledPieces[AtIndex].Piece := aBoard[nextSquare]; Inc(AtIndex); end; {OK we can jump, now adjust board and search level deeper.} aBoard[afterSquare] := aBoard [aSquare]; aBoard[aSquare] := RP_FREE; aBoard[nextSquare] := aBoard[nextSquare] or RP_KILLED; if GenerateManJump(aMoveList, aBoard, aJumpList, afterSquare, aColor) then begin // We have found a capture sequence! // Copy move from buffer to movelist with aJumpList do begin aMoveList.Moves[aMoveList.AtMove].FromSquare := FromSquare; aMoveList.Moves[aMoveList.AtMove].ToSquare := afterSquare; if aBoard[afterSquare] = (RP_MAN or RP_BLACK) then begin aMoveList.MoveInfo[aMoveList.AtMove].Promotion := afterSquare in [29..32]; end else if aBoard[afterSquare] = (RP_MAN or RP_WHITE) then begin aMoveList.MoveInfo[aMoveList.AtMove].Promotion := afterSquare in [1..4]; end; aMoveList.MoveInfo[aMoveList.AtMove].JumpIndex := aMoveList.AtJump; aMoveList.MoveInfo[aMoveList.AtMove].JumpSize := AtIndex - 1; for i := Low(KilledPieces) to AtIndex - 1 do begin aMoveList.KilledPieces[aMoveList.AtJump].Square := KilledPieces[i].Square; aMoveList.KilledPieces[aMoveList.AtJump].Piece := KilledPieces[i].Piece; Inc(aMoveList.AtJump); end; // while // Point to the next free location Inc(aMoveList.AtMove); end; // with end; // if {NOTE This is probably the most difficult part of this routine to understand. It has to do with telling the caller not to store the move found so far; it has already been stored as a move. } result := False; // Restore board now aBoard[aSquare] := aBoard[afterSquare]; aBoard[afterSquare] := RP_FREE; aBoard[nextSquare] := aBoard[nextSquare] and not RP_KILLED; // Remove the information from the buffer. Dec(aJumpList.AtIndex); end; // if end; // if end; // for end; // GenerateManJump function GenerateKingJump( var aMoveList : TMoveList; var aBoard : TBoard; var aJumpList : TJumpList; aSquare : Integer; aColor : Integer ) : boolean; var direction : Integer; nextSquare : Integer; afterSquare : Integer; i : Integer; begin result := True; for direction := 1 to 4 do begin nextSquare := BOARD_STRUCT[aSquare, direction]; {NOTE Check if next square is on the board, if there is a piece on it, if this piece is of a different color and is not already killed. } if ( (nextSquare <> EDGE) and (aBoard[nextSquare] <> RP_FREE) and (aBoard[nextSquare] and aColor = 0) and (aBoard[nextSquare] and RP_KILLED = 0) ) then begin afterSquare := BOARD_STRUCT[nextSquare, direction]; if (afterSquare <> EDGE) and (aBoard[afterSquare] = RP_FREE) then begin // store the information on the jumped piece and its square // to the buffer. with aJumpList do begin KilledPieces[AtIndex].Square := nextSquare; KilledPieces[AtIndex].Piece := aBoard[nextSquare]; Inc(AtIndex); end; // OK we can jump, now adjust board and search level deeper aBoard[afterSquare] := aBoard [aSquare]; aBoard[aSquare] := RP_FREE; aBoard[nextSquare] := aBoard[nextSquare] or RP_KILLED; if GenerateKingJump(aMoveList, aBoard, aJumpList, afterSquare, aColor) then begin // We have found a capture sequence! // Copy move from buffer to movelist with aJumpList do begin aMoveList.Moves[aMoveList.AtMove].FromSquare := aJumpList.FromSquare; aMoveList.Moves[aMoveList.AtMove].ToSquare := afterSquare; aMoveList.MoveInfo[aMoveList.AtMove].Promotion := False; aMoveList.MoveInfo[aMoveList.AtMove].JumpIndex := aMoveList.AtJump; aMoveList.MoveInfo[aMoveList.AtMove].JumpSize := AtIndex - 1; for i := Low(KilledPieces) to AtIndex - 1 do begin aMoveList.KilledPieces[aMoveList.AtJump].Square := KilledPieces[i].Square; aMoveList.KilledPieces[aMoveList.AtJump].Piece := KilledPieces[i].Piece; Inc(aMoveList.AtJump); // Inc(aMoveList.ExtraInfo[AtMove].JumpSize); end; // while // Point to the next free location Inc(aMoveList.AtMove); end; // with end; // if {NOTE This is probably the most difficult part of this routine to understand. It has to do with telling the caller not to store the move found so far; it has already been stored as a move. } result := False; // Restore board now aBoard[aSquare] := aBoard[afterSquare]; aBoard[afterSquare] := RP_FREE; aBoard[nextSquare] := aBoard[nextSquare] and not RP_KILLED; // Remove the information from the buffer. Dec(aJumpList.AtIndex); end; // if end; // if end; // for end; // GenerateKingJump procedure GenerateKingMove( var aMoveList : TMoveList; var aBoard : TBoard; aSquare : Integer ); var direction : Integer; nextSquare : Integer; begin for direction := 1 to 4 do begin nextSquare := BOARD_STRUCT[aSquare, direction]; if nextSquare <> EDGE then begin if aBoard[nextSquare] = RP_FREE then begin aMoveList.Moves[aMoveList.AtMove].FromSquare := aSquare; aMoveList.Moves[aMoveList.AtMove].ToSquare := nextSquare; aMoveList.MoveInfo[aMoveList.AtMove].Promotion := False; aMoveList.MoveInfo[aMoveList.AtMove].JumpIndex := 0; aMoveList.MoveInfo[aMoveList.AtMove].JumpSize := 0; // increment list pointer Inc(aMoveList.AtMove); end; end; end; // for end; // GenerateKingMove procedure GenerateManMove( var aMoveList : TMoveList; var aBoard : TBoard; aSquare : Integer ); var direction : Integer; startDirection : Integer; nextSquare : Integer; begin {Determine startDirection (based on color to move)} if aBoard[aSquare] = (RP_WHITE or RP_MAN) then begin startDirection := 3; end else begin startDirection := 1; end; for direction := startDirection to startDirection + 1 do begin nextSquare := BOARD_STRUCT[aSquare, direction]; if nextSquare <> EDGE then begin if aBoard[nextSquare] = RP_FREE then begin aMoveList.Moves[aMoveList.AtMove].FromSquare := aSquare; aMoveList.Moves[aMoveList.AtMove].ToSquare := nextSquare; if aBoard[aSquare] = (RP_MAN or RP_BLACK) then begin aMoveList.MoveInfo[aMoveList.AtMove].Promotion := nextSquare in [29..32]; end else if aBoard[aSquare] = (RP_MAN or RP_WHITE) then begin aMoveList.MoveInfo[aMoveList.AtMove].Promotion := nextSquare in [1..4]; end; aMoveList.MoveInfo[aMoveList.AtMove].JumpIndex := 0; aMoveList.MoveInfo[aMoveList.AtMove].JumpSize := 0; // increment list pointer Inc(aMoveList.AtMove); end; end; end; // for end; // GenerateManMove procedure GenerateMoves( var aMoveList : TMoveList; var aBoard : TBoard; aColor : Integer ); var square : Integer; jumpList : TJumpList; saveIndex : Integer; begin saveIndex := aMoveList.AtMove; //for square := 32 downto 1 do begin for square := 1 to 32 do begin if aBoard[square] = (RP_MAN or aColor) then begin jumpList.FromSquare := square; jumpList.AtIndex := 1; GenerateManJump(aMoveList, aBoard, jumpList, square, aColor); end else if aBoard[square] = (RP_KING or aColor) then begin jumpList.FromSquare := square; jumpList.AtIndex := 1; GenerateKingJump(aMoveList, aBoard, jumpList, square, aColor); end; end; // for if aMoveList.AtMove = saveIndex then begin //for square := 32 downto 1 do begin for square := 1 to 32 do begin if aBoard[square] = (RP_MAN or aColor) then begin GenerateManMove(aMoveList, aBoard, square); end else if aBoard[square] = (RP_KING or aColor) then begin GenerateKingMove(aMoveList, aBoard, square); end; end; // for end; end; // GenerateMoves procedure ExecuteMove( var aMoveList : TMoveList; var aBoard : TBoardStruct; aIndex : Integer ); var i : Integer; fromSq, toSq : Integer; begin fromSq := aMoveList.Moves[aIndex].FromSquare; toSq := aMoveList.Moves[aIndex].ToSquare; with aBoard do begin {Move piece from original to new position.} Board[toSq] := Board[fromSq]; AdjustHashKey(aBoard.HashKey, Board[fromSq], fromSq); AdjustHashKey(aBoard.HashKey, Board[fromSq], toSq); if toSq <> fromSq then begin if Board[fromSq] = RP_BLACKMAN then begin Dec(Tempo, BLACK_TEMPO[fromSq]); Inc(Tempo, BLACK_TEMPO[toSq]); end else if Board[fromSq] = RP_WHITEMAN then begin Inc(Tempo, WHITE_TEMPO[fromSq]); Dec(Tempo, WHITE_TEMPO[toSq]); end; Board[fromSq] := RP_FREE; end; {Crown piece if applicable} if aMoveList.MoveInfo[aIndex].Promotion then begin Board[toSq] := (Board[toSq] and not RP_MAN) or RP_KING; if Board[toSq] = RP_BLACKKING then begin Inc(QuickEval, KING_VALUE - MAN_VALUE); Dec(BlackMen); Inc(BlackKings); AdjustHashKey(aBoard.HashKey, RP_BLACKMAN, toSq); AdjustHashKey(aBoard.HashKey, RP_BLACKKING, toSq); end else begin Dec(QuickEval, KING_VALUE - MAN_VALUE); Dec(WhiteMen); Inc(WhiteKings); AdjustHashKey(aBoard.HashKey, RP_WHITEMAN, toSq); AdjustHashKey(aBoard.HashKey, RP_WHITEKING, toSq); end; end; {Take the jumped/killed pieces from the board} with aMoveList do begin if MoveInfo[aIndex].JumpIndex > 0 then begin for i := MoveInfo[aIndex].JumpIndex to MoveInfo[aIndex].JumpIndex + MoveInfo[aIndex].JumpSize - 1 do begin Board[KilledPieces[i].Square] := RP_FREE; case KilledPieces[i].Piece of RP_WHITEMAN : begin Inc(QuickEval, MAN_VALUE); Dec(WhiteMen); Inc(Tempo, WHITE_TEMPO[KilledPieces[i].Square]); AdjustHashKey(aBoard.HashKey, RP_WHITEMAN, KilledPieces[i].Square); end; RP_BLACKMAN : begin Dec(QuickEval, MAN_VALUE); Dec(BlackMen); Dec(Tempo, BLACK_TEMPO[KilledPieces[i].Square]); AdjustHashKey(aBoard.HashKey, RP_BLACKMAN, KilledPieces[i].Square); end; RP_WHITEKING : begin Inc(QuickEval, KING_VALUE); Dec(WhiteKings); AdjustHashKey(aBoard.HashKey, RP_WHITEKING, KilledPieces[i].Square); end; RP_BLACKKING : begin Dec(QuickEval, KING_VALUE); Dec(BlackKings); AdjustHashKey(aBoard.HashKey, RP_BLACKKING, KilledPieces[i].Square); end; end; // case end; // for end; // if end; // with aMovelist aBoard.ColorToMove := aBoard.ColorToMove xor RP_CHANGECOLOR; end; // with end; // ExecuteMove procedure UndoMove( var aMoveList : TMoveList; var aBoard : TBoardStruct; aIndex : Integer ); var i : Integer; fromSq, toSq : Integer; begin fromSq := aMoveList.Moves[aIndex].FromSquare; toSq := aMoveList.Moves[aIndex].ToSquare; with aBoard do begin {Put the piece back to its original position} Board[fromSq] := Board[toSq]; AdjustHashKey(aBoard.HashKey, Board[fromSq], fromSq); AdjustHashKey(aBoard.HashKey, Board[fromSq], toSq); if fromSq <> toSq then begin Board[toSq] := RP_FREE; end; {Undo promotions if applicable} if aMoveList.MoveInfo[aIndex].Promotion then begin Board[fromSq] := (Board[fromSq] and not RP_KING) or RP_MAN; if Board[fromSq] = RP_BLACKMAN then begin Dec(QuickEval, KING_VALUE - MAN_VALUE); Dec(BlackKings); Inc(BlackMen); AdjustHashKey(aBoard.HashKey, RP_BLACKKING, fromSq); AdjustHashKey(aBoard.HashKey, RP_BLACKMAN, fromSq); end else begin Inc(QuickEval, KING_VALUE - MAN_VALUE); Dec(WhiteKings); Inc(WhiteMen); AdjustHashKey(aBoard.HashKey, RP_WHITEKING, fromSq); AdjustHashKey(aBoard.HashKey, RP_WHITEMAN, fromSq); end; end; if Board[fromSq] = RP_BLACKMAN then begin Inc(Tempo, BLACK_TEMPO[fromSq]); Dec(Tempo, BLACK_TEMPO[toSq]); end else if Board[fromSq] = RP_WHITEMAN then begin Dec(Tempo, WHITE_TEMPO[fromSq]); Inc(Tempo, WHITE_TEMPO[toSq]); end; {Return the taken pieces to the board} with aMoveList do begin if MoveInfo[aIndex].JumpIndex > 0 then begin for i := MoveInfo[aIndex].JumpIndex to MoveInfo[aIndex].JumpIndex + MoveInfo[aIndex].JumpSize - 1 do begin Board[KilledPieces[i].Square] := KilledPieces[i].Piece; case KilledPieces[i].Piece of RP_WHITEMAN : begin Dec(QuickEval, MAN_VALUE); Inc(WhiteMen); Dec(Tempo, WHITE_TEMPO[KilledPieces[i].Square]); AdjustHashKey(aBoard.HashKey, RP_WHITEMAN, KilledPieces[i].Square); end; RP_BLACKMAN : begin Inc(QuickEval, MAN_VALUE); Inc(BlackMen); Inc(Tempo, BLACK_TEMPO[KilledPieces[i].Square]); AdjustHashKey(aBoard.HashKey, RP_BLACKMAN, KilledPieces[i].Square); end; RP_WHITEKING : begin Dec(QuickEval, KING_VALUE); Inc(WhiteKings); AdjustHashKey(aBoard.HashKey, RP_WHITEKING, KilledPieces[i].Square); end; RP_BLACKKING : begin Inc(QuickEval, KING_VALUE); Inc(BlackKings); AdjustHashKey(aBoard.HashKey, RP_BLACKKING, KilledPieces[i].Square); end; end; // case end; // for end; // if end; // with aMovelist aBoard.ColorToMove := aBoard.ColorToMove xor RP_CHANGECOLOR; end; // with end; // UndoMove function FindMove( var aMoveList : TMoveList; aStart : Integer; aEnd : Integer; aFromSquare : Integer; aToSquare : Integer ): Integer; var i : Integer; begin {If the move cannot be found then simply return the first in the range of moves. So no access violations occur in case a non existing move is looked for. This might arise when forward pruning occurs in the main variant. F.i. if a short term sacrifice appears to be the best.} result := aStart; for i := aStart to aEnd do begin if (aMoveList.Moves[i].FromSquare = aFromSquare) and (aMoveList.Moves[i].ToSquare = aToSquare) then begin result := i; Break; end; end; end; // FindMove procedure SwapMoves( var aMoveList : TMoveList; aIndex1 : Integer; aIndex2 : Integer ); var tempMove : TMove; tempInfo : TExtraMoveInfo; begin { TODO : Take a pointer to MoveInfo in TMove. Save some processor time. Then a proc CopyMove can be made too. (Not a lot as at this moment (0.27) SwapMoves is only called a very few times during a search.) } Assert( (aIndex1 >= Low(aMoveList.Moves)) and (aIndex1 <= High(aMoveList.Moves)), 'Value aIndex1 is out of bounds: ' + IntToStr(aIndex1) ); Assert( (aIndex2 >= Low(aMoveList.Moves)) and (aIndex2 <= High(aMoveList.Moves)), 'Value aIndex2 is out of bounds: ' + IntToStr(aIndex2) ); if aIndex1 <> aIndex2 then begin tempMove.FromSquare := aMoveList.Moves[aIndex1].FromSquare; tempMove.ToSquare := aMoveList.Moves[aIndex1].ToSquare; tempInfo.Promotion := aMoveList.MoveInfo[aIndex1].Promotion; tempInfo.JumpIndex := aMoveList.MoveInfo[aIndex1].JumpIndex; tempInfo.JumpSize := aMoveList.MoveInfo[aIndex1].JumpSize; {copy aIndex2 to aIndex1} aMoveList.Moves[aIndex1].FromSquare := aMoveList.Moves[aIndex2].FromSquare; aMoveList.Moves[aIndex1].ToSquare := aMoveList.Moves[aIndex2].ToSquare; aMoveList.MoveInfo[aIndex1].Promotion := aMoveList.MoveInfo[aIndex2].Promotion; aMoveList.MoveInfo[aIndex1].JumpIndex := aMoveList.MoveInfo[aIndex2].JumpIndex; aMoveList.MoveInfo[aIndex1].JumpSize := aMoveList.MoveInfo[aIndex2].JumpSize; {Copy temp to index2} aMoveList.Moves[aIndex2].FromSquare := tempMove.FromSquare; aMoveList.Moves[aIndex2].ToSquare := tempMove.ToSquare; aMoveList.MoveInfo[aIndex2].Promotion := tempInfo.Promotion; aMoveList.MoveInfo[aIndex2].JumpIndex := tempInfo.JumpIndex; aMoveList.MoveInfo[aIndex2].JumpSize := tempInfo.JumpSize; end; end; // SwapMoves procedure InitializeBoard(var aBoard : TBoardStruct; aColorToMove: Integer); var i : Integer; begin with aBoard do begin ColorToMove := aColorToMove; QuickEval := 0; BlackMen := 0; BlackKings := 0; WhiteMen := 0; WhiteKings := 0; Tempo := 0; for i := Low(TBoard) to High(TBoard) do begin case Board[i] of RP_WHITEMAN : begin Dec(QuickEval, MAN_VALUE); Inc(WhiteMen); Dec(Tempo, WHITE_TEMPO[i]); end; RP_BLACKMAN : begin Inc(QuickEval, MAN_VALUE); Inc(BlackMen); Inc(Tempo, BLACK_TEMPO[i]); end; RP_WHITEKING : begin Dec(QuickEval, KING_VALUE); Inc(WhiteKings); end; RP_BLACKKING : begin Inc(QuickEval, KING_VALUE); Inc(BlackKings); end; end; // case end; // for HashKey := CalculateHashKey(aBoard.Board); end; // with end; // InitializeBoard { $Log 27-11-2002, DG : First version. Simple moves. No jumps. 02-12-2002, DG : Implemented GenerateKingJump, GenerateManJump. 06-12-2002, DG : Added UndoMove. 09-12-2002, DG : Implemented UndoMove and GetMoveCount. 11-12-2002, DG : Fixed a bug in UndoMove and one in GenerateMoves. 18-12-2002, DG : New MoveList implementation. } end.
{ LEOShell - Intérprete de comandos experimental Copyright (C) 2015 - Valentín Costa - Leandro Lonardi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Controles; interface uses BaseUnix, Unix, CRT, SysUtils, DateUtils; const // Es usada para mostrar fecha y hora con el formato correcto. numeros: array [0..59] of string = ( '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59' ); type proceso = record pid: longint; comando: string; estado: string; end; arregloProcesos = array of proceso; arregloStrings = array of string; arregloDirents = array of dirent; var // Formato original del texto de la terminal. formatoOriginal: byte; // Directorio actual de trabajo. directorioActual: string; // String ingresado luego de prompt. entrada: string; // Arreglo cuyos elementos son el comando y sus opciones/argumentos. comando: arregloStrings; // Determina si, luego de un fork, el proceso hijo terminó. hijoTerminado: boolean; // Cantidad de trabajos ejecutados. cantidadProcesos: byte; // PID del último proceso ejecutado o detenido. ultimoProceso: longint; // Lista de todos los trabajos ejecutados. listaProcesos: arregloProcesos; procedure inicializar(); // Tratamiento de la entrada. procedure leer( var entrada: string ); function convertir( entrada: string ): arregloStrings; function hayOperador( argumentos: arregloStrings ): string; // Listado de archivos. procedure listarArchivos( lista: arregloDirents; opcion: char ); // Registro de los procesos. procedure agregarProceso( pid: longint; comando: string; estado: string ); procedure modificarProceso( pid: longint; estado: string ); function comandoProceso( pid: longint ): string; implementation { procedimiento INICIALIZAR: Asigna los valores iniciales de algunas de las variables globales. } procedure inicializar(); begin formatoOriginal := textAttr; cantidadProcesos := 0; ultimoProceso := -1; end; { procedimiento PROMPT: Escribe el prompt en pantalla. } procedure prompt(); var home, usuario: string; begin // Obtiene el directorio del home, el nombre de usuario y el directorio // actual de trabajo. home := fpGetEnv( 'HOME' ); usuario := fpGetEnv( 'USER' ); getDir( 0, directorioActual ); textColor( LightMagenta ); write( usuario + '@' + getHostName() + ' ' ); textColor( Yellow ); // Si la ruta del directorio actual comienza en home, reemplaza el // principio de la misma por '~'. if copy( directorioActual, 1, length( home ) ) = home then write( '~' + copy( directorioActual, length( home ) + 1, length( directorioActual ) ) ) else write( directorioActual ); // Si el usuario es root, muestra '#', de lo contrario muestra '$'. if (usuario = 'root') then write(' # ') else write(' $ '); // Restaura el formato original del texto de la terminal. textAttr := formatoOriginal; end; { función SIN ESPACIOS EXTRAS: Devuelve el string de entrada sin espacios de más, es decir, sólo con aquellos espacios necesarios (los que separan los comandos, opciones y argumentos). Ejemplo: ' ls -l /home ' -> 'ls -l /home' } function sinEspaciosExtras( entrada: string ): string; var posicion: integer; begin // Quita los espacios que están al principio. while entrada[1] = ' ' do entrada := copy( entrada, 2, length( entrada ) ); // Quita los espacios que están al final. while entrada[length( entrada )] = ' ' do entrada := copy( entrada, 1, length( entrada ) - 1); // Si hay dos espacios juntos, devuelve su posición. posicion := pos( ' ', entrada ); // Deja solamente un espacio entre palabras. while posicion <> 0 do begin delete( entrada, posicion, 1 ); posicion := pos( ' ', entrada ); end; sinEspaciosExtras := entrada; end; { procedimiento LEER: Muestra el prompt y lee un string hasta que éste sea distinto de vacío y no sea sólo espacios. Luego le quita los espacios que tenga de más. } procedure leer( var entrada: string ); begin repeat prompt(); readLn( entrada ); until (entrada <> '') and (entrada <> space( length( entrada ) )); entrada := sinEspaciosExtras( entrada ); end; { función CONVERTIR: Separa el string de entrada en sub-strings de acuerdo a los espacios que posea y los guarda en un arreglo. Ejemplo: 'ls -l /home/vale' -> ['ls', '-l', '/home/vale'] } function convertir( entrada: string ): arregloStrings; var argumentos: arregloStrings; i: byte; posicionEspacio, posicionComilla: integer; begin // Índice del arreglo. i := 0; // Establece el tamaño del arreglo. setLength( argumentos, i + 1 ); // Posición del primer espacio (' ') del string. posicionEspacio := pos( ' ', entrada ); // Mientras haya espacios, guarda los strings que estos separan en el arreglo. while posicionEspacio <> 0 do begin // Si se encuentra una comilla, se guarda el string hasta la siguiente comilla. if entrada[1] = '"' then begin delete( entrada, 1, 1 ); posicionComilla := pos( '"', entrada ); argumentos[i] := copy( entrada, 1, posicionComilla - 1 ); entrada := copy( entrada, posicionComilla + 1, length( entrada ) ); if entrada[1] = ' ' then delete( entrada, 1, 1 ); end // Si no, se guarda hasta el siguiente espacio. else begin argumentos[i] := copy( entrada, 1, posicionEspacio - 1 ); entrada := copy( entrada, posicionEspacio + 1, length( entrada ) ); end; posicionEspacio := pos( ' ', entrada ); // Si la entrada no es vacía, aumenta el tamaño del arreglo. if entrada <> '' then begin inc( i ); setLength( argumentos, i + 1 ); end; end; // Si la entrada no es vacía, la guarda como el último argumento. if entrada <> '' then argumentos[i] := entrada; convertir := argumentos; end; { función HAY OPERADOR: Devuelve la posición del operador (|, > o >>) en el arreglo que toma como argumento. Devuelve -1 si no lo encontró. } function hayOperador( argumentos: arregloStrings ): string; var i: byte; operador: string; begin // Índice del arreglo. i := 0; // Por defecto, sin operador. operador := ''; // Mientras no haya operador y no se acabe el arreglo, busca un operador. while (operador = '') and (i <= high( argumentos )) do begin if (argumentos[i] = '|') or (argumentos[i] = '>') or (argumentos[i] = '>>') then operador := argumentos[i] else inc( i ); end; hayOperador := operador; end; { procedimiento ORDERNAR POR NOMBRE: Ordena alfabéticamente los archivos (dirents*) de un arregloDirents según sus nombres. * Los dirents son registros que guardan la información de los archivos. } procedure ordenarPorNombre( var arreglo: arregloDirents ); var i, j: word; auxiliar: dirent; begin // Ordenamiento burbuja for i := 1 to high( arreglo ) do for j := 0 to high( arreglo ) - i do if upCase( arreglo[j].d_name ) > upCase( arreglo[j+1].d_name ) then begin auxiliar := arreglo[j+1]; arreglo[j+1] := arreglo[j]; arreglo[j] := auxiliar; end; end; { procedimiento COLOR TIPO: Establece el color con el que escribir nombre del archivo según su tipo. Nota: debe cambiar el color sólo si se está escibiendo en pantalla; de escribir en un archivo, puede mostrar caracteres inesperados. } procedure colorTipo( archivo: dirent; info: stat ); begin // Si no hay operador, establece el color del texto según el tipo de archivo. if hayOperador( comando ) = '' then begin if fpS_ISLNK( info.st_mode ) then textColor( LightCyan ) else if fpS_ISDIR( info.st_mode ) then textColor( LightBlue ) else if fpS_ISREG( info.st_mode ) then if pos( '.', archivo.d_name{pChar(@d_name[0])} ) <> 0 then textColor( White ) else textColor( LightGreen ); end; end; { función PERMISOS ARCHIVOS: Devuelve un string con los permisos de un archivo respecto a la lectura, escritura y ejecución del usuario, el grupo y los demás. } function permisosArchivo( mode: mode_t ): string; var resultado: string; begin resultado := ''; // Permisos del usuario if STAT_IRUSR and mode = STAT_IRUSR then resultado := resultado + 'r' else resultado := resultado + '-'; if STAT_IWUSR and mode = STAT_IWUSR then resultado := resultado + 'w' else resultado := resultado + '-'; if STAT_IXUSR and mode = STAT_IXUSR then resultado := resultado + 'x' else resultado := resultado + '-'; // Permisos del grupo if STAT_IRGRP and mode = STAT_IRGRP then resultado := resultado + 'r' else resultado := resultado + '-'; if STAT_IWGRP and mode = STAT_IWGRP then resultado := resultado + 'w' else resultado := resultado + '-'; if STAT_IXGRP and mode = STAT_IXGRP then resultado := resultado + 'x' else resultado := resultado + '-'; // Permisos de los demás if STAT_IROTH and mode = STAT_IROTH then resultado := resultado + 'r' else resultado := resultado + '-'; if STAT_IWOTH and mode = STAT_IWOTH then resultado := resultado + 'w' else resultado := resultado + '-'; if STAT_IXOTH and mode = STAT_IXOTH then resultado := resultado + 'x' else resultado := resultado + '-'; permisosArchivo := resultado; end; { procedimiento LISTAR ARCHIVOS: Muestra la información de los archivos almacenados en un arregloDirents de acuerdo a la opción especificada. } procedure listarArchivos( lista: arregloDirents; opcion: char ); var ano, mes, dia, horas, minutos, segundos, milisegundos: word; archivo: stat; fecha: TDateTime; i, cantidadArchivos: word; begin case opcion of // Muestra todos los archivos no ocultos de forma ordenada y con color. '_': begin ordenarPorNombre( lista ); // Recorre toda la lista (arreglo) de archivos. for i := 0 to high( lista ) do begin // Si el nombre del archivo no comienza con '.', lo muestra. if lista[i].d_name[0] <> '.' then with lista[i] do begin fpLStat( pChar(@d_name[0]), archivo ); // Establece el color para escribir el nombre. colorTipo( lista[i], archivo ); writeLn( pChar(@d_name[0]) ); end; end; end; // Muestra todos los archivos (incluso los ocultos) de forma ordenada y con color. 'a': begin ordenarPorNombre( lista ); // Recorre toda la lista (arreglo) de archivos. for i := 0 to high( lista ) do with lista[i] do begin fpLStat( pChar(@d_name[0]), archivo ); // Establece el color para escribir el nombre. colorTipo( lista[i], archivo ); writeLn( pChar(@d_name[0]) ); end; end; // Muestra todos los archivos (incluso los ocultos) de forma desordenada // y sin color. 'f': for i := 0 to high( lista ) do with lista[i] do writeLn( pChar(@d_name[0]) ); // Muestra archivos no ocultos de forma ordenada, con color, sus tamaños, // permisos y fechas de modificacion. 'l': begin ordenarPorNombre( lista ); // Establece la cantidad inicial de archivos. cantidadArchivos := 0; // Recorre toda la lista (arreglo) de archivos. for i := 0 to high( lista ) do // Si el nombre del archivo no comienza con '.', lo muestra. if lista[i].d_name[0] <> '.' then with lista[i] do begin fpLStat( pChar(@d_name[0]), archivo ); write( archivo.st_size:10 ); write( permisosArchivo( archivo.st_mode ):11 ); // Obtiene la fecha de modificación y la decodifica. fecha := unixToDateTime( archivo.st_ctime ); decodeDate( fecha, ano, mes, dia ); decodeTime( fecha, horas, minutos, segundos, milisegundos ); write( ' ' ); write( numeros[dia], '/', numeros[mes], '/', ano, ' ', numeros[horas], ':', numeros[minutos], ' ' ); // Establece el color para escribir el nombre. colorTipo( lista[i], archivo ); writeLn( pChar(@d_name[0]) ); // Restaura el formato original del texto de la terminal. textAttr := formatoOriginal; inc( cantidadArchivos ); end; writeLn( 'Cantidad de archivos: ', cantidadArchivos ); end; end; // Restaura el formato original del texto de la terminal. textAttr := formatoOriginal; end; { procedimiento AGREGAR PROCESO: Agrega un nuevo trabajo al arreglo "listaProcesos" (variable global). Esto ocurre cuando un proceso es detenido o ejecutado en segundo plano. } procedure agregarProceso( pid: longint; comando: string; estado: string ); begin // Incrementa la cantidad de procesos actuales. inc( cantidadProcesos ); // Aumenta el tamaño de la lista de procesos (arreglo). setLength( listaProcesos, cantidadProcesos ); // Asigna los datos correspondientes al proceso. listaProcesos[cantidadProcesos-1].pid := pid; listaProcesos[cantidadProcesos-1].comando := comando; listaProcesos[cantidadProcesos-1].estado := estado; end; { procedimiento MODIFICAR PROCESO: Cambia el estado de un poceso. Esto ocurre cuando un proceso pasa de estar detenido a ejecutarse. } procedure modificarProceso( pid: longint; estado: string ); var i: byte; begin // Recorre la lista de procesos (arreglo). for i := 0 to high( listaProcesos ) do // Si lo encuentra, le cambia el estado. if listaProcesos[i].pid = pid then listaProcesos[i].estado := estado; end; { función COMANDO PROCESO: Devuelve el comando asociado al proceso de PID especificado. } function comandoProceso( pid: longint ): string; var i: byte; begin // Recorre la lista de procesos (arreglo). for i := 0 to high( listaProcesos ) do // Si lo encuentra, devuelve el comando. if listaProcesos[i].pid = pid then comandoProceso := listaProcesos[i].comando; end; end.
{ @exclude } unit rtcDBTypes; interface uses DB, DBClient, rtcInfo; {$include rtcDefs.inc} const RTC_DB2FIELD_TYPE: array[TFieldType] of TRtcFieldTypes = ( ft_Unknown, ft_String, ft_Smallint, ft_Integer, ft_Word, ft_Boolean, ft_Float, ft_Currency, ft_BCD, ft_Date, ft_Time, ft_DateTime, ft_Bytes, ft_VarBytes, ft_AutoInc, ft_Blob, ft_Memo, ft_Graphic, ft_FmtMemo, ft_ParadoxOle, ft_DBaseOle, ft_TypedBinary, ft_Cursor, ft_FixedChar, ft_WideString, ft_Largeint, ft_ADT, ft_Array, ft_Reference, ft_DataSet {$IFNDEF IDE_0} ,ft_OraBlob, ft_OraClob, ft_Variant, ft_Interface, ft_IDispatch,ft_Guid {$IFNDEF IDE_1} , ft_TimeStamp, ft_FMTBcd {$IFDEF IDE_2006up} , ft_WideString, ft_WideString, ft_TimeStamp, ft_Variant {$ENDIF} {$ENDIF} {$ENDIF} ); RTC_FIELD2DB_TYPE: array[TRtcFieldTypes] of TFieldType = ( ftUnknown, ftString, ftSmallint, ftInteger, ftWord, ftBoolean, ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, ftBytes, ftVarBytes, ftAutoInc, ftBlob, ftMemo, ftGraphic, ftFmtMemo, ftParadoxOle, ftDBaseOle, ftTypedBinary, ftCursor, ftFixedChar, {$IFDEF IDE_1} ftString, // TDataSet in D4 doesn't really support WideString {$ELSE} ftWideString, {$ENDIF} ftLargeint, ftADT, ftArray, ftReference, ftDataSet {$IFNDEF IDE_1} ,ftOraBlob, ftOraClob, ftVariant, ftInterface, ftIDispatch,ftGuid, ftTimeStamp, ftFMTBcd {$ELSE} ,ftBlob, ftMemo, ftString, ftBlob, ftBlob, ftString, ftDateTime, ftBcd {$ENDIF}); // Can be used to copy data (this code only supports native types, no blobs) from a RTC Dataset to a TDataSet procedure RtcDataSetToDelphi(rtcDS:TRtcDataSet; DelphiDS:TDataSet; ClearFieldDefs:boolean=True); // Can be used to copy data (this code only supports native types, no blobs) from a TDataSet to a RTC Dataset procedure DelphiDataSetToRtc(DelphiDS:TDataSet; rtcDS:TRtcDataSet; ClearFieldDefs:boolean=True); implementation procedure RtcDataSetToDelphi(rtcDS:TRtcDataSet; DelphiDS:TDataSet; ClearFieldDefs:boolean=True); var flds:integer; fldname:string; field:TField; begin if ClearFieldDefs then begin DelphiDS.Active:=False; DelphiDS.FieldDefs.Clear; for flds:=0 to rtcDS.FieldCount-1 do begin fldname:=rtcDS.FieldName[flds]; DelphiDS.FieldDefs.Add(fldname, RTC_FIELD2DB_TYPE[rtcDS.FieldType[fldname]], rtcDS.FieldSize[fldname], rtcDS.FieldRequired[fldname]); end; if DelphiDS is TClientDataSet then TClientDataSet(DelphiDS).CreateDataSet; end; if not DelphiDS.Active then DelphiDS.Active:=True; rtcDS.First; while not rtcDS.EOF do begin DelphiDS.Append; for flds:=0 to rtcDS.FieldCount-1 do begin fldname:=rtcDS.FieldName[flds]; field:=delphiDS.FindField(fldname); if assigned(field) then field.Value:=rtcDS.Value[fldname]; end; rtcDS.Next; end; end; procedure DelphiDataSetToRtc(DelphiDS:TDataSet; rtcDS:TRtcDataSet; ClearFieldDefs:boolean=True); var fdef:TFieldDef; flds:integer; fldname:string; field:TField; begin if ClearFieldDefs then begin rtcDS.Clear; for flds:=0 to DelphiDS.FieldCount-1 do begin fdef:=DelphiDS.FieldDefs.Items[flds]; fldname:=fdef.Name; field:=DelphiDS.FindField(fldname); if assigned(field) then rtcDS.SetField(fldname, RTC_DB2FIELD_TYPE[fdef.DataType], fdef.Size, fdef.Required); end; end; DelphiDS.First; while not delphiDS.EOF do begin rtcDS.Append; for flds:=0 to rtcDS.FieldCount-1 do begin fldname:=rtcDS.FieldName[flds]; field:=delphiDS.FindField(fldname); if assigned(field) then rtcDS.Value[fldname]:=field.Value; end; delphiDS.Next; end; end; end.
unit pFIBEditorsConsts; interface const (************************************) (** Database parameter block stuff **) (************************************) isc_dpb_version1 = 1; isc_dpb_cdd_pathname = 1; isc_dpb_allocation = 2; isc_dpb_journal = 3; isc_dpb_page_size = 4; isc_dpb_num_buffers = 5; isc_dpb_buffer_length = 6; isc_dpb_debug = 7; isc_dpb_garbage_collect = 8; isc_dpb_verify = 9; isc_dpb_sweep = 10; isc_dpb_enable_journal = 11; isc_dpb_disable_journal = 12; isc_dpb_dbkey_scope = 13; isc_dpb_number_of_users = 14; isc_dpb_trace = 15; isc_dpb_no_garbage_collect = 16; isc_dpb_damaged = 17; isc_dpb_license = 18; isc_dpb_sys_user_name = 19; isc_dpb_encrypt_key = 20; isc_dpb_activate_shadow = 21; isc_dpb_sweep_interval = 22; isc_dpb_delete_shadow = 23; isc_dpb_force_write = 24; isc_dpb_begin_log = 25; isc_dpb_quit_log = 26; isc_dpb_no_reserve = 27; isc_dpb_user_name = 28; isc_dpb_password = 29; isc_dpb_password_enc = 30; isc_dpb_sys_user_name_enc = 31; isc_dpb_interp = 32; isc_dpb_online_dump = 33; isc_dpb_old_file_size = 34; isc_dpb_old_num_files = 35; isc_dpb_old_file = 36; isc_dpb_old_start_page = 37; isc_dpb_old_start_seqno = 38; isc_dpb_old_start_file = 39; isc_dpb_drop_walfile = 40; isc_dpb_old_dump_id = 41; isc_dpb_wal_backup_dir = 42; isc_dpb_wal_chkptlen = 43; isc_dpb_wal_numbufs = 44; isc_dpb_wal_bufsize = 45; isc_dpb_wal_grp_cmt_wait = 46; isc_dpb_lc_messages = 47; isc_dpb_lc_ctype = 48; isc_dpb_cache_manager = 49; isc_dpb_shutdown = 50; isc_dpb_online = 51; isc_dpb_shutdown_delay = 52; isc_dpb_reserved = 53; isc_dpb_overwrite = 54; isc_dpb_sec_attach = 55; isc_dpb_disable_wal = 56; isc_dpb_connect_timeout = 57; isc_dpb_dummy_packet_interval = 58; isc_dpb_gbak_attach = 59; isc_dpb_sql_role_name = 60; isc_dpb_set_page_buffers = 61; isc_dpb_working_directory = 62; isc_dpb_SQL_dialect = 63; isc_dpb_set_db_readonly = 64; isc_dpb_set_db_SQL_dialect = 65; isc_dpb_gfix_attach = 66; isc_dpb_gstat_attach = 67; //IB 2007 isc_dpb_gbak_ods_version = 68; isc_dpb_gbak_ods_minor_version = 69; isc_dpb_set_group_commit = 70; isc_dpb_gbak_validate = 71; isc_dpb_client_interbase_var = 72; isc_dpb_admin_option = 73; isc_dpb_flush_interval = 74; isc_dpb_instance_name = 75; isc_dpb_old_overwrite = 76; isc_dpb_archive_database = 77; isc_dpb_archive_journals = 78; isc_dpb_archive_sweep = 79; isc_dpb_archive_dumps = 80; isc_dpb_archive_recover = 81; isc_dpb_recover_until = 82; isc_dpb_force = 83; // isc_dpb_last_dpb_constant = isc_dpb_force; DPBConstantNames: array[1..isc_dpb_last_dpb_constant] of String = ( 'cdd_pathname', 'allocation', 'journal', 'page_size', 'num_buffers', 'buffer_length', 'debug', 'garbage_collect', 'verify', 'sweep', 'enable_journal', 'disable_journal', 'dbkey_scope', 'number_of_users', 'trace', 'no_garbage_collect', 'damaged', 'license', 'sys_user_name', 'encrypt_key', 'activate_shadow', 'sweep_interval', 'delete_shadow', 'force_write', 'begin_log', 'quit_log', 'no_reserve', 'user_name', 'password', 'password_enc', 'sys_user_name_enc', 'interp', 'online_dump', 'old_file_size', 'old_num_files', 'old_file', 'old_start_page', 'old_start_seqno', 'old_start_file', 'drop_walfile', 'old_dump_id', 'wal_backup_dir', 'wal_chkptlen', 'wal_numbufs', 'wal_bufsize', 'wal_grp_cmt_wait', 'lc_messages', 'lc_ctype', 'cache_manager', 'shutdown', 'online', 'shutdown_delay', 'reserved', 'overwrite', 'sec_attach', 'disable_wal', 'connect_timeout', 'dummy_packet_interval', 'gbak_attach', 'sql_role_name', 'set_page_buffers', 'working_directory', 'sql_dialect', 'set_db_readonly', 'set_db_sql_dialect', 'gfix_attach', 'gstat_attach', //IB2007 'gbak_ods_version', 'gbak_ods_minor_version', 'set_group_commit', 'gbak_validate', 'client_interbase_var', 'admin_option', 'flush_interval', 'instance_name', 'old_overwrite', 'archive_database', 'archive_journals', 'archive_sweep', 'archive_dumps', 'archive_recover', 'recover_until', 'force' ); ResourceString SCompEditEditFieldInfo = 'Edit field information table'; SCompEditErrorMessages = 'Edit error messages table'; SRepositoriesScript = 'Metadata for repository tables'; SScriptExecutor = 'Execute script'; SDBEditCaption = 'Connection Properties'; SDBEditServerGroup = ' Server '; SDBEditServer = '&Server'; SDBEditNetProtocol = '&Network protocol'; SDBEditDatabase = '&Database'; SDBEditAlias = '&Alias name'; SDBEditLocal = '&Local engine'; SDBEditRemote = '&Remote server'; SDBEditBrowse = '&Browse'; SDBEditConnectParams = 'Connection Parameters'; SDBEditUserName = '&User name'; SDBEditPassword = '&Password'; SDBEditSQLRole = 'Rol&e'; SDBEditConnectCharSet = 'C&harSet'; SDBEditSQLDialect = 'S&QL Dialect'; SDBEditLoginPromt = 'Use lo&gin prompt'; SDBEditTestButton = '&Test'; SDBEditGDBFilter = 'IB/FB Database Files (*.gdb;*.ib;*.fdb)|*.gdb;*.ib;*.fdb|'+ 'Interbase Database Files (*.gdb)|*.gdb|'+ 'Firebird Database Files (*.fdb)|*.fdb|'+ 'Interbase7 Database Files (*.ib)|*.ib|All files (*.*)|*.*'; SDBEditSuccessConnection = 'Connection is successful'; SCompDatabaseNotConnected = 'Database component is not set properly or not connected'; SCompEditInfoFieldsNotExist = 'Table FIB$FIELDS_INFO does not exist. Would you like to create it?'; SCompEditInfoTableNotExist = 'Table FIB$DATASETS_INFO does not exist. Would you like to create it?'; SCompEditErrorTableNotExist = 'Table FIB$ERROR_MESSAGES does not exist. Would you like to create it?'; SOKButton = '&OK'; SCancelButton = '&Cancel'; //FieldRepository Editor SFieldInfoCaption = 'Developers Data Repository'; SFieldInfoCopyFieldsHint = 'Copy fields from current meta-object'; SFieldInfoCopyFields = '&Copy fields'; SFieldInfoFilter = '&Filter by current meta-object'; SFieldInfoKindTables = 'Tables/Views'; SFieldInfoProcedures = 'Stored Procedures'; SFieldInfoFilterHint = 'Filter text'; SFieldInfoGridHint = 'List of tables or stored procedures'; SFieldInfoTablesItem = 'Tables'; SFieldInfoProcedureItem = 'Procedures'; SFieldInfoUserFormsItem = 'User forms'; // Error repository //Conditions Edit frame FPConditionsCaption = 'Edit Conditions'; FPConditionsText = ' Condition text '; FPConditionsNames = ' Condition Names '; FPConditionsColumnConditions = 'Conditions'; FPConditionsDelete = '&Delete'; FPConditionsAdd = '&Add'; FPConditionsClear = 'C&lear'; //Dataset Repository editor SEdDataSetInfoCaption = 'Choose DataSet repository information'; SEdDataSetInfoFields = 'Other fields'; SEdDataSetInfoKeyField = 'Key field'; SEdDataSetInfoGenerator = 'Generator'; SEdDataSetInfoFilter = 'Filter'; //Transaction Editor SCompEditEditTransaction = 'Edit transaction parameters'; STransEditCaption = 'Transaction Editor'; STransEditKind = 'Kind of transaction'; STransEditSettings = '&Settings:'; STransEditNewKind = '&New kind'; STransEditSaveKindButton = '&Save kind'; STransEditExportButton = '&Export to INI'; STransEditImportButton = '&Import from INI'; STransEditOpenFilter = 'Transaction kinds *.trk|*.trk|*.ini |*.ini'; STransEditSaveFilter = 'Transaction kinds *.trk|*.trk'; STransEditExportTitle = 'Export transaction settings to file'; STransEditNewKindDialog = 'Input new kind of transaction'; STransEditNewKindName = 'Name of kind'; // Dataset Options Editor FPOptionsCaption = '%s - Options, PrepareOptions'; FPOptionsPage = 'Options'; FPOptionsTrimChars = 'Trim char fields'; FPOptionsRefresh = 'Refresh current record after posting'; FPOptionsRefreshDelete = 'Delete non existing records from local buffer'; FPOptionsAutoStart = 'Auto start transaction before opening'; FPOptionsApplyFormats = 'Apply DefaultFormats to DisplayFormat and EditFormat'; FPOptionsIdleUpdate = 'Execute idle update before record editing'; FPOptionsKeepSort = 'Place modified record according to sorting order'; FPOptionsRestoreSort = 'Restore local sorting after re-opening'; FPOptionsPreparePage = 'PrepareOptions'; FPOptionsSetRequired = 'Set Required property in TField components according to NOT NULL state'; FPOptionsSetReadOnly = 'Set ReadOnly property in TField components for calculated fields'; FPOptionsSetDefault = 'Set Default property of TField components according to table description'; FPOptionsEmulateBoolean = 'Emulate boolean fields'; FPOptionsCreateBCD = 'Create TBCDField instances for INT64 fields with any scale (SQLDialect 3)'; FPOptionsApplyRepository = 'Apply FIBPlus Repository options to field propetries, queries, etc'; FPOptionsSortFields = 'Fill SortFields property using ORDER BY clause'; FPOptionsRecordCount = 'Get record count without fetching all records'; FPVisibleRecno = 'Recno for visible records only'; //AutoUpdateOptions FPAutoOptEditorCaption = '%s - AutoUpdateOptions Editor'; FPAutoOptEditorPrimaryKey = 'Primary key field(s):'; FPAutoOptEditorModTable = 'Modifying table'; FPAutoOptEditorSQL = ' SQL generation '; FPAutoOptEditorAutoGen = 'Auto generation of modifying queries after DataSet opening'; FPAutoOptEditorModFields = 'Include in UpdateSQL only modified fields'; FPAutoOptEditorAutoInc = ' Auto increment options '; FPAutoOptEditorGenName = 'Generator Name'; FPAutoOptEditorWhenGet1 = 'Do not get generator value'; FPAutoOptEditorWhenGet2 = 'Get new generator value when inserting of new record'; FPAutoOptEditorWhenGet3 = 'Get new generator value before posting of new record'; //SQL generator SGenSQLCaption = 'FIBPlus SQL Generator'; SGenSQLOptions = 'Options'; SGenSQLGetFieldsButton = 'Get &table fields'; SGenSQLGenerateButton = '&Generate SQLs'; SGenSQLClearButton = '&Clear SQLs'; SGenSQLOnSaveGroup = 'On save SQLs'; SGenSQLCheckSQLHint = 'Check SQLs before saving properties'; SGenSQLCheckSQL = 'Check SQLs'; SGenSQLFieldOriginHint = 'Save fields origin'; SGenSQLFieldOrigin = 'Field origins'; SGenSQLGeneratorOptions = 'Options of SQLs generation'; SGenSQLPrimaryHint = 'Use only primary key in where clause'; SGenSQLPrimary = 'Where by primary key'; SGenSQLNonUpdatePrimaryHint = 'Not to change primary key in UpdateSQL'; SGenSQLNonUpdatePrimary = 'Not to update primary key'; SGenSQLDefaultSymbol = 'Use '#39'?'#39' for parameters'; SGenSQLCheckButton = 'C&heck SQLs'; SGenSQLKeyFields = 'Key fields'; SGenSQLUpdateFields = 'Update fields'; SGenSQL_SQLsTabs = 'SQLs'; SGenSQLStatement = 'Statement &type'; SGenSQLMakeSQLTab = 'Make SQL'; SGenSQLFilterBy = 'Filter by'; SGenSQLAlias = 'Table alias'; SGenSQLTablesColumn = 'Tables'; SGenSQLView1 = 'No Objects'; SGenSQLView2 = 'Tables/Views'; SGenSQLView3 = 'Stored Procedures'; SGenSQLTargetMemo = 'Target memo'; SGenSQLOutput1 = 'Add to buffer memo'; SGenSQLOutput2 = 'Replace SelectSQL '; SGenSQLOutput3 = 'Add as JOIN to SelectSQL'; SGenSQLSaveAllButton = 'Save &all'; SGenSQLReplaceButton = 'Re&place "*"'; SGenSQLCheckErrorButton = 'Check &error'; SGenSQLSaveSQLButtonHint = 'Save current SQL'; SReplaceSQL = '&Replace Select SQL text'; SGenSQLSaveSQLButton = '&Save SQL'; SGenSQLErrorPreffix = 'Error in %s'; SGenSQLEmpty = 'SQL is empty'; SGenSQLCorrectSQL = 'SQL is correct'; SGenSQLFromNotFound = 'Clause "FROM" is not found'; SCheckSQLs ='Check SQLs'; SEditSQL ='Edit SQL text'; SNoErrors ='No Errors'; SErrorIn ='Error in :'; SEInvalidCharsetData='Invalid data charset %s. Need charset %s'; SErrorInProc ='Error in %s procedure %s '#13#10; //Dataset Editor SCompEditDBEditor = 'Database Editor'; SCompEditSQLGenerator = 'SQL Generator'; SCompSaveToDataSetInfo = 'Save to dataSets repository table'; SCompChooseDataSetInfo = 'Choose from dataSets repository table'; SCompEditDataSetInfo = 'Edit dataSets repository table'; SCompEditDataSet_ID = '.DataSet_ID should be greater than 0'; SCompEditSQLText = '(SQL Text)'; SCompEditStatTableExist = 'Statistic table already exists.'; SCompEditStatTableCreated = 'Statistic table has been created successfully.'; SCompEditCreateStatTable = 'Create statistic table'; SCompEditDataSetInfoNotExists = 'Table FIB$DATASETS_INFO does not exist.'; SCompEditDataSetInfoForbid = 'Can''t use FIB$DATASETS_INFO.'#13#10+ 'urDataSetInfo not included into Database.UseRepositories.'; SCompEditUnableInsertInfoRecord = 'Error of inserting new information record'; SCompEditSaveDataSetProperty = 'Save FIBDataSet properties'; SCompEditDataSetDesc = 'Set dataset description'; SCompEditFieldInfoLoadError = 'Error of loading FieldInfo from stream'; SDataBaseNotAssigned = 'Database is not assigned'; SCompEditDeltaReceiver1='Create common triggers'; SCompEditDeltaReceiver2='Create triggers for table %s'; SCompEditDeltaReceiverErr1='Can''t create triggers. Table name is empty.'; SCompEditDeltaReceiverErr2='Can''t create triggers. Transaction not assigned.'; //SQL texts const qryExistTable= 'select COUNT(RDB$RELATION_NAME)'#13#10+ 'from RDB$RELATIONS where RDB$FLAGS = 1'#13#10+ 'and RDB$RELATION_NAME=?RT'; qryExistField='Select Count(*) from RDB$RELATION_FIELDS'#13#10+ 'where RDB$RELATION_NAME= :TABNAME and RDB$FIELD_NAME =:FIELDNAME'; qryExistDomain= 'Select Count(*) FROM RDB$FIELDS FLD'#13#10 + 'WHERE FLD.RDB$FIELD_NAME = ?DOMAIN' ; qryCreateBooleanDomain= 'CREATE DOMAIN FIB$BOOLEAN AS SMALLINT DEFAULT 1 NOT NULL CHECK (VALUE IN (0,1))'; qryCreateFieldInfoVersionGen ='CREATE GENERATOR FIB$FIELD_INFO_VERSION'; qryTabFieldsSQL=' Select RDB$FIELD_NAME from RDB$RELATION_FIELDS '+ 'where RDB$RELATION_NAME=?tabName order by RDB$FIELD_POSITION'; qrySPFieldsSQL='select RDB$PARAMETER_NAME, RDB$PARAMETER_NUMBER, RDB$PARAMETER_TYPE '+ 'from RDB$PROCEDURE_PARAMETERS WHERE RDB$PROCEDURE_NAME=?PN AND RDB$PARAMETER_TYPE=1'; qryGeneratorExist=' Select COUNT(*) from RDB$GENERATORS where RDB$GENERATOR_NAME=:GEN_NAME'; qryCreateTabFieldsRepository= 'CREATE TABLE FIB$FIELDS_INFO (TABLE_NAME VARCHAR(31) NOT NULL,'#13#10+ ' FIELD_NAME VARCHAR(31) NOT NULL,'#13#10+ ' DISPLAY_LABEL VARCHAR(25),'#13#10+ ' VISIBLE FIB$BOOLEAN DEFAULT 1 NOT NULL,'#13#10+ ' DISPLAY_FORMAT VARCHAR(15),'#13#10+ ' EDIT_FORMAT VARCHAR(15),'#13#10+ ' TRIGGERED FIB$BOOLEAN DEFAULT 0 NOT NULL,'#13#10+ ' CONSTRAINT PK_FIB$FIELDS_INFO PRIMARY KEY (TABLE_NAME, FIELD_NAME)'#13#10+ ')'; qryCreateFieldRepositoryTriggerBI= ' CREATE TRIGGER FIB$FIELDS_INFO_BI FOR FIB$FIELDS_INFO '#13#10+ ' ACTIVE BEFORE INSERT POSITION 0 AS '+#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; qryCreateFieldRepositoryTriggerBU= ' CREATE TRIGGER FIB$FIELDS_INFO_BU FOR FIB$FIELDS_INFO '#13#10+ ' ACTIVE BEFORE UPDATE POSITION 0 AS '+#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; qryCreateDataSetsRepository= 'CREATE TABLE FIB$DATASETS_INFO ('#13#10+ ' DS_ID INTEGER NOT NULL,'#13#10+ ' DESCRIPTION VARCHAR(40),'+ ' SELECT_SQL BLOB sub_type 1 segment size 80,'#13#10+ ' UPDATE_SQL BLOB sub_type 1 segment size 80,'#13#10+ ' INSERT_SQL BLOB sub_type 1 segment size 80,'#13#10+ ' DELETE_SQL BLOB sub_type 1 segment size 80,'#13#10+ ' REFRESH_SQL BLOB sub_type 1 segment size 80,'#13#10+ ' NAME_GENERATOR VARCHAR(68), '#13#10+ ' KEY_FIELD VARCHAR(68),'#13#10+ ' UPDATE_TABLE_NAME VARCHAR(68),'#13#10+ ' UPDATE_ONLY_MODIFIED_FIELDS FIB$BOOLEAN NOT NULL,'#13#10+ ' CONDITIONS BLOB sub_type 1 segment size 80,'#13#10+ ' FIB$VERSION INTEGER,'#13#10+ ' CONSTRAINT PK_FIB$DATASETS_INFO PRIMARY KEY (DS_ID)'#13#10+ ')'; qryCreateDataSetRepositoryTriggerBI= ' CREATE TRIGGER FIB$DATASETS_INFO_BI FOR FIB$DATASETS_INFO '#13#10+ ' ACTIVE BEFORE INSERT POSITION 0 AS '+#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; qryCreateDataSetRepositoryTriggerBU= ' CREATE TRIGGER FIB$DATASETS_INFO_BU FOR FIB$DATASETS_INFO '#13#10+ ' ACTIVE BEFORE UPDATE POSITION 0 AS '#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; qryCreateErrorsRepository= 'CREATE TABLE FIB$ERROR_MESSAGES ('#13#10+ ' CONSTRAINT_NAME VARCHAR(67) NOT NULL,'#13#10+ ' MESSAGE_STRING VARCHAR(100),'#13#10+ ' FIB$VERSION INTEGER,'#13#10+ ' CONSTR_TYPE VARCHAR(11) DEFAULT ''UNIQUE'' NOT NULL,'#13#10+ ' CONSTRAINT PK_FIB$ERROR_MESSAGES PRIMARY KEY (CONSTRAINT_NAME)'#13#10+ ')'; qryCreateErrorsRepositoryTriggerBI= ' CREATE TRIGGER FIB$ERROR_MESSAGES_BI FOR FIB$ERROR_MESSAGES '#13#10+ ' ACTIVE BEFORE INSERT POSITION 0 AS '#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; qryCreateErrorsRepositoryTriggerBU= ' CREATE TRIGGER FIB$ERROR_MESSAGES_BU FOR FIB$ERROR_MESSAGES '#13#10+ ' ACTIVE BEFORE UPDATE POSITION 0 AS '#13#10+ ' BEGIN '+#13#10+ ' NEW.FIB$VERSION=GEN_ID(FIB$FIELD_INFO_VERSION,1);'+#13#10+ ' END'; implementation end.
// // This unit is part of the GLScene Project, http://glscene.org // { : GLFullscreenViewer<p> A Platform specific full-screen viewer.<p> Note: Eng: Lazarus has problems with minimizing and normalizing windows. See code DoAvtivate DoDeactivate. Tests were conducted on Lazarus 0.9.29.24627. If these problems are fixed in future versions of FPC / Lazarus, you can safely remove work-arounds. Note: Linux still has problems intercepting mouse events and problems with DoActivate DoDeactivate. Ru(CP1251) В лазарусе есть проблемы минимизации - нормализации окна. Смотри код DoAvtivate DoDeactivate. Тесты проводились на лазарусе 0.9.29.24627. В случае устранения проблем в лазарусе, удалите код лазаруса оставив тот который для делфи. Модуль еще не закончен! В линуксе есть проблемы перехвата мыши и проблемы с DoActivate DoDeactivate.<p> <b>History : </b><font size=-1><ul> <li>22/08/10 - DaStr - Restored backward-compatibility after previous changes <li>11/06/10 - Yar - Fixed uses section after lazarus-0.9.29.26033 release <li>28/04/10 - Yar - Merged GLFullScreenViewer and GLWin32FullScreenViewer into one unit (by Rustam Asmandiarov aka Predator) <li>08/04/10 - Yar - Added more UNIX compatibility (thanks Rustam Asmandiarov aka Predator) <li>07/01/10 - DaStr - Added UNIX compatibility (thanks Predator) <li>07/11/09 - DaStr - Added to main GLScene CVS repository (from GLScene-Lazarus) <li>24/07/03 - EG - Creation from GLWin32Viewer split </ul></font> } unit GLFullScreenViewer; interface {$I GLScene.inc} uses Winapi.Windows, Winapi.Messages, System.Classes, System.SysUtils, VCL.Forms, VCL.Controls, VCL.Menus, GLViewer, GLScene, GLContext; type // TGLScreenDepth // TGLScreenDepth = (sd8bits, sd16bits, sd24bits, sd32bits); // TGLFullScreenViewer // { : A FullScreen viewer.<p> This non visual viewer will, when activated, use the full screen as rendering surface. It will also switch/restore videomode depending on the required width/height.<br> This is performed by creating an underlying TForm and using its surface for rendering OpenGL, "decent" ICDs will automatically use PageFlipping instead of BlockTransfer (slower buffer flipping mode used for windowed OpenGL).<br> Note: if you terminate the application either via a kill or in the IDE, the original resolution isn't restored. } TGLFullScreenViewer = class(TGLNonVisualViewer) private { Private Declarations } FFormIsOwned: Boolean; FForm: TForm; FOwnDC: HWND; FScreenDepth: TGLScreenDepth; FActive: Boolean; FSwitchedResolution: Boolean; FManualRendering: Boolean; FUpdateCount: Integer; FOnMouseDown: TMouseEvent; FOnMouseUp: TMouseEvent; FOnMouseMove: TMouseMoveEvent; FOnMouseWheel: TMouseWheelEvent; FOnMouseWheelDown: TMouseWheelUpDownEvent; FOnMouseWheelUp: TMouseWheelUpDownEvent; FOnClick, FOnDblClick: TNotifyEvent; FOnKeyDown: TKeyEvent; FOnKeyUp: TKeyEvent; FOnKeyPress: TKeyPressEvent; FOnClose: TCloseEvent; FOnCloseQuery: TCloseQueryEvent; FStayOnTop: Boolean; FVSync: TVSyncMode; FRefreshRate: Integer; FCursor: TCursor; FPopupMenu: TPopupMenu; procedure SetScreenDepth(const val: TGLScreenDepth); procedure SetActive(const val: Boolean); procedure SetOnMouseDown(const val: TMouseEvent); procedure SetOnMouseUp(const val: TMouseEvent); procedure SetOnMouseMove(const val: TMouseMoveEvent); procedure SetOnMouseWheel(const val: TMouseWheelEvent); procedure SetOnMouseWheelDown(const val: TMouseWheelUpDownEvent); procedure SetOnMouseWheelUp(const val: TMouseWheelUpDownEvent); procedure SetOnClick(const val: TNotifyEvent); procedure SetOnDblClick(const val: TNotifyEvent); procedure SetOnCloseQuery(const val: TCloseQueryEvent); procedure SetOnClose(const val: TCloseEvent); procedure SetOnKeyUp(const val: TKeyEvent); procedure SetOnKeyDown(const val: TKeyEvent); procedure SetOnKeyPress(const val: TKeyPressEvent); procedure SetStayOnTop(const val: Boolean); procedure SetCursor(const val: TCursor); procedure SetPopupMenu(const val: TPopupMenu); procedure SetForm(aVal: TForm); procedure SetManualRendering(const val: Boolean); protected { Protected Declarations } function GetHandle: HWND; procedure DoBeforeRender(Sender: TObject); procedure DoBufferChange(Sender: TObject); override; procedure DoBufferStructuralChange(Sender: TObject); override; procedure Startup; procedure Shutdown; procedure BindFormEvents; procedure DoCloseQuery(Sender: TObject; var CanClose: Boolean); procedure DoPaint(Sender: TObject); procedure DoActivate(Sender: TObject); procedure DoDeactivate(Sender: TObject); procedure DoFormDestroy(Sender: TObject); public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Render(baseObject: TGLBaseSceneObject = nil); override; { : Adjusts property so that current resolution will be used.<p> Call this method if you want to make sure video mode isn't switched. } procedure UseCurrentResolution; procedure BeginUpdate; procedure EndUpdate; { : Activates/deactivates full screen mode.<p> } property Active: Boolean read FActive write SetActive; procedure ReActivate; { : Read access to the underlying form handle.<p> Returns 0 (zero) if the viewer is not active or has not yet instantiated its form. } property Handle: HWND read GetHandle; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function LastFrameTime: Single; function FramesPerSecond: Single; function FramesPerSecondText(decimals: Integer = 1): String; procedure ResetPerformanceMonitor; property RenderDC: HWND read FOwnDC; published { Public Declarations } property Form: TForm read FForm write SetForm; property ManualRendering: Boolean read FManualRendering write SetManualRendering; // It is not used in UNIX { : Requested ScreenDepth. } property ScreenDepth: TGLScreenDepth read FScreenDepth write SetScreenDepth default sd32bits; { : Specifies if the underlying form is "fsStayOnTop".<p> The benefit of StayOnTop is that it hides the windows bar and other background windows. The "fsStayOnTop" is automatically switched off/on when the underlying form loses/gains focus.<p> It is recommended not to use StayOnTop while running in the IDE or during the debugging phase.<p> } property StayOnTop: Boolean read FStayOnTop write SetStayOnTop default False; { : Specifies if the refresh should be synchronized with the VSync signal.<p> If the underlying OpenGL ICD does not support the WGL_EXT_swap_control extension, this property is ignored. } property VSync: TVSyncMode read FVSync write FVSync default vsmSync; { : Screen refresh rate.<p> Use zero for system default. This property allows you to work around the winxp bug that limits uses a refresh rate of 60hz when changeing resolution. it is however suggested to give the user the opportunity to adjust it instead of having a fixed value (expecially beyond 75hz or for resolutions beyond 1024x768).<p> the value will be automatically clamped to the highest value *reported* compatible with the monitor. } property RefreshRate: Integer read FRefreshRate write FRefreshRate; property Cursor: TCursor read FCursor write SetCursor default crDefault; property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu; property OnClose: TCloseEvent read FOnClose write SetOnClose; property OnKeyUp: TKeyEvent read FOnKeyUp write SetOnKeyUp; property OnKeyDown: TKeyEvent read FOnKeyDown write SetOnKeyDown; property OnKeyPress: TKeyPressEvent read FOnKeyPress write SetOnKeyPress; property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery write SetOnCloseQuery; property OnClick: TNotifyEvent read FOnClick write SetOnClick; property OnDblClick: TNotifyEvent read FOnDblClick write SetOnDblClick; property OnMouseDown: TMouseEvent read FOnMouseDown write SetOnMouseDown; property OnMouseUp: TMouseEvent read FOnMouseUp write SetOnMouseUp; property OnMouseMove: TMouseMoveEvent read FOnMouseMove write SetOnMouseMove; property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write SetOnMouseWheel; property OnMouseWheelDown: TMouseWheelUpDownEvent read FOnMouseWheelDown write SetOnMouseWheelDown; property OnMouseWheelUp: TMouseWheelUpDownEvent read FOnMouseWheelUp write SetOnMouseWheelUp; end; procedure Register; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses OpenGLTokens, OpenGLAdapter, GLCrossPlatform, GLScreen, GLWin32Context; const cScreenDepthToBPP: array [sd8bits .. sd32bits] of Integer = (8, 16, 24, 32); procedure Register; begin RegisterComponents('GLScene', [TGLFullScreenViewer]); end; // ------------------ // ------------------ TGLFullScreenViewer ------------------ // ------------------ // Create // constructor TGLFullScreenViewer.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 800; Height := 600; FScreenDepth := sd32bits; FVSync := vsmSync; FCursor := crDefault; Buffer.ViewerBeforeRender := DoBeforeRender; end; // Destroy // destructor TGLFullScreenViewer.Destroy; begin Active := False; inherited Destroy; end; // DoBeforeRender // procedure TGLFullScreenViewer.DoBeforeRender(Sender: TObject); begin SetupVSync(VSync); end; // DoBufferChange // procedure TGLFullScreenViewer.DoBufferChange(Sender: TObject); begin if Assigned(FForm) and (not Buffer.Rendering) then begin Buffer.Render; end; end; // DoBufferStructuralChange // procedure TGLFullScreenViewer.DoBufferStructuralChange(Sender: TObject); begin if Active and (FUpdateCount = 0) then ReActivate end; // Render // procedure TGLFullScreenViewer.Render(baseObject: TGLBaseSceneObject = nil); begin Buffer.Render(baseObject); end; // BeginUpdate // procedure TGLFullScreenViewer.BeginUpdate; begin Inc(FUpdateCount); end; // EndUpdate // procedure TGLFullScreenViewer.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then begin if Active then DoBufferStructuralChange(Self) end else if FUpdateCount < 0 then begin FUpdateCount := 0; Assert(False, 'Unbalanced Begin/EndUpdate'); end; end; procedure TGLFullScreenViewer.ReActivate; begin Shutdown; Startup; end; procedure TGLFullScreenViewer.Notification(AComponent: TComponent; Operation: TOperation); begin if (Operation = opRemove) and (Buffer <> nil) then begin if (AComponent = Buffer.Camera) then Buffer.Camera := nil; Active := False; if (AComponent = FForm) then begin Active := False; Form := nil; end; end; inherited Notification(AComponent, Operation); end; function TGLFullScreenViewer.LastFrameTime: Single; begin Result := Buffer.LastFrameTime; end; function TGLFullScreenViewer.FramesPerSecond: Single; begin Result := Buffer.FramesPerSecond; end; function TGLFullScreenViewer.FramesPerSecondText(decimals: Integer): String; begin Result := Format('%.*f FPS', [decimals, Buffer.FramesPerSecond]); end; procedure TGLFullScreenViewer.ResetPerformanceMonitor; begin Buffer.ResetPerformanceMonitor; end; // UseCurrentResolution // procedure TGLFullScreenViewer.UseCurrentResolution; begin BeginUpdate; try Width := Screen.Width; Height := Screen.Height; case GetCurrentColorDepth of 24: ScreenDepth := sd24bits; 16: ScreenDepth := sd16bits; 8: ScreenDepth := sd8bits; else // highest depth possible otherwise ScreenDepth := sd32bits; end; finally EndUpdate; end; end; // SetActive // procedure TGLFullScreenViewer.SetActive(const val: Boolean); begin if val <> FActive then begin // Alt+Tab delayed until better times // {$IFDEF MSWindows} // Application.OnDeactivate:=DoDeActivate; // Application.OnActivate:=DoActivate; // {$ENDIF} if val then Startup else Shutdown; end; end; // Startup // procedure TGLFullScreenViewer.Startup; var res: TResolution; begin if FActive then Exit; if FForm = nil then begin FFormIsOwned := True; FForm := TForm.Create(nil); FForm.Show(); end else FFormIsOwned := False; with FForm do begin If BorderStyle <> bsNone then BorderStyle := bsNone; Cursor := Self.Cursor; PopupMenu := Self.PopupMenu; Left := 0; Top := 0; ClientWidth := Self.Width; ClientHeight := Self.Height; BindFormEvents; res := GetIndexFromResolution(Width, Height, cScreenDepthToBPP[ScreenDepth]); if res = 0 then raise Exception.Create('Unsupported video mode'); if StayOnTop then FormStyle := fsStayOnTop else FormStyle := fsNormal; {$IFDEF MSWINDOWS} SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) and not WS_CAPTION); {$ENDIF} // WindowState:=wsMaximized; // Switch video mode if (Screen.Width <> Width) or (Screen.Height <> Height) or (GetCurrentColorDepth <> cScreenDepthToBPP[ScreenDepth]) then begin SetFullscreenMode(res, FRefreshRate); FSwitchedResolution := True; end; {$IFDEF MSWINDOWS} // Hides Taskbar + Windows 7 Button ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_HIDE); ShowWindow(FindWindow('BUTTON', nil), SW_HIDE); {$ENDIF} // Show; end; Buffer.Resize(0, 0, Width, Height); FOwnDC := GetDC(FForm.Handle); Buffer.CreateRC(FOwnDC, False); // Linux Unicode {$IFDEF Linux} GrabMouseToForm(FForm); {$ENDIF} // todo FActive := True; end; // Shutdown // procedure TGLFullScreenViewer.Shutdown; begin if not FActive then Exit; Assert(FForm <> nil); Buffer.DestroyRC; with FForm do begin Cursor := crDefault; PopupMenu := nil; end; {$IFDEF Linux} ReleaseMouseFromForm(FForm); {$ENDIF} {$IFDEF MSWINDOWS} // Restore Taskbar + Windows 7 Button ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_SHOWNA); ShowWindow(FindWindow('BUTTON', nil), SW_SHOWNA); {$ENDIF} // attempt that, at the very least... if FSwitchedResolution then RestoreDefaultMode; FActive := False; if FFormIsOwned then FreeAndNil(FForm); end; // BindFormEvents // procedure TGLFullScreenViewer.BindFormEvents; begin if Assigned(FForm) then with FForm do begin OnMouseDown := FOnMouseDown; OnMouseUp := FOnMouseUp; OnMouseMove := FOnMouseMove; OnMouseWheel := FOnMouseWheel; OnMouseWheelDown := FOnMouseWheelDown; OnMouseWheelUp := FOnMouseWheelUp; OnClick := FOnClick; OnDblClick := FOnDblClick; OnCloseQuery := DoCloseQuery; OnClose := FOnClose; OnKeyUp := FOnKeyUp; OnKeyDown := FOnKeyDown; OnKeyPress := FOnKeyPress; OnPaint := DoPaint; OnDestroy := DoFormDestroy; end; end; // DoCloseQuery // procedure TGLFullScreenViewer.DoCloseQuery(Sender: TObject; var CanClose: Boolean); begin if Assigned(FOnCloseQuery) then FOnCloseQuery(Sender, CanClose); CanClose := True; // if CanClose then Shutdown; end; // DoPaint // procedure TGLFullScreenViewer.DoPaint(Sender: TObject); begin If not ManualRendering then if Form <> nil then Render; end; procedure TGLFullScreenViewer.DoActivate(Sender: TObject); begin (* If not Active and (Form <> nil) then begin Startup; end; *) end; procedure TGLFullScreenViewer.DoDeactivate(Sender: TObject); begin (* If Active and (Form <> nil) then begin Shutdown; Form.Height:=0; Form.Width:=0; end; *) end; procedure TGLFullScreenViewer.DoFormDestroy(Sender: TObject); begin Active := False; end; // SetScreenDepth // procedure TGLFullScreenViewer.SetScreenDepth(const val: TGLScreenDepth); begin if FScreenDepth <> val then begin FScreenDepth := val; DoBufferStructuralChange(Self); end; end; // SetStayOnTop // procedure TGLFullScreenViewer.SetStayOnTop(const val: Boolean); begin if val <> FStayOnTop then begin FStayOnTop := val; DoBufferStructuralChange(Self); end; end; // SetOnCloseQuery // procedure TGLFullScreenViewer.SetOnCloseQuery(const val: TCloseQueryEvent); begin FOnCloseQuery := val; // this one uses a special binding end; // SetOnClose // procedure TGLFullScreenViewer.SetOnClose(const val: TCloseEvent); begin If Form <> nil then Form.OnClose := val; FOnClose := val; end; // SetOnKeyPress // procedure TGLFullScreenViewer.SetOnKeyPress(const val: TKeyPressEvent); begin If Form <> nil then Form.OnKeyPress := val; FOnKeyPress := val; end; // SetOnKeyUp // procedure TGLFullScreenViewer.SetOnKeyUp(const val: TKeyEvent); begin If Form <> nil then Form.OnKeyUp := val; FOnKeyUp := val; end; // SetOnKeyDown // procedure TGLFullScreenViewer.SetOnKeyDown(const val: TKeyEvent); begin If Form <> nil then Form.OnKeyDown := val; FOnKeyDown := val; end; // SetOnMouseWheel // procedure TGLFullScreenViewer.SetOnMouseWheel(const val: TMouseWheelEvent); begin If Form <> nil then Form.OnMouseWheel := val; FOnMouseWheel := val; end; // SetOnMouseWheelDown // procedure TGLFullScreenViewer.SetOnMouseWheelDown (const val: TMouseWheelUpDownEvent); begin If Form <> nil then Form.OnMouseWheelDown := val; FOnMouseWheelDown := val; end; // SetOnMouseWheelUp // procedure TGLFullScreenViewer.SetOnMouseWheelUp (const val: TMouseWheelUpDownEvent); begin If Form <> nil then Form.OnMouseWheelUp := val; FOnMouseWheelUp := val; end; // SetOnClick // procedure TGLFullScreenViewer.SetOnClick(const val: TNotifyEvent); begin If Form <> nil then Form.OnClick := val; FOnClick := val; end; // SetOnDblClick // procedure TGLFullScreenViewer.SetOnDblClick(const val: TNotifyEvent); begin If Form <> nil then Form.OnDblClick := val; FOnDblClick := val; end; // SetOnMouseMove // procedure TGLFullScreenViewer.SetOnMouseMove(const val: TMouseMoveEvent); begin If Form <> nil then Form.OnMouseMove := val; FOnMouseMove := val; end; // SetOnMouseDown // procedure TGLFullScreenViewer.SetOnMouseDown(const val: TMouseEvent); begin If Form <> nil then Form.OnMouseDown := val; FOnMouseDown := val; end; // SetOnMouseUp // procedure TGLFullScreenViewer.SetOnMouseUp(const val: TMouseEvent); begin If Form <> nil then Form.OnMouseUp := val; FOnMouseUp := val; end; // SetCursor // procedure TGLFullScreenViewer.SetCursor(const val: TCursor); begin if val <> FCursor then begin FCursor := val; if Form <> nil then FForm.Cursor := val; end; end; // SetPopupMenu // procedure TGLFullScreenViewer.SetPopupMenu(const val: TPopupMenu); begin if val <> FPopupMenu then begin FPopupMenu := val; if Assigned(FForm) then FForm.PopupMenu := val; end; end; procedure TGLFullScreenViewer.SetForm(aVal: TForm); begin FForm := aVal; end; procedure TGLFullScreenViewer.SetManualRendering(const val: Boolean); begin if FManualRendering <> val then FManualRendering := val; end; // GetHandle // function TGLFullScreenViewer.GetHandle: HWND; begin if Form <> nil then Result := FForm.Handle else Result := 0; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterClasses([TGLFullScreenViewer]); finalization {$IFDEF MSWINDOWS} // Restore Taskbar + Windows 7 Button ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_SHOWNA); ShowWindow(FindWindow('BUTTON', nil), SW_SHOWNA); {$ENDIF} end.
unit KeyCodes; (* copyright 1991 by Art Steinmetz *) interface uses CRT; CONST { These are valid ASCII codes } ESC = 27; BS = 8; SP = 32; LF = 10; FF = 12; CR = 13; Break = 3; { These are only valid if you use the GetKey procedure below } F1 = 315; F2 = 316; F3 = 317; F4 = 318; F5 = 319; F6 = 320; F7 = 321; F8 = 322; F9 = 323; F10 = 324; F11 = 389; F12 = 390; SF1 = 340; SF2 = 341; SF3 = 342; SF4 = 343; SF5 = 344; SF6 = 345; SF7 = 346; SF8 = 347; SF9 = 348; SF10 = 349; SF11 = 391; SF12 = 392; Home = 327; UpArrow = 328; PgUp = 329; LeftArrow = 331; RightArrow = 333; EndKey = 335; DownArrow = 336; PgDn = 337; Ins = 338; Del = 339; function GetKey : Integer; { This uses Turbo's ReadKey procedure and interpets extended key codes according to the constants defined above } implementation function GetKey : Integer; Var CH : Char; Int : Integer; begin CH := ReadKey; If CH = #0 then begin CH := ReadKey; int := Ord(CH); inc(int,256); {add 256 to the extended code to avoid ascii conflict} end else Int := Ord(CH); GetKey := Int; end; BEGIN END. {KeyCodes} 
{********************************************} { TeeChart Pro PS Canvas and Exporting } { Copyright (c) 2002-2004 by Marjan Slatinek } { and David Berneda } { All Rights Reserved } {********************************************} unit TeePSCanvas; {$I TeeDefs.inc} interface uses {$IFNDEF LINUX} Windows, {$ENDIF} Classes, {$IFDEF CLX} QGraphics, QForms, Types, {$ELSE} Graphics, Forms, {$ENDIF} TeCanvas, TeeProcs, TeeExport, Math; type TEPSCanvas = class(TTeeCanvas3D) private { Private declarations } tmpStr: String; FStrings : TStrings; FBackColor : TColor; FBackMode : TCanvasBackMode; FTextAlign : TCanvasTextAlign; IWidth, IHeight: Integer; FX, FY: Integer; Procedure Add(Const S:String); Function BrushProperties(Brush: TBrush): String; Procedure InternalRect(Const Rect:TRect; UsePen,IsRound:Boolean); Procedure InternalArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer; Pie: Boolean); Function PenProperties(Pen: TPen): String; Function PointToStr(X,Y:Integer):String; Function SetPenStyle(PenStyle: TPenStyle): String; Function TextToPSText(AText:String): String; Function TheBounds:String; Procedure TranslateVertCoord(var Y: Integer); protected { Protected declarations } Procedure PolygonFour; override; { 2d } procedure SetPixel(X, Y: Integer; Value: TColor); override; Function GetTextAlign:TCanvasTextAlign; override; { 3d } procedure SetPixel3D(X,Y,Z:Integer; Value: TColor); override; Procedure SetBackMode(Mode:TCanvasBackMode); override; Function GetMonochrome:Boolean; override; Procedure SetMonochrome(Value:Boolean); override; Procedure SetBackColor(Color:TColor); override; Function GetBackMode:TCanvasBackMode; override; Function GetBackColor:TColor; override; procedure SetTextAlign(Align:TCanvasTextAlign); override; public { Public declarations } Constructor Create(AStrings:TStrings); Function InitWindow( DestCanvas:TCanvas; A3DOptions:TView3DOptions; ABackColor:TColor; Is3D:Boolean; Const UserRect:TRect):TRect; override; procedure Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override; procedure Draw(X, Y: Integer; Graphic: TGraphic); override; procedure FillRect(const Rect: TRect); override; procedure Ellipse(X1, Y1, X2, Y2: Integer); override; procedure LineTo(X,Y:Integer); override; procedure MoveTo(X,Y:Integer); override; procedure Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); override; procedure Rectangle(X0,Y0,X1,Y1:Integer); override; procedure RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); override; procedure StretchDraw(const Rect: TRect; Graphic: TGraphic); override; Procedure TextOut(X,Y:Integer; const Text:String); override; Procedure DoHorizLine(X0,X1,Y:Integer); override; Procedure DoVertLine(X,Y0,Y1:Integer); override; procedure ClipRectangle(Const Rect:TRect); override; procedure ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); override; procedure UnClipRectangle; override; Procedure GradientFill( Const Rect:TRect; StartColor,EndColor:TColor; Direction:TGradientDirection; Balance:Integer=50); override; procedure RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); override; procedure RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double); override; Procedure Line(X0,Y0,X1,Y1:Integer); override; Procedure Polygon(const Points: array of TPoint); override; { 3d } Procedure ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); override; procedure EllipseWithZ(X1, Y1, X2, Y2, Z:Integer); override; Procedure HorizLine3D(Left,Right,Y,Z:Integer); override; procedure LineTo3D(X,Y,Z:Integer); override; Procedure LineWithZ(X0,Y0,X1,Y1,Z:Integer); override; procedure MoveTo3D(X,Y,Z:Integer); override; Procedure TextOut3D(X,Y,Z:Integer; const Text:String); override; Procedure VertLine3D(X,Top,Bottom,Z:Integer); override; Procedure ZLine3D(X,Y,Z0,Z1:Integer); override; end; TEPSExportFormat=class(TTeeExportFormat) private protected Procedure DoCopyToClipboard; override; public function Description:String; override; function FileExtension:String; override; function FileFilter:String; override; Function EPSList:TStringList; Function Options(Check:Boolean=True):TForm; override; Procedure SaveToStream(Stream:TStream); override; end; procedure TeeSaveToPSFile( APanel:TCustomTeePanel; const FileName: WideString; AWidth:Integer=0; AHeight: Integer=0); implementation Uses {$IFDEF CLX} QClipbrd, {$ELSE} Clipbrd, {$ENDIF} TeeConst, SysUtils; { Convert , to . } procedure FixSeparator(var St: String); begin while Pos(',', St) > 0 do St[Pos(',', St)] := '.'; end; procedure StringToPSString(var St: String); begin end; Function PSColor(AColor:TColor):String; begin AColor:=ColorToRGB(AColor); Result:= FormatFloat('0.00',GetRVAlue(AColor)/255) + ' ' + FormatFloat('0.00',GetGVAlue(AColor)/255) + ' ' + FormatFloat('0.00',GetBVAlue(AColor)/255) + ' rgb'; FixSeparator(Result); end; { TPSCanvas } Constructor TEPSCanvas.Create(AStrings:TStrings); begin inherited Create; FBackMode := cbmTransparent; FStrings:=AStrings; UseBuffer:=False; end; Procedure TEPSCanvas.ShowImage(DestCanvas,DefaultCanvas:TCanvas; Const UserRect:TRect); begin Add('gr'); end; Procedure TEPSCanvas.Add(Const S:String); begin FStrings.Add(S); end; procedure TEPSCanvas.Rectangle(X0,Y0,X1,Y1:Integer); begin InternalRect(TeeRect(X0,Y0,X1,Y1),True,False); end; procedure TEPSCanvas.MoveTo(X, Y: Integer); begin FX := X; FY := Y; end; procedure TEPSCanvas.LineTo(X, Y: Integer); begin tmpStr := 'gs ' + PenProperties(Pen) + ' ' + PointToStr(FX,FY)+' m '+ PointToStr(X,Y)+' l st gr '; Add(tmpStr); FX := X; FY := Y; end; procedure TEPSCanvas.ClipRectangle(Const Rect:TRect); var tmpB: Integer; begin tmpB := Rect.Bottom; TranslateVertCoord(tmpB); tmpStr :='clipsave ' + IntToStr(Rect.Left) + ' ' + IntToStr(tmpB) + ' ' + IntToStr(Rect.Right - Rect.Left) + ' ' + IntToStr(Rect.Bottom - Rect.Top) + ' rectclip'; Add(tmpStr); end; procedure TEPSCanvas.ClipCube(Const Rect:TRect; MinZ,MaxZ:Integer); begin { Not implemented } end; procedure TEPSCanvas.UnClipRectangle; begin Add('cliprestore'); end; function TEPSCanvas.GetBackColor:TColor; begin result:=FBackColor; end; procedure TEPSCanvas.SetBackColor(Color:TColor); begin FBackColor:=Color; end; procedure TEPSCanvas.SetBackMode(Mode:TCanvasBackMode); begin FBackMode:=Mode; end; Function TEPSCanvas.GetMonochrome:Boolean; begin result:=False; end; Procedure TEPSCanvas.SetMonochrome(Value:Boolean); begin { Not implemented } end; procedure TEPSCanvas.StretchDraw(const Rect: TRect; Graphic: TGraphic); begin { Not implemented } end; procedure TEPSCanvas.Draw(X, Y: Integer; Graphic: TGraphic); begin { Not implemented } end; Function TEPSCanvas.TheBounds:String; begin IWidth := Bounds.Right - Bounds.Left; IHeight := Bounds.Bottom - Bounds.Top; Result:='%%BoundingBox: 0 0 ' + IntToStr(IWidth) + ' ' + IntToStr(IHeight); end; Function TEPSCanvas.PointToStr(X,Y:Integer):String; begin TranslateVertCoord(Y); result:=IntToStr(X)+' '+IntToStr(Y); end; Procedure TEPSCanvas.GradientFill( Const Rect:TRect; StartColor,EndColor:TColor; Direction:TGradientDirection; Balance:Integer=50); begin { Not implemented } end; procedure TEPSCanvas.FillRect(const Rect: TRect); begin InternalRect(Rect,False,False); end; Procedure TEPSCanvas.InternalRect(Const Rect:TRect; UsePen, IsRound:Boolean); var tmpB: Integer; begin if (Brush.Style<>bsClear) or (UsePen and (Pen.Style<>psClear)) then begin tmpB := Rect.Bottom; TranslateVertCoord(tmpB); if Brush.Style<>bsClear then begin tmpStr := 'gs '+ PsColor(Brush.Color); tmpStr := tmpStr + ' ' +IntToStr(Rect.Left) + ' ' + IntToStr(tmpB) + ' ' + IntToStr(Rect.Right - Rect.Left) + ' ' + IntToStr(Rect.Bottom - Rect.Top) + ' rectfill gr'; Add(tmpStr); end; if UsePen and (Pen.Style<>psClear) then begin tmpStr := 'gs '+ PenProperties(Pen); tmpStr := tmpStr + ' ' + IntToStr(Rect.Left) + ' ' + IntToStr(tmpB) + ' ' + IntToStr(Rect.Right - Rect.Left) + ' ' + IntToStr(Rect.Bottom - Rect.Top) + ' rectstroke gr'; Add(tmpStr); end; end; end; procedure TEPSCanvas.Ellipse(X1, Y1, X2, Y2: Integer); begin EllipseWithZ(X1,Y1,X2,Y2,0); end; procedure TEPSCanvas.EllipseWithZ(X1, Y1, X2, Y2, Z: Integer); var CenterX, CenterY: Integer; Ra,Rb: String; procedure DrawEllipse; begin Add(IntToStr(CenterX) + ' '+IntToStr(CenterY) + ' ' + Ra + ' ' + Rb + ' 0 360 ellipse') ; end; begin if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then begin Calc3DPos(X1,Y1,Z); Calc3DPos(X2,Y2,Z); CenterX := (X1 + X2) div 2; CenterY := (Y1 + Y2) div 2; TranslateVertCoord(CenterY); { radius } Ra := FormatFloat('0.00',(X2-X1)*0.5); FixSeparator(Ra); Rb := FormatFloat('0.00',(Y2-Y1)*0.5); FixSeparator(Rb); if (Brush.Style<>bsClear) then begin Add('gs ' + BrushProperties(Brush)); DrawEllipse; Add('fi gr'); end; if (Pen.Style<>psClear) then begin Add('gs ' + PenProperties(Pen)); DrawEllipse; Add('st gr'); end; end; end; procedure TEPSCanvas.SetPixel3D(X,Y,Z:Integer; Value: TColor); begin if Pen.Style<>psClear then begin Calc3DPos(x,y,z); Pen.Color:=Value; MoveTo(x,y); LineTo(x,y); end; end; procedure TEPSCanvas.SetPixel(X, Y: Integer; Value: TColor); begin if Pen.Style<>psClear then begin Pen.Color:=Value; MoveTo(x,y); LineTo(x,y); end; end; procedure TEPSCanvas.Arc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); begin InternalArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4, False); end; procedure TEPSCanvas.Pie(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer); begin InternalArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4, True); end; procedure TEPSCanvas.RoundRect(X1, Y1, X2, Y2, X3, Y3: Integer); begin InternalRect(TeeRect(X1,Y1,X2,Y2),True,True); end; Procedure TEPSCanvas.TextOut3D(X,Y,Z:Integer; const Text:String); Function FontSize:String; begin result:=IntToStr(Font.Size); end; Procedure DoText(AX,AY:Integer); begin Inc(AY,TextHeight(Text) div 2); tmpStr := PsColor(Font.Color) + ' /' + Font.Name + ' findfont ' + FontSize + ' scalefont setfont'; Add(tmpStr); Add(PointToStR(AX,AY) + ' m'); if (TextAlign and TA_CENTER)=TA_CENTER then Add('(' + TextToPSText(Text) + ') ctext') else if (TextAlign and TA_RIGHT)=TA_RIGHT then Add('(' + TextToPSText(Text) + ') rtext') else Add('(' + TextToPSText(Text) + ') ltext') end; Var tmpX : Integer; tmpY : Integer; begin Calc3DPos(x,y,z); if Assigned(IFont) then With IFont.Shadow do if (HorizSize<>0) or (VertSize<>0) then begin if HorizSize<0 then begin tmpX:=X; X:=X-HorizSize; end else tmpX:=X+HorizSize; if VertSize<0 then begin tmpY:=Y; Y:=Y-VertSize; end else tmpY:=Y+VertSize; DoText(tmpX,tmpY) end; DoText(X,Y); end; Procedure TEPSCanvas.TextOut(X,Y:Integer; const Text:String); begin TextOut3D(x,y,0,Text); end; procedure TEPSCanvas.MoveTo3D(X,Y,Z:Integer); begin Calc3DPos(x,y,z); MoveTo(x,y); end; procedure TEPSCanvas.LineTo3D(X,Y,Z:Integer); begin Calc3DPos(x,y,z); LineTo(x,y); end; Function TEPSCanvas.GetTextAlign:TCanvasTextAlign; begin result:=FTextAlign; end; Procedure TEPSCanvas.DoHorizLine(X0,X1,Y:Integer); begin MoveTo(X0,Y); LineTo(X1,Y); end; Procedure TEPSCanvas.DoVertLine(X,Y0,Y1:Integer); begin MoveTo(X,Y0); LineTo(X,Y1); end; procedure TEPSCanvas.RotateLabel3D(x,y,z:Integer; Const St:String; RotDegree:Double); begin Calc3DPos(x,y,z); Add('gs '+PointToStr(x,y) + ' tr ' + IntToStr(Round(RotDegree))+ ' rot'); TextOut(0,Self.Bounds.Bottom,St); Add('gr'); end; procedure TEPSCanvas.RotateLabel(x,y:Integer; Const St:String; RotDegree:Double); begin RotateLabel3D(x,y,0,St,RotDegree); end; Procedure TEPSCanvas.Line(X0,Y0,X1,Y1:Integer); begin MoveTo(X0,Y0); LineTo(X1,Y1); end; Procedure TEPSCanvas.HorizLine3D(Left,Right,Y,Z:Integer); begin MoveTo3D(Left,Y,Z); LineTo3D(Right,Y,Z); end; Procedure TEPSCanvas.VertLine3D(X,Top,Bottom,Z:Integer); begin MoveTo3D(X,Top,Z); LineTo3D(X,Bottom,Z); end; Procedure TEPSCanvas.ZLine3D(X,Y,Z0,Z1:Integer); begin MoveTo3D(X,Y,Z0); LineTo3D(X,Y,Z1); end; Procedure TEPSCanvas.LineWithZ(X0,Y0,X1,Y1,Z:Integer); begin MoveTo3D(X0,Y0,Z); LineTo3D(X1,Y1,Z); end; Function TEPSCanvas.GetBackMode:TCanvasBackMode; begin result:=FBackMode; end; Procedure TEPSCanvas.PolygonFour; begin Polygon(IPoints); end; Procedure TEPSCanvas.Polygon(const Points: Array of TPoint); Procedure AddPoly; var t : Integer; begin Add('np '+ PointToStr(Points[0].X,Points[0].Y)+' m'); for t:=1 to High(Points) do Add(PointToStr(Points[t].X,Points[t].Y)+' l'); Add('cp'); end; begin if (Brush.Style<>bsClear) or (Pen.Style<>psClear) then begin if (Brush.Style<>bsClear) then begin Add('gs ' +BrushProperties(Brush)); AddPoly; Add('fi gr'); end; if (Pen.Style<>psClear) then begin tmpStr :='gs '+ PenProperties(Pen); Add(tmpStr); AddPoly; Add('st gr'); end; end; end; function TEPSCanvas.InitWindow(DestCanvas: TCanvas; A3DOptions: TView3DOptions; ABackColor: TColor; Is3D: Boolean; const UserRect: TRect): TRect; begin result:=inherited InitWindow(DestCanvas,A3DOptions,ABackColor,Is3D,UserRect); Add('%!PS-Adobe-3.0 EPSF-3.0'); Add(TheBounds); { bounding box } Add('%%Creator: '+TeeMsg_Version); Add('%%LanguageLevel: 1'); Add('%%EndComments'); Add('/bd{bind def} bind def /ld{load def}bd /ed{exch def}bd /xd{cvx def}bd'); Add('/np/newpath ld /cp/closepath ld /m/moveto ld /l/lineto ld /rm/rmoveto ld' + '/rl/rlineto ld'); Add('/rot/rotate ld /sc/scale ld /tr/translate ld'); Add('/cpt/currentpoint ld'); Add('/sw/setlinewidth ld /sd/setdash ld /rgb/setrgbcolor ld'); Add('/gs/gsave ld /gr/grestore ld'); Add('/st/stroke ld /fi/fill ld /s/show ld'); Add('/ltext{cpt st m s}def '); Add('/rtext{cpt st m dup stringwidth pop neg 0 rm s} def'); Add('/ctext{cpt st m dup stringwidth pop -2 div 0 rm s} def'); Add('/ellipsedict 8 dict def'); Add('ellipsedict /mtrx matrix put'); Add('/ellipse'); Add('{ ellipsedict begin'); Add(' np'); Add(' /endangle exch def'); Add(' /startangle exch def'); Add(' /yrad exch def'); Add(' /xrad exch def'); Add(' /y exch def'); Add(' /x exch def'); Add(' /savematrix mtrx currentmatrix def'); Add(' x y tr xrad yrad sc'); Add(' 0 0 1 startangle endangle arc'); Add(' savematrix setmatrix'); Add(' end'); Add('} def'); Add('/piedict 8 dict def'); Add('piedict /mtrx matrix put'); Add('/pie'); Add('{ piedict begin'); Add(' np'); Add(' /endangle exch def'); Add(' /startangle exch def'); Add(' /yrad exch def'); Add(' /xrad exch def'); Add(' /y exch def'); Add(' /x exch def'); Add(' /savematrix mtrx currentmatrix def'); Add(' x y tr xrad yrad sc'); Add(' newpath'); Add(' 0 0 m'); Add(' 0 0 1 startangle endangle arc'); Add(' closepath'); Add(' savematrix setmatrix'); Add(' end'); Add('} def'); Add('%%EndProlog'); Add('gs'); Add('np'); end; procedure TEPSCanvas.SetTextAlign(Align: TCanvasTextAlign); begin FTextAlign:=Align; end; { TVMLExportFormat } function TEPSExportFormat.Description: String; begin result:=TeeMsg_AsPS; end; procedure TEPSExportFormat.DoCopyToClipboard; begin with EPsList do try Clipboard.AsText:=Text; finally Free; end; end; function TEPSExportFormat.FileExtension: String; begin result:='eps'; end; function TEPSExportFormat.FileFilter: String; begin result:=TeeMsg_PSFilter; end; function TEPSExportFormat.Options(Check:Boolean): TForm; begin result:=nil; end; procedure TEPSExportFormat.SaveToStream(Stream: TStream); begin with EPSList do try SaveToStream(Stream); finally Free; end; end; type TTeePanelAccess=class(TCustomTeePanel); function TEPSExportFormat.EPSList: TStringList; var tmp : TCanvas3D; begin { return a panel or chart in PS format into a StringList } CheckSize; result:=TStringList.Create; Panel.AutoRepaint:=False; try {$IFNDEF CLR} // Protected across assemblies tmp:=TTeePanelAccess(Panel).InternalCanvas; TTeePanelAccess(Panel).InternalCanvas:=nil; {$ENDIF} Panel.Canvas:=TEPSCanvas.Create(Result); try Panel.Draw(Panel.Canvas.ReferenceCanvas,TeeRect(0,0,Width,Height)); finally Panel.Canvas:=tmp; end; finally Panel.AutoRepaint:=True; end; end; procedure TeeSaveToPSFile( APanel:TCustomTeePanel; const FileName: WideString; AWidth:Integer=0; AHeight: Integer=0); begin { save panel or chart to filename in EPS (PostScript) format } with TEPSExportFormat.Create do try Panel:=APanel; Height:=AHeight; Width:=AWidth; SaveToFile(FileName); finally Free; end; end; procedure TEPSCanvas.TranslateVertCoord(var Y: Integer); begin { vertical coordinate is reversed in PS !! } Y := (Self.Bounds.Bottom - Self.Bounds.Top) - Y; end; function TEPSCanvas.SetPenStyle(PenStyle: TPenStyle): String; begin case PenStyle of psSolid : Result := '[] 0 sd'; psDash : Result := '[3] 0 sd'; psDot : Result := '[2] 1 sd'; { psDashDot : Result := psDashDotDot : Result := } else Result := ''; end; end; procedure TEPSCanvas.InternalArc(X1, Y1, X2, Y2, X3, Y3, X4, Y4: Integer; Pie: Boolean); var CenterX, CenterY: Integer; StartAngle, EndAngle: String; Ra,Rb: String; procedure DrawPie; begin Add(IntToStr(CenterX) + ' '+IntToStr(CenterY) + ' ' + Ra + ' ' + Rb + ' '+StartAngle+' ' + EndAngle+' pie') ; end; procedure DrawArc; begin Add(IntToStr(CenterX) + ' '+IntToStr(CenterY) + ' ' + Ra + ' ' + Rb + ' '+StartAngle+' ' + EndAngle+' ellipse') ; end; var Theta: double; const HalfDivPi = 57.29577951; begin if ((Brush.Style<>bsClear) or (Pen.Style<>psClear)) then begin CenterX := (X1 + X2) div 2; CenterY := (Y1 + Y2) div 2; { StartAngle } Theta := Math.ArcTan2(CenterY-Y3, X3 - CenterX); if Theta<0 then Theta:=2.0*Pi+Theta; Theta := Theta*HalfDivPi; StartAngle := FloatToStr(Theta); FixSeparator(StartAngle); { EndAngle } Theta := Math.ArcTan2(CenterY-Y4, X4 - CenterX); if Theta<0 then Theta:=2.0*Pi+Theta; Theta := Theta*HalfDivPi; if Theta=0 then Theta:=361; EndAngle := FloatToStr(Theta); FixSeparator(EndAngle); TranslateVertCoord(CenterY); { radius } Ra := FormatFloat('0.00',(X2-X1)*0.5); FixSeparator(Ra); Rb := FormatFloat('0.00',(Y2-Y1)*0.5); FixSeparator(Rb); If Pie then begin if (Brush.Style<>bsClear) then begin Add('gs ' + BrushProperties(Brush)); DrawPie; Add('fi gr'); end; if (Pen.Style<>psClear) then begin Add('gs ' + PenProperties(Pen)); DrawPie; Add('st gr'); end; end else if (Pen.Style<>psClear) then begin Add('gs ' + PenProperties(Pen)); DrawArc; Add('st gr'); end; end; end; function TEPSCanvas.PenProperties(Pen: TPen): String; begin tmpStr := PSColor(Pen.Color) + ' ' + SetPenStyle(Pen.Style) + ' ' + IntToStr(Pen.Width)+' sw'; Result := tmpStr; end; function TEPSCanvas.BrushProperties(Brush: TBrush): String; begin tmpStr := PsColor(Brush.Color); Result := tmpStr; end; function TEPSCanvas.TextToPSText(AText: String): String; begin AText := StringReplace(AText,'\','\\',[rfReplaceAll,rfIgnoreCase]); AText := StringReplace(AText,'(','\(',[rfReplaceAll,rfIgnoreCase]); AText := StringReplace(AText,')','\)',[rfReplaceAll,rfIgnoreCase]); Result := AText; end; initialization RegisterTeeExportFormat(TEPSExportFormat); finalization UnRegisterTeeExportFormat(TEPSExportFormat); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TfrmTestResults } TfrmTestResults = class(TForm) btnSummary: TButton; edtTotal: TEdit; gpbSummary: TGroupBox; lblPassed: TLabel; lblAverage: TLabel; lblHighest: TLabel; lblMarks: TLabel; lblTotal: TLabel; memMarks: TMemo; procedure btnSummaryClick(Sender: TObject); private { private declarations } public { public declarations } end; var frmTestResults: TfrmTestResults; implementation {$R *.lfm} { TfrmTestResults } procedure TfrmTestResults.btnSummaryClick(Sender: TObject); var Percentages: array of double; I, NoOfMarks, TestTotal, NumPassed: integer; Sum, Highest, Average: double; begin //set the length of the array based on the number of marks entered NoOfMarks:=memMarks.Lines.Count; setLength(Percentages, NoOfMarks); //store the marks in array as % TestTotal:=StrToInt(edtTotal.Text); for I:=0 to NoOfMarks-1 do Percentages[I]:=StrToInt(memMarks.Lines[I]) / TestTotal * 100; //for ak of the marks, calculate the total and keep track of the highest mark Sum:=0; Highest:=0; NumPassed:=0; for I:=0 to NoOfMarks-1 do begin Sum:=Sum+Percentages[I]; if (Percentages[I] > Highest) then Highest:=Percentages[I]; if (Percentages[I] >= 50) then NumPassed:=NumPassed+1; end; //calculate the average and display the summary Average:=Sum / NoOfMarks; lblHighest.Caption:='Highest percentage: ' + FloatToStrF(Highest, ffFixed, 12, 0) + '%'; lblAverage.Caption:='Average percentage: ' + FloatToStrF(Average, ffFixed, 12, 0) + '%'; lblPassed.Caption:='Number passed: ' + IntToStr(NumPassed); end; end.
unit Ths.Erp.Database.Table.AyarPrsYabanciDilSeviyesi; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table; type TAyarPrsYabanciDilSeviyesi = class(TTable) private FYabanciDilSeviyesi: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override; procedure Update(pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property YabanciDilSeviyesi: TFieldDB read FYabanciDilSeviyesi write FYabanciDilSeviyesi; end; implementation uses Ths.Erp.Constants, Ths.Erp.Database.Singleton; constructor TAyarPrsYabanciDilSeviyesi.Create(OwnerDatabase:TDatabase); begin TableName := 'ayar_prs_yabanci_dil_seviyesi'; SourceCode := '1000'; inherited Create(OwnerDatabase); FYabanciDilSeviyesi := TFieldDB.Create('yabanci_dil_seviyesi', ftString, ''); end; procedure TAyarPrsYabanciDilSeviyesi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, getRawDataByLang(TableName, FYabanciDilSeviyesi.FieldName) ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID'; Self.DataSource.DataSet.FindField(FYabanciDilSeviyesi.FieldName).DisplayLabel := 'Yabancı Dil Seviyesi'; end; end; end; procedure TAyarPrsYabanciDilSeviyesi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + Self.Id.FieldName, getRawDataByLang(TableName, FYabanciDilSeviyesi.FieldName) ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value); FYabanciDilSeviyesi.Value := FormatedVariantVal(FieldByName(FYabanciDilSeviyesi.FieldName).DataType, FieldByName(FYabanciDilSeviyesi.FieldName).Value); List.Add(Self.Clone()); Next; end; Close; end; end; end; procedure TAyarPrsYabanciDilSeviyesi.Insert(out pID: Integer; pPermissionControl: Boolean=True); begin if IsAuthorized(ptAddRecord, pPermissionControl) then begin {$IFDEF CRUD_MODE_SP} SpInsert.ExecProc; pID := SpInsert.ParamByName('result').AsInteger; Self.Notify; {$ELSE IFDEF CRUD_MODE_PURE_SQL} with QueryOfInsert do begin Close; SQL.Clear; SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [ FYabanciDilSeviyesi.FieldName ]); NewParamForQuery(QueryOfInsert, FYabanciDilSeviyesi); Open; if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then pID := Fields.FieldByName(Self.Id.FieldName).AsInteger else pID := 0; EmptyDataSet; Close; end; Self.Notify; {$ENDIF} end; end; procedure TAyarPrsYabanciDilSeviyesi.Update(pPermissionControl: Boolean=True); begin if IsAuthorized(ptUpdate, pPermissionControl) then begin {$IFDEF CRUD_MODE_SP} SpUpdate.ExecProc; Self.Notify; {$ELSE IFDEF CRUD_MODE_PURE_SQL} with QueryOfUpdate do begin Close; SQL.Clear; SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [ FYabanciDilSeviyesi.FieldName ]); NewParamForQuery(QueryOfUpdate, FYabanciDilSeviyesi); NewParamForQuery(QueryOfUpdate, Id); ExecSQL; Close; end; Self.Notify; {$ENDIF} end; end; function TAyarPrsYabanciDilSeviyesi.Clone():TTable; begin Result := TAyarPrsYabanciDilSeviyesi.Create(Database); Self.Id.Clone(TAyarPrsYabanciDilSeviyesi(Result).Id); FYabanciDilSeviyesi.Clone(TAyarPrsYabanciDilSeviyesi(Result).FYabanciDilSeviyesi); end; end.
unit XMLBuilderWriter; interface uses SysUtils, Variants, Classes, WebAdapt, WebComp, DBAdapt, XMLDoc, XMLIntf, Contnrs, XMLBuilderComp; type TXMLWriter = class(TInterfacedObject, IXMLWriter) private FXMLDocument: IXMLDocument; FXMLNode: IXMLNode; FList: TStack; protected { IXMLWriter } procedure PushNode; procedure PopNode; procedure AddNode(const AName: WideString); procedure WritePropertyValue(AName: WideString; AValue: Variant); function GetXMLDocument: IXMLDocument; public property XMLDocument: IXMLDocument read GetXMLDocument; constructor Create; destructor Destroy; override; end; implementation uses SiteComp, WebAuto, AutoAdap, ActiveX, msxmldom; { TXMLWriter } constructor TXMLWriter.Create; var Temp: TXMLDocument; begin Temp := TXMLDocument.Create(nil); FXMLDocument := Temp; FXMLDocument.Active := True; FXMLNode := FXMLDocument.GetDocumentElement; FList := TStack.Create; inherited; end; destructor TXMLWriter.Destroy; begin while FList.Count > 0 do PopNode; FList.Free; inherited; end; procedure TXMLWriter.WritePropertyValue(AName: WideString; AValue: Variant); begin if not VarIsClear(AValue) then FXMLNode.Attributes[AName] := AValue else FXMLNode.Attributes[AName] := WideString(''); end; procedure TXMLWriter.PopNode; begin FXMLNode := IXMLNode(FList.Pop); if FXMLNode <> nil then FXMLNode._Release; end; procedure TXMLWriter.PushNode; begin if FXMLNode <> nil then FXMLNode._AddRef; FList.Push(Pointer(FXMLNode)); end; procedure TXMLWriter.AddNode(const AName: WideString); begin if FXMLNode = nil then FXMLNode := FXMLDocument.AddChild(AName, WideString('')) else FXMLNode := FXMLNode.AddChild(AName); end; function TXMLWriter.GetXMLDocument: IXMLDocument; begin Result := FXMLDocument; end; end.
unit DragDropFormats; // ----------------------------------------------------------------------------- // Project: Drag and Drop Component Suite. // Module: DragDropFormats // Description: Implements commonly used clipboard formats and base classes. // Version: 4.0 // Date: 18-MAY-2001 // Target: Win32, Delphi 5-6 // Authors: Anders Melander, anders@melander.dk, http://www.melander.dk // Copyright © 1997-2001 Angus Johnson & Anders Melander // ----------------------------------------------------------------------------- interface uses DragDrop, Windows, Classes, ActiveX, ShlObj; {$include DragDrop.inc} type //////////////////////////////////////////////////////////////////////////////// // // TStreamList // //////////////////////////////////////////////////////////////////////////////// // Utility class used by TFileContentsStreamClipboardFormat and // TDataStreamDataFormat. //////////////////////////////////////////////////////////////////////////////// TStreamList = class(TObject) private FStreams : TStrings; FOnChanging : TNotifyEvent; protected function GetStream(Index: integer): TStream; function GetCount: integer; procedure Changing; public constructor Create; destructor Destroy; override; function Add(Stream: TStream): integer; function AddNamed(Stream: TStream; Name: string): integer; procedure Delete(Index: integer); procedure Clear; procedure Assign(Value: TStreamList); property Count: integer read GetCount; property Streams[Index: integer]: TStream read GetStream; default; property Names: TStrings read FStreams; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; end; //////////////////////////////////////////////////////////////////////////////// // // TInterfaceList // //////////////////////////////////////////////////////////////////////////////// // List of named interfaces. // Note: Delphi 5 also implements a TInterfaceList, but it can not be used // because it doesn't support change notification and isn't extensible. //////////////////////////////////////////////////////////////////////////////// // Utility class used by TFileContentsStorageClipboardFormat. //////////////////////////////////////////////////////////////////////////////// TInterfaceList = class(TObject) private FList : TStrings; FOnChanging : TNotifyEvent; protected function GetCount: integer; function GetName(Index: integer): string; function GetItem(Index: integer): IUnknown; procedure Changing; public constructor Create; destructor Destroy; override; function Add(Item: IUnknown): integer; function AddNamed(Item: IUnknown; Name: string): integer; procedure Delete(Index: integer); procedure Clear; procedure Assign(Value: TInterfaceList); property Items[Index: integer]: IUnknown read GetItem; default; property Names[Index: integer]: string read GetName; property Count: integer read GetCount; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; end; //////////////////////////////////////////////////////////////////////////////// // // TStorageInterfaceList // //////////////////////////////////////////////////////////////////////////////// // List of IStorage interfaces. // Used by TFileContentsStorageClipboardFormat. //////////////////////////////////////////////////////////////////////////////// TStorageInterfaceList = class(TInterfaceList) private protected function GetStorage(Index: integer): IStorage; public property Storages[Index: integer]: IStorage read GetStorage; default; end; //////////////////////////////////////////////////////////////////////////////// // // TFixedStreamAdapter // //////////////////////////////////////////////////////////////////////////////// // TFixedStreamAdapter fixes several serious bugs in TStreamAdapter.CopyTo. //////////////////////////////////////////////////////////////////////////////// TFixedStreamAdapter = class(TStreamAdapter, IStream) public function CopyTo(stm: IStream; cb: Largeint; out cbRead: Largeint; out cbWritten: Largeint): HResult; override; stdcall; end; //////////////////////////////////////////////////////////////////////////////// // // TMemoryList // //////////////////////////////////////////////////////////////////////////////// // List which owns the memory blocks it points to. //////////////////////////////////////////////////////////////////////////////// TMemoryList = class(TObject) private FList: TList; protected function Get(Index: Integer): Pointer; function GetCount: Integer; public constructor Create; destructor Destroy; override; function Add(Item: Pointer): Integer; procedure Clear; procedure Delete(Index: Integer); property Count: Integer read GetCount; property Items[Index: Integer]: Pointer read Get; default; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomSimpleClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Abstract base class for simple clipboard formats stored in global memory // or a stream. //////////////////////////////////////////////////////////////////////////////// // // Two different methods of data transfer from the medium to the object are // supported: // // 1) Descendant class reads data from a buffer provided by the base class. // // 2) Base class reads data from a buffer provided by the descendant class. // // Method #1 only requires that the descedant class implements the ReadData. // // Method #2 requires that the descedant class overrides the default // DoGetDataSized method. The descedant DoGetDataSized method should allocate a // buffer of the specified size and then call the ReadDataInto method to // transfer data to the buffer. Even though the ReadData method will not be used // in this scenario, it should be implemented as an empty method (to avoid // abstract warnings). // // The WriteData method must be implemented regardless of which of the two // approaches the class implements. // //////////////////////////////////////////////////////////////////////////////// TCustomSimpleClipboardFormat = class(TClipboardFormat) private protected function DoGetData(ADataObject: IDataObject; const AMedium: TStgMedium): boolean; override; //: Transfer data from medium to a buffer of the specified size. function DoGetDataSized(ADataObject: IDataObject; const AMedium: TStgMedium; Size: integer): boolean; virtual; //: Transfer data from the specified buffer to the objects storage. function ReadData(Value: pointer; Size: integer): boolean; virtual; abstract; //: Transfer data from the medium to the specified buffer. function ReadDataInto(ADataObject: IDataObject; const AMedium: TStgMedium; Buffer: pointer; Size: integer): boolean; virtual; function DoSetData(const FormatEtcIn: TFormatEtc; var AMedium: TStgMedium): boolean; override; //: Transfer data from the objects storage to the specified buffer. function WriteData(Value: pointer; Size: integer): boolean; virtual; abstract; function GetSize: integer; virtual; abstract; public constructor Create; override; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomStringClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Abstract base class for simple clipboard formats. // The data is stored in a string. //////////////////////////////////////////////////////////////////////////////// TCustomStringClipboardFormat = class(TCustomSimpleClipboardFormat) private FData: string; FTrimZeroes: boolean; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; function GetString: string; procedure SetString(const Value: string); property Data: string read FData write FData; // DONE : Why is SetString used instead of FData? public procedure Clear; override; function HasData: boolean; override; property TrimZeroes: boolean read FTrimZeroes write FTrimZeroes; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomStringListClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Abstract base class for simple cr/lf delimited string clipboard formats. // The data is stored in a TStringList. //////////////////////////////////////////////////////////////////////////////// TCustomStringListClipboardFormat = class(TCustomSimpleClipboardFormat) private FLines : TStrings; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; function GetLines: TStrings; property Lines: TStrings read FLines; public constructor Create; override; destructor Destroy; override; procedure Clear; override; function HasData: boolean; override; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Abstract base class for simple text based clipboard formats. //////////////////////////////////////////////////////////////////////////////// TCustomTextClipboardFormat = class(TCustomStringClipboardFormat) private protected function GetSize: integer; override; property Text: string read GetString write SetString; public constructor Create; override; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomWideTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Abstract base class for simple wide string clipboard formats storing the data // in a wide string. //////////////////////////////////////////////////////////////////////////////// TCustomWideTextClipboardFormat = class(TCustomSimpleClipboardFormat) private FText : WideString; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; function GetText: WideString; procedure SetText(const Value: WideString); property Text: WideString read FText write FText; public procedure Clear; override; function HasData: boolean; override; end; //////////////////////////////////////////////////////////////////////////////// // // TTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TTextClipboardFormat = class(TCustomTextClipboardFormat) public function GetClipboardFormat: TClipFormat; override; property Text; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDWORDClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TCustomDWORDClipboardFormat = class(TCustomSimpleClipboardFormat) private FValue : DWORD; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; function GetValueDWORD: DWORD; procedure SetValueDWORD(Value: DWORD); function GetValueInteger: integer; procedure SetValueInteger(Value: integer); function GetValueLongInt: longInt; procedure SetValueLongInt(Value: longInt); function GetValueBoolean: boolean; procedure SetValueBoolean(Value: boolean); public procedure Clear; override; end; //////////////////////////////////////////////////////////////////////////////// // // TFileGroupDescritorClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TFileGroupDescritorClipboardFormat = class(TCustomSimpleClipboardFormat) private FFileGroupDescriptor : PFileGroupDescriptor; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; public function GetClipboardFormat: TClipFormat; override; destructor Destroy; override; procedure Clear; override; function HasData: boolean; override; property FileGroupDescriptor: PFileGroupDescriptor read FFileGroupDescriptor; procedure CopyFrom(AFileGroupDescriptor: PFileGroupDescriptor); end; //////////////////////////////////////////////////////////////////////////////// // // TFileGroupDescritorWClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Warning: TFileGroupDescriptorW has wrong declaration in ShlObj.pas! TFileGroupDescriptorW = record cItems: UINT; fgd: array[0..0] of TFileDescriptorW; end; PFileGroupDescriptorW = ^TFileGroupDescriptorW; TFileGroupDescritorWClipboardFormat = class(TCustomSimpleClipboardFormat) private FFileGroupDescriptor : PFileGroupDescriptorW; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; public function GetClipboardFormat: TClipFormat; override; destructor Destroy; override; procedure Clear; override; function HasData: boolean; override; property FileGroupDescriptor: PFileGroupDescriptorW read FFileGroupDescriptor; procedure CopyFrom(AFileGroupDescriptor: PFileGroupDescriptorW); end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Note: File contents must be zero terminated, so we descend from // TCustomTextClipboardFormat instead of TCustomStringClipboardFormat. //////////////////////////////////////////////////////////////////////////////// TFileContentsClipboardFormat = class(TCustomTextClipboardFormat) public function GetClipboardFormat: TClipFormat; override; constructor Create; override; property Data; end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStreamClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TFileContentsStreamClipboardFormat = class(TClipboardFormat) private FStreams: TStreamList; protected public constructor Create; override; destructor Destroy; override; function GetClipboardFormat: TClipFormat; override; function GetData(DataObject: IDataObject): boolean; override; procedure Clear; override; function HasData: boolean; override; function AssignTo(Dest: TCustomDataFormat): boolean; override; property Streams: TStreamList read FStreams; end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStreamOnDemandClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Yeah, it's a long name, but I like my names descriptive. //////////////////////////////////////////////////////////////////////////////// TVirtualFileStreamDataFormat = class; TFileContentsStreamOnDemandClipboardFormat = class; TOnGetStreamEvent = procedure(Sender: TFileContentsStreamOnDemandClipboardFormat; Index: integer; out AStream: IStream) of object; TFileContentsStreamOnDemandClipboardFormat = class(TClipboardFormat) private FOnGetStream: TOnGetStreamEvent; FGotData: boolean; FDataRequested: boolean; protected function DoSetData(const FormatEtcIn: TFormatEtc; var AMedium: TStgMedium): boolean; override; public constructor Create; override; destructor Destroy; override; function GetClipboardFormat: TClipFormat; override; function GetData(DataObject: IDataObject): boolean; override; procedure Clear; override; function HasData: boolean; override; function AssignTo(Dest: TCustomDataFormat): boolean; override; function Assign(Source: TCustomDataFormat): boolean; override; function GetStream(Index: integer): IStream; property OnGetStream: TOnGetStreamEvent read FOnGetStream write FOnGetStream; end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStorageClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TFileContentsStorageClipboardFormat = class(TClipboardFormat) private FStorages : TStorageInterfaceList; protected public constructor Create; override; destructor Destroy; override; function GetClipboardFormat: TClipFormat; override; function GetData(DataObject: IDataObject): boolean; override; procedure Clear; override; function HasData: boolean; override; function AssignTo(Dest: TCustomDataFormat): boolean; override; property Storages: TStorageInterfaceList read FStorages; end; //////////////////////////////////////////////////////////////////////////////// // // TPreferredDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TPreferredDropEffectClipboardFormat = class(TCustomDWORDClipboardFormat) public class function GetClassClipboardFormat: TClipFormat; function GetClipboardFormat: TClipFormat; override; function HasData: boolean; override; property Value: longInt read GetValueLongInt write SetValueLongInt; end; //////////////////////////////////////////////////////////////////////////////// // // TPerformedDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TPerformedDropEffectClipboardFormat = class(TCustomDWORDClipboardFormat) public function GetClipboardFormat: TClipFormat; override; property Value: longInt read GetValueLongInt write SetValueLongInt; end; //////////////////////////////////////////////////////////////////////////////// // // TLogicalPerformedDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// // Microsoft's latest (so far) "logical" solution to the never ending attempts // of reporting back to the source which operation actually took place. Sigh! //////////////////////////////////////////////////////////////////////////////// TLogicalPerformedDropEffectClipboardFormat = class(TCustomDWORDClipboardFormat) public function GetClipboardFormat: TClipFormat; override; property Value: longInt read GetValueLongInt write SetValueLongInt; end; //////////////////////////////////////////////////////////////////////////////// // // TPasteSuccededClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TPasteSuccededClipboardFormat = class(TCustomDWORDClipboardFormat) public function GetClipboardFormat: TClipFormat; override; property Value: longInt read GetValueLongInt write SetValueLongInt; end; //////////////////////////////////////////////////////////////////////////////// // // TInDragLoopClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TInShellDragLoopClipboardFormat = class(TCustomDWORDClipboardFormat) public function GetClipboardFormat: TClipFormat; override; property InShellDragLoop: boolean read GetValueBoolean write SetValueBoolean; end; //////////////////////////////////////////////////////////////////////////////// // // TTargetCLSIDClipboardFormat // //////////////////////////////////////////////////////////////////////////////// TTargetCLSIDClipboardFormat = class(TCustomSimpleClipboardFormat) private FCLSID: TCLSID; protected function ReadData(Value: pointer; Size: integer): boolean; override; function WriteData(Value: pointer; Size: integer): boolean; override; function GetSize: integer; override; public function GetClipboardFormat: TClipFormat; override; procedure Clear; override; function HasData: boolean; override; property CLSID: TCLSID read FCLSID write FCLSID; end; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // TTextDataFormat // //////////////////////////////////////////////////////////////////////////////// TTextDataFormat = class(TCustomDataFormat) private FText : string; protected procedure SetText(const Value: string); public function Assign(Source: TClipboardFormat): boolean; override; function AssignTo(Dest: TClipboardFormat): boolean; override; procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; property Text: string read FText write SetText; end; //////////////////////////////////////////////////////////////////////////////// // // TDataStreamDataFormat // //////////////////////////////////////////////////////////////////////////////// TDataStreamDataFormat = class(TCustomDataFormat) private FStreams : TStreamList; public constructor Create(AOwner: TDragDropComponent); override; destructor Destroy; override; procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; property Streams: TStreamList read FStreams; end; //////////////////////////////////////////////////////////////////////////////// // // TVirtualFileStreamDataFormat // //////////////////////////////////////////////////////////////////////////////// TVirtualFileStreamDataFormat = class(TCustomDataFormat) private FFileDescriptors: TMemoryList; FFileNames: TStrings; FFileContentsClipboardFormat: TFileContentsStreamOnDemandClipboardFormat; FFileGroupDescritorClipboardFormat: TFileGroupDescritorClipboardFormat; FHasContents: boolean; protected procedure SetFileNames(const Value: TStrings); function GetOnGetStream: TOnGetStreamEvent; procedure SetOnGetStream(const Value: TOnGetStreamEvent); public constructor Create(AOwner: TDragDropComponent); override; destructor Destroy; override; function Assign(Source: TClipboardFormat): boolean; override; function AssignTo(Dest: TClipboardFormat): boolean; override; procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; property FileDescriptors: TMemoryList read FFileDescriptors; property FileNames: TStrings read FFileNames write SetFileNames; property FileContentsClipboardFormat: TFileContentsStreamOnDemandClipboardFormat read FFileContentsClipboardFormat; property FileGroupDescritorClipboardFormat: TFileGroupDescritorClipboardFormat read FFileGroupDescritorClipboardFormat; property OnGetStream: TOnGetStreamEvent read GetOnGetStream write SetOnGetStream; end; //////////////////////////////////////////////////////////////////////////////// // // TFeedbackDataFormat // //////////////////////////////////////////////////////////////////////////////// // Data used for communication between source and target. // Only used by the drop source. //////////////////////////////////////////////////////////////////////////////// TFeedbackDataFormat = class(TCustomDataFormat) private FPreferredDropEffect: longInt; FPerformedDropEffect: longInt; FLogicalPerformedDropEffect: longInt; FPasteSucceded: longInt; FInShellDragLoop: boolean; FGotInShellDragLoop: boolean; FTargetCLSID: TCLSID; protected procedure SetInShellDragLoop(const Value: boolean); procedure SetPasteSucceded(const Value: longInt); procedure SetPerformedDropEffect(const Value: longInt); procedure SetPreferredDropEffect(const Value: longInt); procedure SetTargetCLSID(const Value: TCLSID); procedure SetLogicalPerformedDropEffect(const Value: Integer); public function Assign(Source: TClipboardFormat): boolean; override; function AssignTo(Dest: TClipboardFormat): boolean; override; procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; property PreferredDropEffect: longInt read FPreferredDropEffect write SetPreferredDropEffect; property PerformedDropEffect: longInt read FPerformedDropEffect write SetPerformedDropEffect; property LogicalPerformedDropEffect: longInt read FLogicalPerformedDropEffect write SetLogicalPerformedDropEffect; property PasteSucceded: longInt read FPasteSucceded write SetPasteSucceded; property InShellDragLoop: boolean read FInShellDragLoop write SetInShellDragLoop; property TargetCLSID: TCLSID read FTargetCLSID write SetTargetCLSID; end; //////////////////////////////////////////////////////////////////////////////// // // TGenericClipboardFormat & TGenericDataFormat // //////////////////////////////////////////////////////////////////////////////// // TGenericDataFormat is not used internally by the library, but can be used to // add support for new formats with a minimum of custom code. // Even though TGenericDataFormat represents the data as a string, it can be // used to transfer any kind of data. // TGenericClipboardFormat is used internally by TGenericDataFormat but can also // be used by other TCustomDataFormat descendants or as a base class for new // clipboard formats. // Note that you should not register TGenericClipboardFormat as compatible with // TGenericDataFormat. // To use TGenericDataFormat, all you need to do is instantiate it against // the desired component and register your custom clipboard formats: // // var // MyCustomData: TGenericDataFormat; // // MyCustomData := TGenericDataFormat.Create(DropTextTarget1); // MyCustomData.AddFormat('MyCustomFormat'); // //////////////////////////////////////////////////////////////////////////////// TGenericDataFormat = class(TCustomDataFormat) private FData : string; protected function GetSize: integer; procedure DoSetData(const Value: string); public procedure Clear; override; function HasData: boolean; override; function NeedsData: boolean; override; procedure AddFormat(const AFormat: string); procedure SetDataHere(const AData; ASize: integer); function GetDataHere(var AData; ASize: integer): integer; property Data: string read FData write DoSetData; property Size: integer read GetSize; end; TGenericClipboardFormat = class(TCustomStringClipboardFormat) private FFormat: string; protected procedure SetClipboardFormatName(const Value: string); override; function GetClipboardFormatName: string; override; function GetClipboardFormat: TClipFormat; override; public function Assign(Source: TCustomDataFormat): boolean; override; function AssignTo(Dest: TCustomDataFormat): boolean; override; property Data; end; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // IMPLEMENTATION // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// implementation uses DropSource, DropTarget, SysUtils; //////////////////////////////////////////////////////////////////////////////// // // TStreamList // //////////////////////////////////////////////////////////////////////////////// constructor TStreamList.Create; begin inherited Create; FStreams := TStringList.Create; end; destructor TStreamList.Destroy; begin Clear; FStreams.Free; inherited Destroy; end; procedure TStreamList.Changing; begin if (Assigned(OnChanging)) then OnChanging(Self); end; function TStreamList.GetStream(Index: integer): TStream; begin Result := TStream(FStreams.Objects[Index]); end; function TStreamList.Add(Stream: TStream): integer; begin Result := AddNamed(Stream, ''); end; function TStreamList.AddNamed(Stream: TStream; Name: string): integer; begin Changing; Result := FStreams.AddObject(Name, Stream); end; function TStreamList.GetCount: integer; begin Result := FStreams.Count; end; procedure TStreamList.Assign(Value: TStreamList); begin Clear; FStreams.Assign(Value.Names); // Transfer ownership of objects Value.FStreams.Clear; end; procedure TStreamList.Delete(Index: integer); begin Changing; FStreams.Delete(Index); end; procedure TStreamList.Clear; var i : integer; begin Changing; for i := 0 to FStreams.Count-1 do if (FStreams.Objects[i] <> nil) then FStreams.Objects[i].Free; FStreams.Clear; end; //////////////////////////////////////////////////////////////////////////////// // // TInterfaceList // //////////////////////////////////////////////////////////////////////////////// constructor TInterfaceList.Create; begin inherited Create; FList := TStringList.Create; end; destructor TInterfaceList.Destroy; begin Clear; FList.Free; inherited Destroy; end; function TInterfaceList.Add(Item: IUnknown): integer; begin Result := AddNamed(Item, ''); end; function TInterfaceList.AddNamed(Item: IUnknown; Name: string): integer; begin Changing; with FList do begin Result := AddObject(Name, nil); Objects[Result] := TObject(Item); Item._AddRef; end; end; procedure TInterfaceList.Changing; begin if (Assigned(OnChanging)) then OnChanging(Self); end; procedure TInterfaceList.Clear; var i : Integer; p : pointer; begin Changing; with FList do begin for i := 0 to Count - 1 do begin p := Objects[i]; IUnknown(p) := nil; end; Clear; end; end; procedure TInterfaceList.Assign(Value: TInterfaceList); var i : Integer; begin Changing; for i := 0 to Value.Count - 1 do AddNamed(Value.Items[i], Value.Names[i]); end; procedure TInterfaceList.Delete(Index: integer); var p : pointer; begin Changing; with FList do begin p := Objects[Index]; IUnknown(p) := nil; Delete(Index); end; end; function TInterfaceList.GetCount: integer; begin Result := FList.Count; end; function TInterfaceList.GetName(Index: integer): string; begin Result := FList[Index]; end; function TInterfaceList.GetItem(Index: integer): IUnknown; var p : pointer; begin p := FList.Objects[Index]; Result := IUnknown(p); end; //////////////////////////////////////////////////////////////////////////////// // // TStorageInterfaceList // //////////////////////////////////////////////////////////////////////////////// function TStorageInterfaceList.GetStorage(Index: integer): IStorage; begin Result := IStorage(Items[Index]); end; //////////////////////////////////////////////////////////////////////////////// // // TMemoryList // //////////////////////////////////////////////////////////////////////////////// function TMemoryList.Add(Item: Pointer): Integer; begin Result := FList.Add(Item); end; procedure TMemoryList.Clear; var i: integer; begin for i := FList.Count-1 downto 0 do Delete(i); end; constructor TMemoryList.Create; begin inherited Create; FList := TList.Create; end; procedure TMemoryList.Delete(Index: Integer); begin Freemem(FList[Index]); FList.Delete(Index); end; destructor TMemoryList.Destroy; begin FList.Free; inherited Destroy; end; function TMemoryList.Get(Index: Integer): Pointer; begin Result := FList[Index]; end; function TMemoryList.GetCount: Integer; begin Result := FList.Count; end; //////////////////////////////////////////////////////////////////////////////// // // TFixedStreamAdapter // //////////////////////////////////////////////////////////////////////////////// function TFixedStreamAdapter.CopyTo(stm: IStream; cb: Largeint; out cbRead: Largeint; out cbWritten: Largeint): HResult; const MaxBufSize = 1024 * 1024; // 1mb var Buffer: Pointer; BufSize, BurstReadSize, BurstWriteSize: Integer; BytesRead, BytesWritten, BurstWritten: LongInt; begin Result := S_OK; BytesRead := 0; BytesWritten := 0; try if (cb < 0) then begin // Note: The folowing is a workaround for a design bug in either explorer // or the clipboard. See comment in TCustomSimpleClipboardFormat.DoSetData // for an explanation. if (Stream.Position = Stream.Size) then Stream.Position := 0; cb := Stream.Size - Stream.Position; end; if cb > MaxBufSize then BufSize := MaxBufSize else BufSize := Integer(cb); GetMem(Buffer, BufSize); try while cb > 0 do begin if cb > BufSize then BurstReadSize := BufSize else BurstReadSize := cb; BurstWriteSize := Stream.Read(Buffer^, BurstReadSize); if (BurstWriteSize = 0) then break; Inc(BytesRead, BurstWriteSize); BurstWritten := 0; Result := stm.Write(Buffer, BurstWriteSize, @BurstWritten); Inc(BytesWritten, BurstWritten); if (Result = S_OK) and (Integer(BurstWritten) <> BurstWriteSize) then Result := E_FAIL; if Result <> S_OK then Exit; Dec(cb, BurstWritten); end; finally FreeMem(Buffer); if (@cbWritten <> nil) then cbWritten := BytesWritten; if (@cbRead <> nil) then cbRead := BytesRead; end; except Result := E_UNEXPECTED; end; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomSimpleClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TCustomSimpleClipboardFormat.Create; begin CreateFormat(TYMED_HGLOBAL or TYMED_ISTREAM); end; function TCustomSimpleClipboardFormat.DoGetData(ADataObject: IDataObject; const AMedium: TStgMedium): boolean; var Stream : IStream; StatStg : TStatStg; Size : integer; begin // Get size from HGlobal. if (AMedium.tymed and TYMED_HGLOBAL <> 0) then begin Size := GlobalSize(AMedium.HGlobal); Result := True; end else // Get size from IStream. if (AMedium.tymed and TYMED_ISTREAM <> 0) then begin Stream := IStream(AMedium.stm); Result := (Stream <> nil) and (Stream.Stat(StatStg, STATFLAG_NONAME) = S_OK); Size := StatStg.cbSize; Stream := nil; // Not really nescessary. end else begin Size := 0; Result := False; end; if (Result) and (Size > 0) then begin // Read the given amount of data. Result := DoGetDataSized(ADataObject, AMedium, Size); end; end; function TCustomSimpleClipboardFormat.DoGetDataSized(ADataObject: IDataObject; const AMedium: TStgMedium; Size: integer): boolean; var Buffer: pointer; Stream: IStream; Remaining: longInt; Chunk: longInt; pChunk: PChar; begin if (Size > 0) then begin (* ** In this method we prefer TYMED_HGLOBAL over TYMED_ISTREAM and thus check ** for TYMED_HGLOBAL first. *) // Read data from HGlobal if (AMedium.tymed and TYMED_HGLOBAL <> 0) then begin // Use global memory as buffer Buffer := GlobalLock(AMedium.HGlobal); try // Read data from buffer into object Result := (Buffer <> nil) and (ReadData(Buffer, Size)); finally GlobalUnlock(AMedium.HGlobal); end; end else // Read data from IStream if (AMedium.tymed and TYMED_ISTREAM <> 0) then begin // Allocate buffer GetMem(Buffer, Size); try // Read data from stream into buffer Stream := IStream(AMedium.stm); if (Stream <> nil) then begin Stream.Seek(0, STREAM_SEEK_SET, PLargeuint(nil)^); Result := True; Remaining := Size; pChunk := Buffer; while (Result) and (Remaining > 0) do begin Result := (Stream.Read(pChunk, Remaining, @Chunk) = S_OK); if (Chunk = 0) then break; inc(pChunk, Chunk); dec(Remaining, Chunk); end; Stream := nil; // Not really nescessary. end else Result := False; // Transfer data from buffer into object. Result := Result and (ReadData(Buffer, Size)); finally FreeMem(Buffer); end; end else Result := False; end else Result := False; end; function TCustomSimpleClipboardFormat.ReadDataInto(ADataObject: IDataObject; const AMedium: TStgMedium; Buffer: pointer; Size: integer): boolean; var Stream: IStream; p: pointer; Remaining: longInt; Chunk: longInt; begin Result := (Buffer <> nil) and (Size > 0); if (Result) then begin // Read data from HGlobal if (AMedium.tymed and TYMED_HGLOBAL <> 0) then begin p := GlobalLock(AMedium.HGlobal); try Result := (p <> nil); if (Result) then Move(p^, Buffer^, Size); finally GlobalUnlock(AMedium.HGlobal); end; end else // Read data from IStream if (AMedium.tymed and TYMED_ISTREAM <> 0) then begin Stream := IStream(AMedium.stm); if (Stream <> nil) then begin Stream.Seek(0, STREAM_SEEK_SET, PLargeuint(nil)^); Remaining := Size; while (Result) and (Remaining > 0) do begin Result := (Stream.Read(Buffer, Remaining, @Chunk) = S_OK); if (Chunk = 0) then break; inc(PChar(Buffer), Chunk); dec(Remaining, Chunk); end; end else Result := False; end else Result := False; end; end; function TCustomSimpleClipboardFormat.DoSetData(const FormatEtcIn: TFormatEtc; var AMedium: TStgMedium): boolean; var p: pointer; Size: integer; Stream: TMemoryStream; // Warning: TStreamAdapter.CopyTo is broken! StreamAdapter: TStreamAdapter; begin Result := False; Size := GetSize; if (Size <= 0) then exit; if (FormatEtcIn.tymed and TYMED_ISTREAM <> 0) then begin Stream := TMemoryStream.Create; StreamAdapter := TFixedStreamAdapter.Create(Stream, soOwned); try Stream.Size := Size; Result := WriteData(Stream.Memory, Size); // Note: Conflicting information on which of the following two are correct: // // 1) Stream.Position := Size; // // 2) Stream.Position := 0; // // #1 is required for clipboard operations to succeed; The clipboard uses // a Seek(0, STREAM_SEEK_CUR) to determine the size of the stream. // // #2 is required for shell operations to succeed; The shell uses a // Read(-1) to read all of the stream. // // This library uses a Stream.Stat to determine the size of the stream and // then reads from start to end of stream. // // Since we use #1 (see below), we work around #2 in // TFixedStreamAdapter.CopyTo. if (Result) then begin Stream.Position := Size; IStream(AMedium.stm) := StreamAdapter as IStream; end; except Result := False; end; if (not Result) then begin StreamAdapter.Free; AMedium.stm := nil; end else AMedium.tymed := TYMED_ISTREAM; end else if (FormatEtcIn.tymed and TYMED_HGLOBAL <> 0) then begin AMedium.hGlobal := GlobalAlloc(GMEM_SHARE or GHND, Size); if (AMedium.hGlobal = 0) then exit; try p := GlobalLock(AMedium.hGlobal); try Result := (p <> nil) and WriteData(p, Size); finally GlobalUnlock(AMedium.hGlobal); end; except Result := False; end; if (not Result) then begin GlobalFree(AMedium.hGlobal); AMedium.hGlobal := 0; end else AMedium.tymed := TYMED_HGLOBAL; end else Result := False; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomStringClipboardFormat // //////////////////////////////////////////////////////////////////////////////// procedure TCustomStringClipboardFormat.Clear; begin FData := ''; end; function TCustomStringClipboardFormat.HasData: boolean; begin Result := (FData <> ''); end; function TCustomStringClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin SetLength(FData, Size); Move(Value^, PChar(FData)^, Size); // IE adds a lot of trailing zeroes which is included in the string length. // To avoid confusion, we trim all trailing zeroes but the last (which is // managed automatically by Delphi). // Note that since this work around, if applied generally, would mean that we // couldn't use this class to handle arbitrary binary data (which might // include zeroes), we are required to explicitly enable it in the classes // where we need it (e.g. all TCustomTextClipboardFormat descedants). if (FTrimZeroes) then SetLength(FData, Length(PChar(FData))); Result := True; end; function TCustomStringClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin // Transfer string including terminating zero if requested. Result := (Size <= Length(FData)+1); if (Result) then Move(PChar(FData)^, Value^, Size); end; function TCustomStringClipboardFormat.GetSize: integer; begin Result := Length(FData); end; function TCustomStringClipboardFormat.GetString: string; begin Result := FData; end; procedure TCustomStringClipboardFormat.SetString(const Value: string); begin FData := Value; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomStringListClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TCustomStringListClipboardFormat.Create; begin inherited Create; FLines := TStringList.Create end; destructor TCustomStringListClipboardFormat.Destroy; begin FLines.Free; inherited Destroy; end; procedure TCustomStringListClipboardFormat.Clear; begin FLines.Clear; end; function TCustomStringListClipboardFormat.HasData: boolean; begin Result := (FLines.Count > 0); end; function TCustomStringListClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; var s : string; begin SetLength(s, Size+1); Move(Value^, PChar(s)^, Size); s[Size] := #0; FLines.Text := s; Result := True; end; function TCustomStringListClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; var s : string; begin s := FLines.Text; Result := (Size = Length(s)+1); if (Result) then Move(PChar(s)^, Value^, Size); end; function TCustomStringListClipboardFormat.GetSize: integer; begin Result := Length(FLines.Text)+1; end; function TCustomStringListClipboardFormat.GetLines: TStrings; begin Result := FLines; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TCustomTextClipboardFormat.Create; begin inherited Create; TrimZeroes := True; end; function TCustomTextClipboardFormat.GetSize: integer; begin Result := inherited GetSize; // Unless the data is already zero terminated, we add a byte to include // the string's implicit terminating zero. if (Data[Result] <> #0) then inc(Result); end; //////////////////////////////////////////////////////////////////////////////// // // TCustomWideTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// procedure TCustomWideTextClipboardFormat.Clear; begin FText := ''; end; function TCustomWideTextClipboardFormat.HasData: boolean; begin Result := (FText <> ''); end; function TCustomWideTextClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin SetLength(FText, Size div 2); Move(Value^, PWideChar(FText)^, Size); Result := True; end; function TCustomWideTextClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin Result := (Size <= (Length(FText)+1)*2); if (Result) then Move(PWideChar(FText)^, Value^, Size); end; function TCustomWideTextClipboardFormat.GetSize: integer; begin Result := Length(FText)*2; // Unless the data is already zero terminated, we add two bytes to include // the string's implicit terminating zero. if (FText[Result] <> #0) then inc(Result, 2); end; function TCustomWideTextClipboardFormat.GetText: WideString; begin Result := FText; end; procedure TCustomWideTextClipboardFormat.SetText(const Value: WideString); begin FText := Value; end; //////////////////////////////////////////////////////////////////////////////// // // TTextClipboardFormat // //////////////////////////////////////////////////////////////////////////////// function TTextClipboardFormat.GetClipboardFormat: TClipFormat; begin Result := CF_TEXT; end; //////////////////////////////////////////////////////////////////////////////// // // TCustomDWORDClipboardFormat // //////////////////////////////////////////////////////////////////////////////// function TCustomDWORDClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin FValue := PDWORD(Value)^; Result := True; end; function TCustomDWORDClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin Result := (Size = SizeOf(DWORD)); if (Result) then PDWORD(Value)^ := FValue; end; function TCustomDWORDClipboardFormat.GetSize: integer; begin Result := SizeOf(DWORD); end; procedure TCustomDWORDClipboardFormat.Clear; begin FValue := 0; end; function TCustomDWORDClipboardFormat.GetValueDWORD: DWORD; begin Result := FValue; end; procedure TCustomDWORDClipboardFormat.SetValueDWORD(Value: DWORD); begin FValue := Value; end; function TCustomDWORDClipboardFormat.GetValueInteger: integer; begin Result := integer(FValue); end; procedure TCustomDWORDClipboardFormat.SetValueInteger(Value: integer); begin FValue := DWORD(Value); end; function TCustomDWORDClipboardFormat.GetValueLongInt: longInt; begin Result := longInt(FValue); end; procedure TCustomDWORDClipboardFormat.SetValueLongInt(Value: longInt); begin FValue := DWORD(Value); end; function TCustomDWORDClipboardFormat.GetValueBoolean: boolean; begin Result := (FValue <> 0); end; procedure TCustomDWORDClipboardFormat.SetValueBoolean(Value: boolean); begin FValue := ord(Value); end; //////////////////////////////////////////////////////////////////////////////// // // TFileGroupDescritorClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_FILEGROUPDESCRIPTOR: TClipFormat = 0; function TFileGroupDescritorClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILEGROUPDESCRIPTOR = 0) then CF_FILEGROUPDESCRIPTOR := RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR); Result := CF_FILEGROUPDESCRIPTOR; end; destructor TFileGroupDescritorClipboardFormat.Destroy; begin Clear; inherited Destroy; end; procedure TFileGroupDescritorClipboardFormat.Clear; begin if (FFileGroupDescriptor <> nil) then begin FreeMem(FFileGroupDescriptor); FFileGroupDescriptor := nil; end; end; function TFileGroupDescritorClipboardFormat.HasData: boolean; begin Result := (FFileGroupDescriptor <> nil) and (FFileGroupDescriptor^.cItems <> 0); end; procedure TFileGroupDescritorClipboardFormat.CopyFrom(AFileGroupDescriptor: PFileGroupDescriptor); var Size : integer; begin Clear; if (AFileGroupDescriptor <> nil) then begin Size := SizeOf(UINT) + AFileGroupDescriptor^.cItems * SizeOf(TFileDescriptor); GetMem(FFileGroupDescriptor, Size); Move(AFileGroupDescriptor^, FFileGroupDescriptor^, Size); end; end; function TFileGroupDescritorClipboardFormat.GetSize: integer; begin if (FFileGroupDescriptor <> nil) then Result := SizeOf(UINT) + FFileGroupDescriptor^.cItems * SizeOf(TFileDescriptor) else Result := 0; end; function TFileGroupDescritorClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin // Validate size against count Result := (Size - SizeOf(UINT)) DIV SizeOf(TFileDescriptor) = integer(PFileGroupDescriptor(Value)^.cItems); if (Result) then CopyFrom(PFileGroupDescriptor(Value)); end; function TFileGroupDescritorClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin // Validate size against count Result := (FFileGroupDescriptor <> nil) and ((Size - SizeOf(UINT)) DIV SizeOf(TFileDescriptor) = integer(FFileGroupDescriptor^.cItems)); if (Result) then Move(FFileGroupDescriptor^, Value^, Size); end; //////////////////////////////////////////////////////////////////////////////// // // TFileGroupDescritorWClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_FILEGROUPDESCRIPTORW: TClipFormat = 0; function TFileGroupDescritorWClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILEGROUPDESCRIPTORW = 0) then CF_FILEGROUPDESCRIPTORW := RegisterClipboardFormat(CFSTR_FILEDESCRIPTORW); Result := CF_FILEGROUPDESCRIPTORW; end; destructor TFileGroupDescritorWClipboardFormat.Destroy; begin Clear; inherited Destroy; end; procedure TFileGroupDescritorWClipboardFormat.Clear; begin if (FFileGroupDescriptor <> nil) then begin FreeMem(FFileGroupDescriptor); FFileGroupDescriptor := nil; end; end; function TFileGroupDescritorWClipboardFormat.HasData: boolean; begin Result := (FFileGroupDescriptor <> nil) and (FFileGroupDescriptor^.cItems <> 0); end; procedure TFileGroupDescritorWClipboardFormat.CopyFrom(AFileGroupDescriptor: PFileGroupDescriptorW); var Size : integer; begin Clear; if (AFileGroupDescriptor <> nil) then begin Size := SizeOf(UINT) + AFileGroupDescriptor^.cItems * SizeOf(TFileDescriptorW); GetMem(FFileGroupDescriptor, Size); Move(AFileGroupDescriptor^, FFileGroupDescriptor^, Size); end; end; function TFileGroupDescritorWClipboardFormat.GetSize: integer; begin if (FFileGroupDescriptor <> nil) then Result := SizeOf(UINT) + FFileGroupDescriptor^.cItems * SizeOf(TFileDescriptorW) else Result := 0; end; function TFileGroupDescritorWClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin // Validate size against count Result := (Size - SizeOf(UINT)) DIV SizeOf(TFileDescriptorW) = integer(PFileGroupDescriptor(Value)^.cItems); if (Result) then CopyFrom(PFileGroupDescriptorW(Value)); end; function TFileGroupDescritorWClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin // Validate size against count Result := (FFileGroupDescriptor <> nil) and ((Size - SizeOf(UINT)) DIV SizeOf(TFileDescriptorW) = integer(FFileGroupDescriptor^.cItems)); if (Result) then Move(FFileGroupDescriptor^, Value^, Size); end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_FILECONTENTS: TClipFormat = 0; constructor TFileContentsClipboardFormat.Create; begin inherited Create; FFormatEtc.lindex := 0; end; function TFileContentsClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILECONTENTS = 0) then CF_FILECONTENTS := RegisterClipboardFormat(CFSTR_FILECONTENTS); Result := CF_FILECONTENTS; end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStreamClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TFileContentsStreamClipboardFormat.Create; begin CreateFormat(TYMED_ISTREAM); FStreams := TStreamList.Create; end; destructor TFileContentsStreamClipboardFormat.Destroy; begin Clear; FStreams.Free; inherited Destroy; end; function TFileContentsStreamClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILECONTENTS = 0) then CF_FILECONTENTS := RegisterClipboardFormat(CFSTR_FILECONTENTS); Result := CF_FILECONTENTS; end; procedure TFileContentsStreamClipboardFormat.Clear; begin FStreams.Clear; end; function TFileContentsStreamClipboardFormat.HasData: boolean; begin Result := (FStreams.Count > 0); end; function TFileContentsStreamClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean; begin Result := True; if (Dest is TDataStreamDataFormat) then begin TDataStreamDataFormat(Dest).Streams.Assign(Streams); end else Result := inherited AssignTo(Dest); end; {$IFOPT R+} {$DEFINE R_PLUS} {$RANGECHECKS OFF} {$ENDIF} function TFileContentsStreamClipboardFormat.GetData(DataObject: IDataObject): boolean; var FGD: TFileGroupDescritorClipboardFormat; Count: integer; Medium: TStgMedium; Stream: IStream; Name: string; MemStream: TMemoryStream; StatStg: TStatStg; Size: longInt; Remaining: longInt; pChunk: PChar; begin Result := False; Clear; FGD := TFileGroupDescritorClipboardFormat.Create; try if (FGD.GetData(DataObject)) then begin // Multiple objects, retrieve one at a time Count := FGD.FileGroupDescriptor^.cItems; FFormatEtc.lindex := 0; end else begin // Single object, retrieve "all" at once Count := 0; FFormatEtc.lindex := -1; Name := ''; end; while (FFormatEtc.lindex < Count) do begin if (DataObject.GetData(FormatEtc, Medium) <> S_OK) then break; try inc(FFormatEtc.lindex); if (Medium.tymed <> TYMED_ISTREAM) then continue; Stream := IStream(Medium.stm); Stream.Stat(StatStg, STATFLAG_NONAME); MemStream := TMemoryStream.Create; try Remaining := StatStg.cbSize; MemStream.Size := Remaining; pChunk := MemStream.Memory; while (Remaining > 0) do begin if (Stream.Read(pChunk, Remaining, @Size) <> S_OK) or (Size = 0) then break; inc(pChunk, Size); dec(Remaining, Size); end; if (FFormatEtc.lindex > 0) then Name := FGD.FileGroupDescriptor^.fgd[FFormatEtc.lindex-1].cFileName; Streams.AddNamed(MemStream, Name); except MemStream.Free; raise; end; Stream := nil; Result := True; finally ReleaseStgMedium(Medium); end; end; finally FGD.Free; end; end; {$IFDEF R_PLUS} {$RANGECHECKS ON} {$UNDEF R_PLUS} {$ENDIF} //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStreamOnDemandClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TFileContentsStreamOnDemandClipboardFormat.Create; begin CreateFormat(TYMED_ISTREAM); end; destructor TFileContentsStreamOnDemandClipboardFormat.Destroy; begin Clear; inherited Destroy; end; function TFileContentsStreamOnDemandClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILECONTENTS = 0) then CF_FILECONTENTS := RegisterClipboardFormat(CFSTR_FILECONTENTS); Result := CF_FILECONTENTS; end; procedure TFileContentsStreamOnDemandClipboardFormat.Clear; begin FGotData := False; FDataRequested := False; end; function TFileContentsStreamOnDemandClipboardFormat.HasData: boolean; begin Result := FGotData or FDataRequested; end; function TFileContentsStreamOnDemandClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean; begin if (Dest is TVirtualFileStreamDataFormat) then begin Result := True end else Result := inherited AssignTo(Dest); end; function TFileContentsStreamOnDemandClipboardFormat.Assign( Source: TCustomDataFormat): boolean; begin if (Source is TVirtualFileStreamDataFormat) then begin // Acknowledge that we can offer the requested data, but defer the actual // data transfer. FDataRequested := True; Result := True end else Result := inherited Assign(Source); end; function TFileContentsStreamOnDemandClipboardFormat.DoSetData( const FormatEtcIn: TFormatEtc; var AMedium: TStgMedium): boolean; var Stream : IStream; begin if (Assigned(FOnGetStream)) and (FormatEtcIn.tymed and TYMED_ISTREAM <> 0) and (FormatEtcIn.lindex <> -1) then begin FOnGetStream(Self, FormatEtcIn.lindex, Stream); if (Stream <> nil) then begin IStream(AMedium.stm) := Stream; AMedium.tymed := TYMED_ISTREAM; Result := True; end else Result := False; end else Result := False; end; function TFileContentsStreamOnDemandClipboardFormat.GetData(DataObject: IDataObject): boolean; begin // Flag that data has been offered to us, but defer the actual data transfer. FGotData := True; Result := True; end; function TFileContentsStreamOnDemandClipboardFormat.GetStream(Index: integer): IStream; var Medium : TStgMedium; begin Result := nil; FFormatEtc.lindex := Index; // Get an IStream interface from the source. if ((DataFormat.Owner as TCustomDroptarget).DataObject.GetData(FormatEtc, Medium) = S_OK) and (Medium.tymed = TYMED_ISTREAM) then try Result := IStream(Medium.stm); finally ReleaseStgMedium(Medium); end; end; //////////////////////////////////////////////////////////////////////////////// // // TFileContentsStorageClipboardFormat // //////////////////////////////////////////////////////////////////////////////// constructor TFileContentsStorageClipboardFormat.Create; begin CreateFormat(TYMED_ISTORAGE); FStorages := TStorageInterfaceList.Create; end; destructor TFileContentsStorageClipboardFormat.Destroy; begin Clear; FStorages.Free; inherited Destroy; end; function TFileContentsStorageClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_FILECONTENTS = 0) then CF_FILECONTENTS := RegisterClipboardFormat(CFSTR_FILECONTENTS); Result := CF_FILECONTENTS; end; procedure TFileContentsStorageClipboardFormat.Clear; begin FStorages.Clear; end; function TFileContentsStorageClipboardFormat.HasData: boolean; begin Result := (FStorages.Count > 0); end; function TFileContentsStorageClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean; begin (* Result := True; if (Dest is TDataStreamDataFormat) then begin TDataStreamDataFormat(Dest).Streams.Assign(Streams); end else *) Result := inherited AssignTo(Dest); end; {$IFOPT R+} {$DEFINE R_PLUS} {$RANGECHECKS OFF} {$ENDIF} function TFileContentsStorageClipboardFormat.GetData(DataObject: IDataObject): boolean; var FGD : TFileGroupDescritorClipboardFormat; Count : integer; Medium : TStgMedium; Storage : IStorage; Name : string; begin Result := False; Clear; FGD := TFileGroupDescritorClipboardFormat.Create; try if (FGD.GetData(DataObject)) then begin // Multiple objects, retrieve one at a time Count := FGD.FileGroupDescriptor^.cItems; FFormatEtc.lindex := 0; end else begin // Single object, retrieve "all" at once Count := 0; FFormatEtc.lindex := -1; Name := ''; end; while (FFormatEtc.lindex < Count) do begin if (DataObject.GetData(FormatEtc, Medium) <> S_OK) then break; try inc(FFormatEtc.lindex); if (Medium.tymed <> TYMED_ISTORAGE) then continue; Storage := IStorage(Medium.stg); if (FFormatEtc.lindex > 0) then Name := FGD.FileGroupDescriptor^.fgd[FFormatEtc.lindex-1].cFileName; Storages.AddNamed(Storage, Name); Storage := nil; Result := True; finally ReleaseStgMedium(Medium); end; end; finally FGD.Free; end; end; {$IFDEF R_PLUS} {$RANGECHECKS ON} {$UNDEF R_PLUS} {$ENDIF} //////////////////////////////////////////////////////////////////////////////// // // TPreferredDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_PREFERREDDROPEFFECT: TClipFormat = 0; // GetClassClipboardFormat is used by TCustomDropTarget.GetPreferredDropEffect class function TPreferredDropEffectClipboardFormat.GetClassClipboardFormat: TClipFormat; begin if (CF_PREFERREDDROPEFFECT = 0) then CF_PREFERREDDROPEFFECT := RegisterClipboardFormat(CFSTR_PREFERREDDROPEFFECT); Result := CF_PREFERREDDROPEFFECT; end; function TPreferredDropEffectClipboardFormat.GetClipboardFormat: TClipFormat; begin Result := GetClassClipboardFormat; end; function TPreferredDropEffectClipboardFormat.HasData: boolean; begin Result := True; //(Value <> DROPEFFECT_NONE); end; //////////////////////////////////////////////////////////////////////////////// // // TPerformedDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_PERFORMEDDROPEFFECT: TClipFormat = 0; function TPerformedDropEffectClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_PERFORMEDDROPEFFECT = 0) then CF_PERFORMEDDROPEFFECT := RegisterClipboardFormat(CFSTR_PERFORMEDDROPEFFECT); Result := CF_PERFORMEDDROPEFFECT; end; //////////////////////////////////////////////////////////////////////////////// // // TLogicalPerformedDropEffectClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_LOGICALPERFORMEDDROPEFFECT: TClipFormat = 0; function TLogicalPerformedDropEffectClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_LOGICALPERFORMEDDROPEFFECT = 0) then CF_LOGICALPERFORMEDDROPEFFECT := RegisterClipboardFormat('Logical Performed DropEffect'); // *** DO NOT LOCALIZE *** Result := CF_LOGICALPERFORMEDDROPEFFECT; end; //////////////////////////////////////////////////////////////////////////////// // // TPasteSuccededClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_PASTESUCCEEDED: TClipFormat = 0; function TPasteSuccededClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_PASTESUCCEEDED = 0) then CF_PASTESUCCEEDED := RegisterClipboardFormat(CFSTR_PASTESUCCEEDED); Result := CF_PASTESUCCEEDED; end; //////////////////////////////////////////////////////////////////////////////// // // TInShellDragLoopClipboardFormat // //////////////////////////////////////////////////////////////////////////////// var CF_InDragLoop: TClipFormat = 0; function TInShellDragLoopClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_InDragLoop = 0) then CF_InDragLoop := RegisterClipboardFormat(CFSTR_InDragLoop); Result := CF_InDragLoop; end; //////////////////////////////////////////////////////////////////////////////// // // TTargetCLSIDClipboardFormat // //////////////////////////////////////////////////////////////////////////////// procedure TTargetCLSIDClipboardFormat.Clear; begin FCLSID := GUID_NULL; end; var CF_TargetCLSID: TClipFormat = 0; function TTargetCLSIDClipboardFormat.GetClipboardFormat: TClipFormat; begin if (CF_TargetCLSID = 0) then CF_TargetCLSID := RegisterClipboardFormat('TargetCLSID'); // *** DO NOT LOCALIZE *** Result := CF_TargetCLSID; end; function TTargetCLSIDClipboardFormat.GetSize: integer; begin Result := SizeOf(TCLSID); end; function TTargetCLSIDClipboardFormat.HasData: boolean; begin Result := not IsEqualCLSID(FCLSID, GUID_NULL); end; function TTargetCLSIDClipboardFormat.ReadData(Value: pointer; Size: integer): boolean; begin // Validate size. Result := (Size = SizeOf(TCLSID)); if (Result) then FCLSID := PCLSID(Value)^; end; function TTargetCLSIDClipboardFormat.WriteData(Value: pointer; Size: integer): boolean; begin // Validate size. Result := (Size = SizeOf(TCLSID)); if (Result) then PCLSID(Value)^ := FCLSID; end; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // TTextDataFormat // //////////////////////////////////////////////////////////////////////////////// function TTextDataFormat.Assign(Source: TClipboardFormat): boolean; begin Result := True; if (Source is TTextClipboardFormat) then FText := TTextClipboardFormat(Source).Text else if (Source is TFileContentsClipboardFormat) then FText := TFileContentsClipboardFormat(Source).Data else Result := inherited Assign(Source); end; function TTextDataFormat.AssignTo(Dest: TClipboardFormat): boolean; var FGD: TFileGroupDescriptor; FGDW: TFileGroupDescriptorW; resourcestring // Name of the text scrap file. sTextScrap = 'Text scrap.txt'; begin Result := True; if (Dest is TTextClipboardFormat) then TTextClipboardFormat(Dest).Text := FText else if (Dest is TFileContentsClipboardFormat) then TFileContentsClipboardFormat(Dest).Data := FText else if (Dest is TFileGroupDescritorClipboardFormat) then begin FillChar(FGD, SizeOf(FGD), 0); FGD.cItems := 1; StrPLCopy(FGD.fgd[0].cFileName, sTextScrap, SizeOf(FGD.fgd[0].cFileName)); TFileGroupDescritorClipboardFormat(Dest).CopyFrom(@FGD); end else if (Dest is TFileGroupDescritorWClipboardFormat) then begin FillChar(FGDW, SizeOf(FGDW), 0); FGDW.cItems := 1; StringToWideChar(sTextScrap, PWideChar(@(FGDW.fgd[0].cFileName)), MAX_PATH); TFileGroupDescritorWClipboardFormat(Dest).CopyFrom(@FGDW); end else Result := inherited AssignTo(Dest); end; procedure TTextDataFormat.Clear; begin Changing; FText := ''; end; procedure TTextDataFormat.SetText(const Value: string); begin Changing; FText := Value; end; function TTextDataFormat.HasData: boolean; begin Result := (FText <> ''); end; function TTextDataFormat.NeedsData: boolean; begin Result := (FText = ''); end; //////////////////////////////////////////////////////////////////////////////// // // TDataStreamDataFormat // //////////////////////////////////////////////////////////////////////////////// constructor TDataStreamDataFormat.Create(AOwner: TDragDropComponent); begin inherited Create(AOwner); FStreams := TStreamList.Create; FStreams.OnChanging := DoOnChanging; end; destructor TDataStreamDataFormat.Destroy; begin Clear; FStreams.Free; inherited Destroy; end; procedure TDataStreamDataFormat.Clear; begin Changing; FStreams.Clear; end; function TDataStreamDataFormat.HasData: boolean; begin Result := (Streams.Count > 0); end; function TDataStreamDataFormat.NeedsData: boolean; begin Result := (Streams.Count = 0); end; //////////////////////////////////////////////////////////////////////////////// // // TFileDescriptorToFilenameStrings // //////////////////////////////////////////////////////////////////////////////// // Used internally to convert between FileDescriptors and filenames on-demand. //////////////////////////////////////////////////////////////////////////////// type TFileDescriptorToFilenameStrings = class(TStrings) private FFileDescriptors: TMemoryList; protected function Get(Index: Integer): string; override; function GetCount: Integer; override; public constructor Create(AFileDescriptors: TMemoryList); procedure Clear; override; procedure Delete(Index: Integer); override; procedure Insert(Index: Integer; const S: string); override; procedure Assign(Source: TPersistent); override; end; constructor TFileDescriptorToFilenameStrings.Create(AFileDescriptors: TMemoryList); begin inherited Create; FFileDescriptors := AFileDescriptors; end; function TFileDescriptorToFilenameStrings.Get(Index: Integer): string; begin Result := PFileDescriptor(FFileDescriptors[Index]).cFileName; end; function TFileDescriptorToFilenameStrings.GetCount: Integer; begin Result := FFileDescriptors.Count; end; procedure TFileDescriptorToFilenameStrings.Assign(Source: TPersistent); var i: integer; begin if Source is TStrings then begin BeginUpdate; try FFileDescriptors.Clear; for i := 0 to TStrings(Source).Count-1 do Add(TStrings(Source)[i]); finally EndUpdate; end; end else inherited Assign(Source); end; procedure TFileDescriptorToFilenameStrings.Clear; begin FFileDescriptors.Clear; end; procedure TFileDescriptorToFilenameStrings.Delete(Index: Integer); begin FFileDescriptors.Delete(Index); end; procedure TFileDescriptorToFilenameStrings.Insert(Index: Integer; const S: string); var FD: PFileDescriptor; begin if (Index = FFileDescriptors.Count) then begin GetMem(FD, SizeOf(TFileDescriptor)); try FillChar(FD^, SizeOf(TFileDescriptor), 0); StrPLCopy(FD.cFileName, S, SizeOf(FD.cFileName)); FFileDescriptors.Add(FD); except FreeMem(FD); raise; end; end; end; //////////////////////////////////////////////////////////////////////////////// // // TVirtualFileStreamDataFormat // //////////////////////////////////////////////////////////////////////////////// constructor TVirtualFileStreamDataFormat.Create(AOwner: TDragDropComponent); begin inherited Create(AOwner); FFileDescriptors := TMemoryList.Create; FFileNames := TFileDescriptorToFilenameStrings.Create(FFileDescriptors); // Add the "file group descriptor" and "file contents" clipboard formats to // the data format's list of compatible formats. // Note: This is normally done via TCustomDataFormat.RegisterCompatibleFormat, // but since this data format and the clipboard format class are specialized // to be used with each other, it is just as easy for us to add the formats // manually. FFileContentsClipboardFormat := TFileContentsStreamOnDemandClipboardFormat.Create; CompatibleFormats.Add(FFileContentsClipboardFormat); FFileGroupDescritorClipboardFormat := TFileGroupDescritorClipboardFormat.Create; // Normaly TFileGroupDescritorClipboardFormat supports both HGlobal and // IStream storage medium transfers, but for this demo we only use IStream. // FFileGroupDescritorClipboardFormat.FormatEtc.tymed := TYMED_ISTREAM; CompatibleFormats.Add(FFileGroupDescritorClipboardFormat); end; destructor TVirtualFileStreamDataFormat.Destroy; begin FFileDescriptors.Free; FFileNames.Free; inherited Destroy; end; procedure TVirtualFileStreamDataFormat.SetFileNames(const Value: TStrings); begin FFileNames.Assign(Value); end; {$IFOPT R+} {$DEFINE R_PLUS} {$RANGECHECKS OFF} {$ENDIF} function TVirtualFileStreamDataFormat.Assign(Source: TClipboardFormat): boolean; var i: integer; FD: PFileDescriptor; begin Result := True; (* ** TFileContentsStreamOnDemandClipboardFormat *) if (Source is TFileContentsStreamOnDemandClipboardFormat) then begin FHasContents := TFileContentsStreamOnDemandClipboardFormat(Source).HasData; end else (* ** TFileGroupDescritorClipboardFormat *) if (Source is TFileGroupDescritorClipboardFormat) then begin FFileDescriptors.Clear; for i := 0 to TFileGroupDescritorClipboardFormat(Source).FileGroupDescriptor^.cItems-1 do begin GetMem(FD, SizeOf(TFileDescriptor)); try Move(TFileGroupDescritorClipboardFormat(Source).FileGroupDescriptor^.fgd[i], FD^, SizeOf(TFileDescriptor)); FFileDescriptors.Add(FD); except FreeMem(FD); raise; end; end; end else (* ** None of the above... *) Result := inherited Assign(Source); end; {$IFDEF R_PLUS} {$RANGECHECKS ON} {$UNDEF R_PLUS} {$ENDIF} {$IFOPT R+} {$DEFINE R_PLUS} {$RANGECHECKS OFF} {$ENDIF} function TVirtualFileStreamDataFormat.AssignTo(Dest: TClipboardFormat): boolean; var FGD: PFileGroupDescriptor; i: integer; begin (* ** TFileContentsStreamOnDemandClipboardFormat *) if (Dest is TFileContentsStreamOnDemandClipboardFormat) then begin // Let the clipboard format handle the transfer. // No data is actually transferred, but TFileContentsStreamOnDemandClipboardFormat // needs to set a flag when data is requested. Result := Dest.Assign(Self); end else (* ** TFileGroupDescritorClipboardFormat *) if (Dest is TFileGroupDescritorClipboardFormat) then begin if (FFileDescriptors.Count > 0) then begin GetMem(FGD, SizeOf(UINT) + FFileDescriptors.Count * SizeOf(TFileDescriptor)); try FGD.cItems := FFileDescriptors.Count; for i := 0 to FFileDescriptors.Count-1 do Move(FFileDescriptors[i]^, FGD.fgd[i], SizeOf(TFileDescriptor)); TFileGroupDescritorClipboardFormat(Dest).CopyFrom(FGD); finally FreeMem(FGD); end; Result := True; end else Result := False; end else (* ** None of the above... *) Result := inherited AssignTo(Dest); end; {$IFDEF R_PLUS} {$RANGECHECKS ON} {$UNDEF R_PLUS} {$ENDIF} procedure TVirtualFileStreamDataFormat.Clear; begin FFileDescriptors.Clear; FHasContents := False; end; function TVirtualFileStreamDataFormat.HasData: boolean; begin Result := (FFileDescriptors.Count > 0) and ((FHasContents) or Assigned(FFileContentsClipboardFormat.OnGetStream)); end; function TVirtualFileStreamDataFormat.NeedsData: boolean; begin Result := (FFileDescriptors.Count = 0) or (not FHasContents); end; function TVirtualFileStreamDataFormat.GetOnGetStream: TOnGetStreamEvent; begin Result := FFileContentsClipboardFormat.OnGetStream; end; procedure TVirtualFileStreamDataFormat.SetOnGetStream(const Value: TOnGetStreamEvent); begin FFileContentsClipboardFormat.OnGetStream := Value; end; //////////////////////////////////////////////////////////////////////////////// // // TFeedbackDataFormat // //////////////////////////////////////////////////////////////////////////////// function TFeedbackDataFormat.Assign(Source: TClipboardFormat): boolean; begin Result := True; if (Source is TPreferredDropEffectClipboardFormat) then FPreferredDropEffect := TPreferredDropEffectClipboardFormat(Source).Value else if (Source is TPerformedDropEffectClipboardFormat) then FPerformedDropEffect := TPerformedDropEffectClipboardFormat(Source).Value else if (Source is TLogicalPerformedDropEffectClipboardFormat) then FLogicalPerformedDropEffect := TLogicalPerformedDropEffectClipboardFormat(Source).Value else if (Source is TPasteSuccededClipboardFormat) then FPasteSucceded := TPasteSuccededClipboardFormat(Source).Value else if (Source is TTargetCLSIDClipboardFormat) then FTargetCLSID := TTargetCLSIDClipboardFormat(Source).CLSID else if (Source is TInShellDragLoopClipboardFormat) then begin FInShellDragLoop := TInShellDragLoopClipboardFormat(Source).InShellDragLoop; FGotInShellDragLoop := True; end else Result := inherited Assign(Source); end; function TFeedbackDataFormat.AssignTo(Dest: TClipboardFormat): boolean; begin Result := True; if (Dest is TPreferredDropEffectClipboardFormat) then TPreferredDropEffectClipboardFormat(Dest).Value := FPreferredDropEffect else if (Dest is TPerformedDropEffectClipboardFormat) then TPerformedDropEffectClipboardFormat(Dest).Value := FPerformedDropEffect else if (Dest is TLogicalPerformedDropEffectClipboardFormat) then TLogicalPerformedDropEffectClipboardFormat(Dest).Value := FLogicalPerformedDropEffect else if (Dest is TPasteSuccededClipboardFormat) then TPasteSuccededClipboardFormat(Dest).Value := FPasteSucceded else if (Dest is TTargetCLSIDClipboardFormat) then TTargetCLSIDClipboardFormat(Dest).CLSID := FTargetCLSID else if (Dest is TInShellDragLoopClipboardFormat) then TInShellDragLoopClipboardFormat(Dest).InShellDragLoop := FInShellDragLoop else Result := inherited AssignTo(Dest); end; procedure TFeedbackDataFormat.Clear; begin Changing; FPreferredDropEffect := DROPEFFECT_NONE; FPerformedDropEffect := DROPEFFECT_NONE; FInShellDragLoop := False; FGotInShellDragLoop := False; end; procedure TFeedbackDataFormat.SetInShellDragLoop(const Value: boolean); begin Changing; FInShellDragLoop := Value; end; procedure TFeedbackDataFormat.SetPasteSucceded(const Value: longInt); begin Changing; FPasteSucceded := Value; end; procedure TFeedbackDataFormat.SetPerformedDropEffect( const Value: longInt); begin Changing; FPerformedDropEffect := Value; end; procedure TFeedbackDataFormat.SetLogicalPerformedDropEffect( const Value: longInt); begin Changing; FLogicalPerformedDropEffect := Value; end; procedure TFeedbackDataFormat.SetPreferredDropEffect( const Value: longInt); begin Changing; FPreferredDropEffect := Value; end; procedure TFeedbackDataFormat.SetTargetCLSID(const Value: TCLSID); begin Changing; FTargetCLSID := Value; end; function TFeedbackDataFormat.HasData: boolean; begin Result := (FPreferredDropEffect <> DROPEFFECT_NONE) or (FPerformedDropEffect <> DROPEFFECT_NONE) or (FPasteSucceded <> DROPEFFECT_NONE) or (FGotInShellDragLoop); end; function TFeedbackDataFormat.NeedsData: boolean; begin Result := (FPreferredDropEffect = DROPEFFECT_NONE) or (FPerformedDropEffect = DROPEFFECT_NONE) or (FPasteSucceded = DROPEFFECT_NONE) or (not FGotInShellDragLoop); end; //////////////////////////////////////////////////////////////////////////////// // // TGenericClipboardFormat // //////////////////////////////////////////////////////////////////////////////// procedure TGenericClipboardFormat.SetClipboardFormatName(const Value: string); begin FFormat := Value; if (FFormat <> '') then ClipboardFormat := RegisterClipboardFormat(PChar(FFormat)); end; function TGenericClipboardFormat.GetClipboardFormat: TClipFormat; begin if (FFormatEtc.cfFormat = 0) and (FFormat <> '') then FFormatEtc.cfFormat := RegisterClipboardFormat(PChar(FFormat)); Result := FFormatEtc.cfFormat; end; function TGenericClipboardFormat.GetClipboardFormatName: string; begin Result := FFormat; end; function TGenericClipboardFormat.Assign(Source: TCustomDataFormat): boolean; begin if (Source is TGenericDataFormat) then begin Data := TGenericDataFormat(Source).Data; Result := True; end else Result := inherited Assign(Source); end; function TGenericClipboardFormat.AssignTo(Dest: TCustomDataFormat): boolean; begin if (Dest is TGenericDataFormat) then begin TGenericDataFormat(Dest).Data := Data; Result := True; end else Result := inherited AssignTo(Dest); end; //////////////////////////////////////////////////////////////////////////////// // // TGenericDataFormat // //////////////////////////////////////////////////////////////////////////////// procedure TGenericDataFormat.AddFormat(const AFormat: string); var ClipboardFormat: TGenericClipboardFormat; begin ClipboardFormat := TGenericClipboardFormat.Create; ClipboardFormat.ClipboardFormatName := AFormat; ClipboardFormat.DataDirections := [ddRead]; CompatibleFormats.Add(ClipboardFormat); end; procedure TGenericDataFormat.Clear; begin Changing; FData := ''; end; function TGenericDataFormat.HasData: boolean; begin Result := (FData <> ''); end; function TGenericDataFormat.NeedsData: boolean; begin Result := (FData = ''); end; procedure TGenericDataFormat.DoSetData(const Value: string); begin Changing; FData := Value; end; procedure TGenericDataFormat.SetDataHere(const AData; ASize: integer); begin Changing; SetLength(FData, ASize); Move(AData, PChar(FData)^, ASize); end; function TGenericDataFormat.GetSize: integer; begin Result := length(FData); end; function TGenericDataFormat.GetDataHere(var AData; ASize: integer): integer; begin Result := Size; if (ASize < Result) then Result := ASize; Move(PChar(FData)^, AData, Result); end; //////////////////////////////////////////////////////////////////////////////// // // Initialization/Finalization // //////////////////////////////////////////////////////////////////////////////// initialization // Data format registration TTextDataFormat.RegisterDataFormat; TDataStreamDataFormat.RegisterDataFormat; TVirtualFileStreamDataFormat.RegisterDataFormat; // Clipboard format registration TTextDataFormat.RegisterCompatibleFormat(TTextClipboardFormat, 0, csSourceTarget, [ddRead]); TTextDataFormat.RegisterCompatibleFormat(TFileContentsClipboardFormat, 1, csSourceTarget, [ddRead]); TTextDataFormat.RegisterCompatibleFormat(TFileGroupDescritorClipboardFormat, 1, [csSource], [ddRead]); TTextDataFormat.RegisterCompatibleFormat(TFileGroupDescritorWClipboardFormat, 1, [csSource], [ddRead]); TFeedbackDataFormat.RegisterCompatibleFormat(TPreferredDropEffectClipboardFormat, 0, csSourceTarget, [ddRead]); TFeedbackDataFormat.RegisterCompatibleFormat(TPerformedDropEffectClipboardFormat, 0, csSourceTarget, [ddWrite]); TFeedbackDataFormat.RegisterCompatibleFormat(TPasteSuccededClipboardFormat, 0, csSourceTarget, [ddWrite]); TFeedbackDataFormat.RegisterCompatibleFormat(TInShellDragLoopClipboardFormat, 0, csSourceTarget, [ddRead]); TFeedbackDataFormat.RegisterCompatibleFormat(TTargetCLSIDClipboardFormat, 0, csSourceTarget, [ddWrite]); TFeedbackDataFormat.RegisterCompatibleFormat(TLogicalPerformedDropEffectClipboardFormat, 0, csSourceTarget, [ddWrite]); TDataStreamDataFormat.RegisterCompatibleFormat(TFileContentsStreamClipboardFormat, 0, [csTarget], [ddRead]); finalization TTextDataFormat.UnregisterDataFormat; TDataStreamDataFormat.UnregisterDataFormat; TFeedbackDataFormat.UnregisterDataFormat; TVirtualFileStreamDataFormat.UnregisterDataFormat; TTextClipboardFormat.UnregisterClipboardFormat; TFileGroupDescritorClipboardFormat.UnregisterClipboardFormat; TFileGroupDescritorWClipboardFormat.UnregisterClipboardFormat; TFileContentsClipboardFormat.UnregisterClipboardFormat; TFileContentsStreamClipboardFormat.UnregisterClipboardFormat; TPreferredDropEffectClipboardFormat.UnregisterClipboardFormat; TPerformedDropEffectClipboardFormat.UnregisterClipboardFormat; TPasteSuccededClipboardFormat.UnregisterClipboardFormat; TInShellDragLoopClipboardFormat.UnregisterClipboardFormat; TTargetCLSIDClipboardFormat.UnregisterClipboardFormat; TLogicalPerformedDropEffectClipboardFormat.UnregisterClipboardFormat; end.
unit SeniorPercentCalculationForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Db, DBTables; type TSeniorIncomePercentCalculationForm = class(TForm) Label1: TLabel; IncomeEdit: TEdit; Label2: TLabel; OKButton: TBitBtn; SeniorIncomeLevelsTable: TTable; procedure FormShow(Sender: TObject); procedure OKButtonClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } ExemptionPercent : Double; end; var SeniorIncomePercentCalculationForm: TSeniorIncomePercentCalculationForm; implementation {$R *.DFM} uses GlblVars, WinUtils; {========================================================} Procedure TSeniorIncomePercentCalculationForm.FormShow(Sender: TObject); begin try SeniorIncomeLevelsTable.Open; except SystemSupport(001, SeniorIncomeLevelsTable, 'Error opening senior income limits table.', 'SeniorPercentCalculationForm', GlblErrorDlgBox); end; end; {FormShow} {===============================================} Procedure TSeniorIncomePercentCalculationForm.OKButtonClick(Sender: TObject); var Income : LongInt; FoundPercent, Quit, Done, FirstTimeThrough : Boolean; begin Income := 0; Quit := False; try Income := StrToInt(IncomeEdit.Text); except MessageDlg('Please enter an income.', mtError, [mbOK], 0); IncomeEdit.SetFocus; Quit := True; end; If not Quit then begin Done := False; FirstTimeThrough := True; FoundPercent := False; SeniorIncomeLevelsTable.First; repeat If FirstTimeThrough then FirstTimeThrough := False else SeniorIncomeLevelsTable.Next; If SeniorIncomeLevelsTable.EOF then Done := True; If not Done then with SeniorIncomeLevelsTable do If ((Income >= FieldByName('LowLimit').AsInteger) and (Income <= FieldByName('UpperLimit').AsInteger)) then begin ExemptionPercent := FieldByName('Percent').AsFloat; FoundPercent := True; end; until Done; If FoundPercent then ModalResult := mrOK else begin ExemptionPercent := 0; MessageDlg('The income amount $' + IncomeEdit.Text + ' is higher than allowed for a senior exemption.' + #13 + 'This person is not entitled to a senior exemption.', mtError, [mbOK], 0); ModalResult := mrCancel; end; {If not FoundPercent} end; {If not Quit} end; {OKButtonClick} {===================================================================} Procedure TSeniorIncomePercentCalculationForm.FormKeyPress( Sender: TObject; var Key: Char); {CHG04272005-1(2.8.4.4): Remove cancel buttons and allow for Esc instead.} begin (* If (Key = vk_Esc) then Close; *) end; {FormKeyPress} {===================================================================} Procedure TSeniorIncomePercentCalculationForm.FormClose( Sender: TObject; var Action: TCloseAction); begin SeniorIncomeLevelsTable.Close; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC CDS Local SQL adapter } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.CDS.LocalSQL; interface implementation uses System.SysUtils, Datasnap.DBClient, FireDAC.Stan.Factory, FireDAC.Phys.Intf; type TFDCDSLocalSQLAdapter = class (TFDObject, IFDPhysLocalSQLAdapter) private FDataSet: TCustomClientDataSet; protected // private function GetFeatures: TFDPhysLocalSQLAdapterFeatures; function GetCachedUpdates: Boolean; procedure SetCachedUpdates(const AValue: Boolean); function GetSavePoint: Int64; procedure SetSavePoint(const AValue: Int64); function GetIndexFieldNames: String; procedure SetIndexFieldNames(const AValue: String); function GetDataSet: TObject; procedure SetDataSet(ADataSet: TObject); function GetConn: NativeUInt; // public function ApplyUpdates(AMaxErrors: Integer = -1): Integer; procedure CommitUpdates; procedure CancelUpdates; procedure SetRange(const AStartValues, AEndValues: array of const; AStartExclusive: Boolean = False; AEndExclusive: Boolean = False); procedure CancelRange; function IsPKViolation(AExc: Exception): Boolean; end; {-------------------------------------------------------------------------------} { TFDCDSLocalSQLAdapter } {-------------------------------------------------------------------------------} // General function TFDCDSLocalSQLAdapter.GetFeatures: TFDPhysLocalSQLAdapterFeatures; begin Result := [afCachedUpdates, afSavePoints, afIndexFieldNames, afRanges, afFilters]; end; {-------------------------------------------------------------------------------} function TFDCDSLocalSQLAdapter.GetDataSet: TObject; begin Result := FDataSet; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.SetDataSet(ADataSet: TObject); begin FDataSet := ADataSet as TCustomClientDataSet; end; {-------------------------------------------------------------------------------} function TFDCDSLocalSQLAdapter.GetConn: NativeUInt; begin Result := NativeUInt(Pointer(FDataSet.AppServer)); end; {-------------------------------------------------------------------------------} function TFDCDSLocalSQLAdapter.IsPKViolation(AExc: Exception): Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} // Cached Updates management function TFDCDSLocalSQLAdapter.GetCachedUpdates: Boolean; begin Result := FDataSet.LogChanges; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.SetCachedUpdates(const AValue: Boolean); begin FDataSet.LogChanges := AValue; end; {-------------------------------------------------------------------------------} function TFDCDSLocalSQLAdapter.ApplyUpdates(AMaxErrors: Integer): Integer; begin Result := FDataSet.ApplyUpdates(AMaxErrors); end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.CommitUpdates; begin FDataSet.MergeChangeLog; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.CancelUpdates; begin FDataSet.CancelUpdates; end; {-------------------------------------------------------------------------------} function TFDCDSLocalSQLAdapter.GetSavePoint: Int64; begin Result := FDataSet.SavePoint; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.SetSavePoint(const AValue: Int64); begin FDataSet.SavePoint := AValue; end; {-------------------------------------------------------------------------------} // Ranges procedure TFDCDSLocalSQLAdapter.SetRange(const AStartValues, AEndValues: array of const; AStartExclusive, AEndExclusive: Boolean); var i: Integer; begin FDataSet.SetRangeStart; FDataSet.KeyExclusive := AStartExclusive; for i := 0 to High(AStartValues) do FDataSet.IndexFields[i].AssignValue(AStartValues[i]); FDataSet.SetRangeEnd; FDataSet.KeyExclusive := AEndExclusive; for i := 0 to High(AEndValues) do FDataSet.IndexFields[i].AssignValue(AEndValues[i]); FDataSet.ApplyRange; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.CancelRange; begin FDataSet.CancelRange; end; {-------------------------------------------------------------------------------} // Indexes function TFDCDSLocalSQLAdapter.GetIndexFieldNames: String; begin Result := FDataSet.IndexFieldNames; end; {-------------------------------------------------------------------------------} procedure TFDCDSLocalSQLAdapter.SetIndexFieldNames(const AValue: String); begin FDataSet.IndexFieldNames := StringReplace(AValue, ':A', '', [rfReplaceAll]); end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization oFact := TFDMultyInstanceFactory.Create(TFDCDSLocalSQLAdapter, IFDPhysLocalSQLAdapter, 'TCustomClientDataSet'); finalization FDReleaseFactory(oFact); end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Analytics; interface uses System.SysUtils, System.Generics.Collections, System.Classes; {$SCOPEDENUMS ON} type /// <summary>Interface implemented by an object that manages the temporary data cache for logging application /// activity events.</summary> IApplicationActivityCacheManager = interface ['{6145E812-8ECA-4B69-994C-26A81B2A84DC}'] /// <summary>Returns the number of events in the temporary data cache.</summary> function GetCacheCount: Integer; /// <summary>Persists the collected data, either by uploading to a server or writing to a file. Typically this /// function should spawn a background thread for saving the data. If Wait is False, then sending the data can be /// done in the background. If the Wait parameter is True, then all processing should be completed before this /// function returns.</summary> procedure PersistData(const Wait: Boolean); /// <summary>Clears the temporary data cache.</summary> procedure ClearData; /// <summary>Writes an event log message to the data cache.</summary> procedure Log(const AMessage: string); /// <summary>Removes an event from the temporary data cache. If the Index is out of range, then an ERangeError /// exception should be raised.</summary> procedure RemoveEventAtIndex(const Index: Integer); /// <summary>Retrieves the event at the specified index from the temporary event cache. If the Index is out of /// range, then an ERangeError exception should be raised.</summary> function GetEventAtIndex(const Index: Integer): string; /// <summary>Sets an event handler which is fired when the temporary data cache has reached its maximum capacity. /// </summary> procedure SetOnDataCacheFull(const AValue: TNotifyEvent); /// <summary>Retrieves the event handler which is fired when the temporary data cache has reached its maximum /// capacity.</summary> function GetOnDataCacheFull: TNotifyEvent; /// <summary>Sets the maximum size of the temporary data cache.</summary> procedure SetMaxCacheSize(const AValue: Integer); /// <summary>Retrieves the maximum size of the temporary data cache.</summary> function GetMaxCacheSize: Integer; /// <summary>Returns the number of events in the temporary data cache.</summary> property CacheCount: Integer read GetCacheCount; /// <summary>Sets or retrieves the maximum size of the temporary data cache.</summary> property MaxCacheSize: Integer read GetMaxCacheSize write SetMaxCacheSize; /// <summary>Returns the event at the specified index from the temporary data cache.</summary> property Event[const Index: Integer]: string read GetEventAtIndex; /// <summary>Sets or retrieves an event handler which is fired when the temporary data cache has reached its /// maximum capacity.</summary> property OnDataCacheFull: TNotifyEvent read GetOnDataCacheFull write SetOnDataCacheFull; end; /// <summary>Interface that should be implemented by the cache manager if it supports the ability to receive and /// store certain application environment data.</summary> IAppAnalyticsStartupDataRecorder = interface ['{783ED8DB-86BC-41C7-BBD3-443C19468FF1}'] /// <summary>Method to provide the cache manager with system data required by v2 of the AppAnalytics service</summary> procedure AddEnvironmentField(const AKey, AValue: string); end; /// <summary>Interface implemented by an object that wants to receive notification of application activity.</summary> /// <remarks>The "Track" methods are called during the event processing sequence, so it is important that these /// methods be fast and not perform excessive data manipulation. Typically, these events should simply be stored in /// a temporary cache.</remarks> IApplicationActivityListener = interface ['{A67DE237-F274-4028-AAC8-DA0BDA0D5D78}'] /// <summary>Called when a TAppActivity.AppStart event has been recorded.</summary> procedure TrackAppStart(const TimeStamp: TDateTime); /// <summary>Called when a TAppActivity.AppExit event has been recorded.</summary> procedure TrackAppExit(const TimeStamp: TDateTime); /// <summary>Called when a TAppActivity.ControlFocused event has been recorded.</summary> procedure TrackControlFocused(const TimeStamp: TDateTime; const Sender: TObject); /// <summary>Called when a TAppActivity.WindowActivated event has been recorded.</summary> procedure TrackWindowActivated(const TimeStamp: TDateTime; const Sender: TObject); /// <summary>Called when a TAppActivity.Custom event is recorded. Context is an optional object reference which can /// be used to provide additional context about the event.</summary> procedure TrackEvent(const TimeStamp: TDateTime; const Sender, Context: TObject); /// <summary>Called when a TAppActivity.Exception event is recorded.</summary> procedure TrackException(const TimeStamp: TDateTime; const E: Exception); end; /// <summary>Enumeration of the types of events which can ben recorded by an IApplicationActivityListener.</summary> TAppActivity = (AppStart, AppExit, ControlFocused, WindowActivated, Exception, Custom); /// <summary>Set of TAppActivity values. Typically used by an object implementing IApplicationActivityListener to /// indicate the types of events that it will record.</summary> TAppActivityOptions = set of TAppActivity; /// <summary>An object used to record application activities and dispatch notifications to one or more /// IApplicationActivityListener objects. An instance of this manager may be held by the framework's Application /// object. </summary> TAnalyticsManager = class strict private FListeners: TList<IApplicationActivityListener>; function GetTrackingEnabled: Boolean; public /// <summary>Destroys this object and releases references to all IApplicationActivityListener objects that have /// been registered with it.</summary> destructor Destroy; override; /// <summary>Registers an activity listener. The listener will immediately begin receiving application activity /// notifications as they occur. This object will retain a reference to the listener. If the listener was previously /// registered, it will not be registered again.</summary> procedure RegisterActivityListener(const AListener: IApplicationActivityListener); /// <summary>Unregisters an activity listener. This listener will immediately stop receive application activity /// notifications and this object will release its reference to the listener. If the specified listener had not /// been previous registered, no action will be taken.</summary> procedure UnregisterActivityListener(const AListener: IApplicationActivityListener); /// <summary>Records a trackable application activity. All registered activity listeners will be notified.</summary> procedure RecordActivity(const Activity: TAppActivity); overload; /// <summary>Records a trackable application activity. All registered activity listeners will be notified.</summary> procedure RecordActivity(const Activity: TAppActivity; const Sender: TObject); overload; /// <summary>Records a trackable application activity. All registered activity listeners will be notified.</summary> procedure RecordActivity(const Activity: TAppActivity; const Sender: TObject; const Context: TObject); overload; /// <summary>Returns True if at least one listener has been registered. Returns False otherwise.</summary> property TrackingEnabled: Boolean read GetTrackingEnabled; end; /// <summary>An exception type which indicates the initialization of an application activity tracking component /// failed.</summary> EAnalyticsInitializationFailed = class(Exception) end; implementation { TAnalyticsManager } destructor TAnalyticsManager.Destroy; begin FListeners.DisposeOf; inherited; end; procedure TAnalyticsManager.RecordActivity(const Activity: TAppActivity); begin RecordActivity(Activity, nil, nil); end; procedure TAnalyticsManager.RecordActivity(const Activity: TAppActivity; const Sender: TObject); begin RecordActivity(Activity, Sender, nil); end; function TAnalyticsManager.GetTrackingEnabled: Boolean; begin Result := (FListeners <> nil) and (FListeners.Count > 0); end; procedure TAnalyticsManager.RecordActivity(const Activity: TAppActivity; const Sender, Context: TObject); var I: Integer; Time: TDateTime; begin if TrackingEnabled then begin Time := Now; for I := 0 to FListeners.Count - 1 do case Activity of TAppActivity.AppStart: FListeners[I].TrackAppStart(Time); TAppActivity.AppExit: FListeners[I].TrackAppExit(Time); TAppActivity.ControlFocused: FListeners[I].TrackControlFocused(Time, Sender); TAppActivity.WindowActivated: FListeners[I].TrackWindowActivated(Time, Sender); TAppActivity.Exception: begin if Sender is Exception then FListeners[I].TrackException(Time, Exception(Sender)); end; TAppActivity.Custom: FListeners[I].TrackEvent(Time, Sender, Context); end; end; end; procedure TAnalyticsManager.RegisterActivityListener(const AListener: IApplicationActivityListener); begin if FListeners = nil then FListeners := TList<IApplicationActivityListener>.Create; if not FListeners.Contains(AListener) then FListeners.Add(AListener); end; procedure TAnalyticsManager.UnregisterActivityListener(const AListener: IApplicationActivityListener); begin if (FListeners <> nil) and FListeners.Contains(AListener) then FListeners.Remove(AListener); end; end.
unit XmlPreview; 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, cxTextEdit, cxMemo, xmlDoc; type TXmlPreviewDlg = class(TForm) cxMemo1: TcxMemo; procedure cxMemo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure ToDelphiClipboard; { Private declarations } public { Public declarations } procedure SetString(const s: string); end; var XmlPreviewDlg: TXmlPreviewDlg; implementation uses GMGlobals, Vcl.Clipbrd; {$R *.dfm} { TForm1 } procedure TXmlPreviewDlg.ToDelphiClipboard(); var res, s: string; i, n: int; buf: ArrayOfByte; begin s := StringReplace(cxMemo1.Lines.Text, #13#10, '', [rfReplaceAll]); n := Pos('(', s); if n <= 0 then Exit; buf := TextNumbersStringToArray(Copy(s, 1, n - 1)); res := ''''; for i := 0 to High(buf) do begin res := res + IntToHex(buf[i], 2) + ' '; if (i + 1) mod 40 = 0 then res := res + ''' +'#13#10''''; end; res := res + ''''; Clipboard.AsText := res; end; procedure TXmlPreviewDlg.cxMemo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl, ssShift]) and (Key = Ord('C')) then ToDelphiClipboard(); end; procedure TXmlPreviewDlg.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close(); end; procedure TXmlPreviewDlg.SetString(const s: string); var xml: string; begin xml := Trim(s); if (xml <> '') and (xml[1] = '<') then xml := FormatXMLData(xml); cxMemo1.Lines.Text := xml; end; end.
unit osMaquina; interface uses Classes, SysUtils, OsParser, osFuncoesParser, osParserErrorHand; type { Item a ser usado em listas de busca por nome } TItemLookup = class FNome: String; public property Nome: String read FNome write FNome; end; { Listas de busca de item por nome } TListLookup = class(TList) public function LookUp(Nome: String): Pointer; end; { Representa uma variavel da maquina } TVariavelMaquina = class (TItemLookup) FValor: Variant; public constructor Create; overload; constructor Create(pNome: String; pValor: Variant); overload; property Nome: String read FNome write FNome; property Valor: Variant read FValor write FValor; end; { Representa funcao da maquina } TFuncaoCallback = function (Parametros: TList) : Double; TFuncaoStrCallback = function (Parametros: TList) : String; TFuncaoMaquina = class (TItemLookup) FNumeroParametros: Integer; FTipo: Char; FCallBack: TFuncaoCallback; FCallBackStr: TFuncaoStrCallback; public constructor Create(NomeFunc: String; NumParam: Integer; Func: TFuncaoCallback); overload; constructor Create(NomeFunc: String; NumParam: Integer; Func: TFuncaoStrCallback); overload; property Nome: String read FNome; property Tipo: Char read FTipo; property CallBack: TFuncaoCallback read FCallBack; property CallBackStr: TFuncaoStrCallback read FCallBackStr; end; { Maquina virtual para processamento de expressoes aritmeticas } TosMaquina = class FpilhaExec: TStack; // Pilha de execucao FParser: TosParser; FVariaveis: TListLookUp; // Listas de variaveis e funcoes definidas FFuncoes: TListLookUp; FResultado: Double; // Resultado do processamento FResultadoStr: String; // Resultado do processamento FnLinhaProc: Integer; // Linha atual sendo processada FnNumArg: Integer; // Linha de inicio de leitura de argumento FListaErros: TListErro; // Lista de Erros ocorridos FStrings: TStringList; private procedure ProcessaInstrucao(bytecode: Integer; Parametro: String); procedure ProcessaFuncao(NomeFuncao: String); procedure ProcessaOperador(Operador: String); procedure ProcessaOperadorUnario(Operador: String); function RecuperaErro(Index: Integer): TNodoErro; function RecuperaNumeroErros: Integer; function LeVariavel(NomeVar: String): Double; procedure pSetaVariavel(NomeVar: String; Value: Double); public constructor Create; destructor Destroy; override; function Exec: Boolean; // registra funçoes do usuario procedure RegisterUserFunction(Name: string; NumParams: integer; FunctionPointer: TFuncaoCallback); // Cria/atribui valores aa variaveis function SetaVariavel(NomeVar: String; Value: Variant): Boolean; // propriedades property Resultado: Double read FResultado; property ResultadoStr: String read FResultadoStr; property Parser: TosParser read FParser write FParser; property Variavel[NomeVar: String]: Double read LeVariavel write pSetaVariavel; property ListaVariavel: TListLookup read FVariaveis; property ListaErros: TListErro read FListaErros; property Erros[Index: integer]: TNodoErro read RecuperaErro; property nErros: Integer read RecuperaNumeroErros; end; { Tipos possiveis de instrucao da maquina } TTipoInstrucao = (tiFunc = 0, tiArg, tiConstNum, tiConstBool, tiConstString, tiRValue, tiOp, tiOpUn); { Erros possiveis } TerrMaquina = ( emNone = 0, emFaltaParser, emFaltaOperandos, emSobraOperandos, emVariavelIndefinida, emFuncaoIndefinida, emNumParametIncorreto, emErroDoParser, emNomeInvalido, emInstrucaoInvalida, emFaltaResultado, emErroInternoFuncao ); const { Estampas do programa na maquina } Estampas : Array [0..Ord(High(TTipoInstrucao))] of String = (('func'), ('arg'), ('constnum'), ('constbool'), ('conststring'), ('rvalue'), ('op'), ('opun')); implementation uses Variants; { TVariavelMaquina } constructor TVariavelMaquina.Create; begin FNome := ''; FValor := 0; end; constructor TVariavelMaquina.Create(pNome: String; pValor: Variant); begin FNome := pNome; FValor := pValor; end; { TosMaquina } constructor TosMaquina.Create; begin FVariaveis := TListLookup.Create; FFuncoes := TListLookup.Create; FListaErros := TListErro.Create; FParser := nil; FPilhaExec := TStack.Create; // Cria funcoes internas FFuncoes.Add(TFuncaoMaquina.Create('SIN', 1, seno)); FFuncoes.Add(TFuncaoMaquina.Create('COS', 1, cosen)); FFuncoes.Add(TFuncaoMaquina.Create('POW', 2, potencia)); FFuncoes.Add(TFuncaoMaquina.Create('SQRT', 1, raiz)); FFuncoes.Add(TFuncaoMaquina.Create('TEST', 1, teste)); FFuncoes.Add(TFuncaoMaquina.Create('IIF', 3, iif)); FFuncoes.Add(TFuncaoMaquina.Create('SUB', 3, sub)); FFuncoes.Add(TFuncaoMaquina.Create('SIF', 3, sif)); FFuncoes.Add(TFuncaoMaquina.Create('SEL', 3, sel)); FFuncoes.Add(TFuncaoMaquina.Create('NUM', 1, num)); FFuncoes.Add(TFuncaoMaquina.Create('STR', 1, str)); FFuncoes.Add(TFuncaoMaquina.Create('CONCAT', 2, concat)); FFuncoes.Add(TFuncaoMaquina.Create('ROUND', 1, round)); FFuncoes.Add(TFuncaoMaquina.Create('MASC', 2, masc)); FFuncoes.Add(TFuncaoMaquina.Create('EQUAL', 2, equal)); FFuncoes.Add(TFuncaoMaquina.Create('TRIM', 1, trimstr)); FFuncoes.Add(TFuncaoMaquina.Create('MAIUSCULO', 1, maiusculo)); FFuncoes.Add(TFuncaoMaquina.Create('MINUSCULO', 1, minusculo)); FFuncoes.Add(TFuncaoMaquina.Create('INICIAL', 1, inicial)); FFuncoes.Add(TFuncaoMaquina.Create('LOGN', 2, logaritmo)); end; destructor TosMaquina.Destroy; begin FPilhaExec.Free; FVariaveis.Free; FFuncoes.Free; FStrings.Free; end; procedure TosMaquina.RegisterUserFunction(Name: string; NumParams: integer; FunctionPointer: TFuncaoCallback); begin FFuncoes.Add(TFuncaoMaquina.Create(Name, NumParams, FunctionPointer)); end; function TosMaquina.SetaVariavel(NomeVar: String; Value: Variant): Boolean; var Variavel: TVariavelMaquina; begin FListaErros.Clear; { Obrigatorio parser definido porque eh o parser que valida o nome do identificador } if Parser = nil then begin FListaErros.Add(epError, Ord(emFaltaParser), 'Parser indefinido', []); Result := False; Exit; end; Variavel := FVariaveis.LookUp(NomeVar); if Variavel = nil then begin if FFuncoes.LookUp(NomeVar) <> nil then begin FListaErros.Add(epError, Ord(emNomeInvalido), 'Nome dado a variável é nome de uma função.', []); Result := False; Exit; end; if not(Parser.ValidaIdentificador(NomeVar)) then begin FListaErros.Add(epError, Ord(emNomeInvalido), 'Nome invalido para variavel', []); Result := False; Exit; end; FVariaveis.Add(TVariavelMaquina.Create(NomeVar, Value)); end else Variavel.Valor := Value; Result := True; end; { Rotina principal de execucao da maquina virtual } function TosMaquina.Exec: Boolean; var Linha: String; PosInstrucao: Integer; Instrucao: String; bytecode: Integer; begin if Parser = nil then begin // E obrigatorio definir o parser Result := False; FListaErros.Add(epError, Ord(emFaltaParser), 'Parser indefinido.', []); Exit; end; // Remove os erros registrados anteriormente e esvazia pilha de execucao FListaErros.Clear; FPilhaExec.Clear; // Se parser indicar que expressao nao foi compilada, compila-a if not(Parser.Compilado) then begin if not(Parser.Compile) then begin // Erro de parsing FListaErros.Add(epError, Ord(emErroDoParser), 'Erro do parser.', []); Result := False; Exit; end; end; if FParser.Programa.nLinhas = 0 then begin // Programa com 0 linhas, resultado default eh 0 FResultado := 0; Result := True; Exit; end; FnLinhaProc := 0; FnNumArg := 0; // nenhum argumento lido // processa as linhas do programa while FnLinhaProc < FParser.Programa.nLinhas do begin Linha := FParser.Programa.Linhas[FnLinhaProc]; Inc(FnLinhaProc); PosInstrucao := AnsiPos(':', Linha); Instrucao := Copy(Linha, 1, PosInstrucao-1); // determina codigo da instrucao bytecode := 0; while (bytecode <= Ord(High(TTipoInstrucao))) and (Instrucao <> Estampas[bytecode]) do Inc(bytecode); if bytecode > Ord(High(TTipoInstrucao)) then begin FListaErros.Add(epError, Ord(emInstrucaoInvalida), 'Instrucao "%s" invalida encontrada!', [ Instrucao ]); Result := False; Exit; end else begin // copia parametro da instrucao e a processa Instrucao := Copy(Linha, PosInstrucao + 1, Length(Linha) - PosInstrucao); ProcessaInstrucao(bytecode, Instrucao); end; end; if FpilhaExec.Count = 0 then begin // Faltou o resultado na pilha FListaErros.Add(epError, Ord(emFaltaResultado), 'Erro interno: faltou resultado na pilha!', []); Result := False; Exit; end; // Ultimo elemento da pilha deve ser o resultado if FResultadoStr <> '' then begin FpilhaExec.pop; end else begin FResultado := Double(FpilhaExec.pop^); end; if FpilhaExec.Count <> 0 then begin // nao pode sobrar operandos na pilha Result := False; Exit; end; Result := FListaErros.Count = 0; end; procedure TosMaquina.ProcessaInstrucao(bytecode: Integer; Parametro: String); var ValorVar: ^Double; doubleAux: Double; Variavel: TVariavelMaquina; begin case bytecode of ord(tiArg): // numero de argumentos lidos begin // marca a linha onde comeca a leitura de argumentos FnNumArg := StrToInt(Parametro); end; ord(tiFunc): // funcoes begin ProcessaFuncao(Parametro); end; ord(tiOp): // operadores binarios begin ProcessaOperador(Parametro); end; ord(tiOpUn): // operadores unarios begin ProcessaOperadorUnario(Parametro); end; ord(tiConstNum): // constantes numericas begin New(ValorVar); ValorVar^ := StrToFloat(Parametro); FpilhaExec.push(ValorVar); end; ord(tiConstBool): // constantes booleanas begin New(ValorVar); if Parametro = 'TRUE' then ValorVar^ := 1 else ValorVar^ := 0; FpilhaExec.push(ValorVar); end; ord(tiConstString): // constantes string begin if FStrings = nil then FStrings := TStringList.Create; FpilhaExec.push(PChar(FStrings.Strings[ FStrings.Add(StringReplace(Parametro,'"','',[rfReplaceAll]))])); end; ord(tiRValue): // variaveis begin // obter valor variavel Variavel := FVariaveis.LookUp(Parametro); New(ValorVar); if Variavel = nil then begin // variavel inexistente FListaErros.Add(epError, Ord(emVariavelIndefinida), 'Variavel %s nao foi definida', [ Parametro ]); // empilha um valor falso para poder continuar a processar ValorVar^ := 1; end else begin if (not VarIsNull(Variavel.Valor)) then begin if (TryStrToFloat(Variavel.Valor,doubleAux)) and (Pos('ST_', UpperCase(Parametro)) = 0) then begin ValorVar^ := Variavel.Valor; FpilhaExec.push(ValorVar); end else begin if FStrings = nil then FStrings := TStringList.Create; FpilhaExec.push(PChar(FStrings.Strings[ FStrings.Add(Variavel.Valor)])); end; end else begin if FStrings = nil then FStrings := TStringList.Create; Variavel.Valor := ''; FpilhaExec.push(PChar(FStrings.Strings[ FStrings.Add(Variavel.Valor)])); end; end; end; end; end; procedure TosMaquina.ProcessaFuncao(NomeFuncao: String); var Funcao : TFuncaoMaquina; Argumentos : TList; i: Integer; Res: ^Double; PStr: PChar; begin // Procura funcao em questao Funcao := FFuncoes.LookUp(NomeFuncao); // Variavel com resultado a ser empilhado New(Res); if Funcao = nil then begin // Funcao inexistente FListaErros.Add(epError, Ord(emFuncaoIndefinida), 'Funcao %s nao foi definida', [ NomeFuncao ]); // empilha 1 para que possa continuar Res^ := 1; FpilhaExec.push(Res); Exit; end; // confere se numero de argumentos passados esta correto if Funcao.FNumeroParametros <> FnNumArg then begin // Numero incorreto de parametros FListaErros.Add(epError, Ord(emNumParametIncorreto), 'Numero incorreto de parametros para funcao %s. ' + 'Esperava-se %d parametros, mas foram encontrados %d.', [ NomeFuncao, Funcao.FNumeroParametros, FnNumArg ]); // empilha 1 para que possa continuar Res^ := 1; FpilhaExec.push(Res); Exit; end; // desempilha N operandos, sendo N o numero de argumentos i := 0; Argumentos := TList.Create; Argumentos.Capacity := Funcao.FNumeroParametros; while (i < Funcao.FNumeroParametros) and (FpilhaExec.Count > 0) do begin Argumentos.Add(FPilhaExec.pop); inc(i); end; if i < Funcao.FNumeroParametros then begin // Erro interno na pilha: nao foi acumulado qtde correta de parametros FListaErros.Add(epError, Ord(emFaltaOperandos), 'Erro interno executando funcao "%s". Faltaram operandos', [ NomeFuncao ]); Exit; end; // Finalmente, chama a callback e executa a funcao try if Funcao.Tipo = 'D' then begin Res^ := Funcao.CallBack(Argumentos); FpilhaExec.push(Res); end else begin if FStrings = nil then FStrings := TStringList.Create; PStr := PChar(FStrings.Strings[FStrings.Add(Funcao.CallBackStr(Argumentos))]); FpilhaExec.push(PStr); FResultadoStr := PStr; end; except on E: Exception do // Erro interno na chamada da função begin if Copy(E.Message, 1, 1) = '*' then FListaErros.Add(epError, Ord(emErroInternoFuncao), '%s', [E.Message] ) else FListaErros.Add(epError, Ord(emErroInternoFuncao), 'Erro interno executando funcao "%s": %s', [ NomeFuncao, E.Message ]); end; end; Argumentos.Free; end; procedure TosMaquina.ProcessaOperador(Operador: String); var Arg1, Arg2: Double; Aux: double; Res: ^Double; begin New(Res); if (FPilhaExec.Count < 2) then begin // Erro interno na pilha: nao foi acumulado qtde correta de parametros FListaErros.Add(epError, Ord(emFaltaOperandos), 'Erro interno executando operacao "%s". Operandos insuficientes.', [ Operador ]); // empilha 1 para que seja possivel continuar Res^ := 1; FpilhaExec.push(Res); Exit; end; Arg2 := Double(FPilhaExec.pop^); Arg1 := Double(FPilhaExec.pop^); if Operador = '+' then begin Res^ := Arg1+Arg2; FpilhaExec.push(Res); end else if Operador = '-' then begin Res^ := Arg1-Arg2; FpilhaExec.push(Res); end else if Operador = '/' then begin Res^ := Arg1/Arg2; FpilhaExec.push(Res); end else if Operador = '*' then begin Res^ := Arg1*Arg2; FpilhaExec.push(Res); end else if Operador = '>' then begin if Arg1 > Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '<' then begin if Arg1 < Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '<=' then begin if Arg1 <= Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '>=' then begin if Arg1 >= Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '=' then begin if Arg1 = Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '<>' then begin if Arg1 <> Arg2 then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = 'AND' then begin if (Arg1 <> 0) and (Arg2 <> 0) then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = 'OR' then begin if (Arg1 <> 0) or (Arg2 <> 0) then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = 'XOR' then begin if (Arg1 <> 0) xor (Arg2 <> 0) then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = 'MOD' then begin Aux := Trunc(Arg1 / Trunc(Arg2)); Res^ := Trunc(Arg1) - (Aux * Trunc(Arg2)); FpilhaExec.push(Res); end else if Operador = 'DIV' then begin Res^ := Trunc(Arg1 / Trunc(Arg2)); FpilhaExec.push(Res); end; end; procedure TosMaquina.ProcessaOperadorUnario(Operador: String); var Arg: Double; Res: ^Double; begin New(Res); if (FPilhaExec.Count < 1) then begin // Erro interno na pilha: nao foi acumulado qtde correta de parametros FListaErros.Add(epError, Ord(emFaltaOperandos), 'Erro interno executando operacao unaria "%s". Operandos insuficientes.', [ Operador ]); // empilha 1 para que seja possivel continuar Res^ := 1; FpilhaExec.push(Res); Exit; end; Arg := Double(FPilhaExec.pop^); if Operador = 'NOT' then begin if (Arg = 0) then Res^ := 1 else Res^ := 0; FpilhaExec.push(Res); end else if Operador = '+' then begin Res^ := Arg; FpilhaExec.push(Res); end else if Operador = '-' then begin Res^ := -Arg; FpilhaExec.push(Res); end; end; function TosMaquina.RecuperaErro(Index: Integer): TNodoErro; begin Result := FListaErros.Items[Index]; end; function TosMaquina.RecuperaNumeroErros: Integer; begin Result := FListaErros.Count; end; function TosMaquina.LeVariavel(NomeVar: String): Double; var Variavel: TVariavelMaquina; begin Variavel := FVariaveis.LookUp(NomeVar); if Variavel = nil then begin SetaVariavel(NomeVar, 0); Result := 0; end else Result := Variavel.Valor; end; procedure TosMaquina.pSetaVariavel(NomeVar: String; Value: Double); begin if not(SetaVariavel(NomeVar, Value)) then raise Exception.Create('Nome inválido para variável!'); end; { TFuncaoMaquina } constructor TFuncaoMaquina.Create(NomeFunc: String; NumParam: Integer; Func: TFuncaoCallback); begin // tratar nomes invalidos de funcoes FNome := NomeFunc; FNumeroParametros := NumParam; FCallBack := @Func; FTipo := 'D'; end; constructor TFuncaoMaquina.Create(NomeFunc: String; NumParam: Integer; Func: TFuncaoStrCallback); begin FNome := NomeFunc; FNumeroParametros := NumParam; FCallBackStr := @Func; FTipo := 'S'; end; { TListLookup } function TListLookup.LookUp(Nome: String): Pointer; var i: Integer; begin i := 0; while (i < Self.Count) and (Nome <> TItemLookUp(Items[i]).Nome) do inc(i); if i >= Self.Count then Result := nil else Result := Items[i]; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { SOAP Support } { } { Copyright (c) 2001 Borland Software Corporation } { } {*******************************************************} unit SOAPPasInv; interface uses Invoker, TypInfo, Classes, OPConvert, OPToSoapDomConv; type TSoapPascalInvoker = class(TComponent) private procedure SetDomConverter(Value: TOPToSoapDomConvert); protected FConverter: IOPConvert; FDomConverter: TOPToSoapDomConvert; // hard coded to DOM converter procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Invoke(AClass: TClass; IntfInfo: PTypeInfo; MethName: string; const Request: TStream; Response: TStream); virtual; published property Converter: TOPToSoapDomConvert read FDomConverter write SetDomConverter; end; implementation uses SoapConst, InvokeRegistry, SysUtils, InvConst, IntfInfo, ActiveX; constructor TSoapPascalInvoker.Create(AOwner: TComponent); begin inherited Create(AOwner); FDomConverter := TOPToSoapDomConvert.Create(Self); FDomConverter.Name := 'Converter1'; { do not localize } FDomConverter.SetSubComponent(True); FConverter := FDomConverter as IOPConvert; end; destructor TSoapPascalInvoker.Destroy; begin if Assigned(FConverter) then FConverter := nil; if Assigned(FDOMConverter) and (FDomConverter.Owner = Self) then FDomConverter.Free; inherited; end; procedure TSoapPascalInvoker.Invoke(AClass: TClass; IntfInfo: PTypeInfo; MethName: string; const Request: TStream; Response: TStream); var Inv: TInterfaceInvoker; Obj: TObject; InvContext: TInvContext; IntfMD: TIntfMetaData; MethNum: Integer; ExMsg: WideString; begin try CoInitialize(nil); // assumes we are using com dependent stuff (like the MSXML DOM) try MethNum := -1; GetIntfMetaData(IntfInfo, IntfMD, True); InvContext := TInvContext.Create; SetRemotableDataContext(InvContext); try if MethName <> '' then MethNum := GetMethNum(IntfMD, MethName); FConverter.MsgToInvContext(Request, IntfMD, MethNum, InvContext); try Obj := InvRegistry.GetInvokableObjectFromClass(AClass); if Obj = nil then raise Exception.CreateFmt(SNoClassRegistered, [IntfMD.Name]); Inv := TInterfaceInvoker.Create; try Inv.Invoke(Obj, IntfMD, MethNum, InvContext); finally Inv.Free; end; FConverter.MakeResponse(IntfMD, MethNum, InvContext, Response); except on E: Exception do begin ExMsg := FConverter.MakeFault(E); Response.Write(ExMsg[1], Length(ExMsg) * 2); end; end; finally InvContext.Free; SetRemotableDataContext(nil); end; except on E: Exception do begin FConverter := TOPToSoapDomConvert.Create(nil) as IOPConvert; ExMsg := FConverter.MakeFault(E); Response.Write(ExMsg[1], Length(ExMsg) * 2); end; end; finally CoUnInitialize; end; end; procedure TSoapPascalInvoker.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent = FDomConverter) then begin FConverter := nil; FDomConverter := nil; end; end; procedure TSoapPascalInvoker.SetDomConverter(Value: TOPToSoapDomConvert); begin if Assigned(FDOMConverter) and (FDomConverter.Owner = Self) then begin FConverter := nil; FDomConverter.Free; end; FDomConverter := Value; if Value <> nil then begin FConverter := Value; Value.FreeNotification(Self); end; end; end.
unit uUpdateService; interface function UpdateService(ANewFile, AServiceName: string): boolean; function GetServiceAppPath(AServiceName: string): string; function GetServiceVersion(AServiceName: string): string; implementation uses Windows, SysUtils, JwaWinSvc, uGlobal, slmlog, uFileVersionProc; function UpdateService(ANewFile, AServiceName: string): boolean; var F : TextFile; AppExeName: string; strBatFileLine: string; begin result := false; //检测文件是否存在 if not FileExists(ANewFile) then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateService(): File %s not exists.', [ANewFile])); exit; end; //获取服务信息 AppExeName := GetServiceAppPath(AServiceName); //比较版本 if VersionCheck(GetFileVersion(ANewFile), GetFileVersion(AppExeName)) <= 0 then begin SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('UpdateService(): Skip Update, %s Have a new Version', [AServiceName])); DeleteFile(ANewFile); exit; end; //准备批处理文件 SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), '准备批处理文件...'); AssignFile(F, CACHE_PATH + UPDATE_BAT_FILE); ReWrite(F); strBatFileLine := 'net stop ' + AServiceName; SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('| %s', [strBatFileLine])); WriteLn(F, strBatFileLine); strBatFileLine := Format('copy "%s" "%s" /y >> ' + LOG_FILE, [ANewFile, AppExeName, FormatDateTime('yyyy-mm', now)]); SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('| %s', [strBatFileLine])); WriteLn(F, strBatFileLine); strBatFileLine := Format('del "%s"', [ANewFile]); SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('| %s', [strBatFileLine])); WriteLn(F, strBatFileLine); strBatFileLine := 'net start ' + AServiceName; SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('| %s', [strBatFileLine])); WriteLn(F, strBatFileLine); strBatFileLine := Format('del "%s%s"', [CACHE_PATH, UPDATE_BAT_FILE]); SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), Format('| %s', [strBatFileLine])); WriteLn(F, strBatFileLine); CloseFile(F); //执行批处理文件 SaveToLogFile(Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)]), '执行批处理文件...'); //WinExec(PChar(ExtractFilePath(AppExeName) + UPDATE_BAT_FILE + ' >> ' + Format(LOG_FILE, [FormatDateTime('yyyy-mm', now)])), SW_HIDE); WinExec(PChar(Format('"%s%s"', [CACHE_PATH, UPDATE_BAT_FILE])), SW_HIDE); result := true; end; function GetServiceAppPath(AServiceName: string): string; var hSCManager: THandle; hService: THandle; buf: array[0..4096-1] of byte; BytesNeeded: Cardinal; begin result := ''; hSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS); if hSCManager = 0 then exit; hService := OpenService(hSCManager, PChar(AServiceName), SERVICE_ALL_ACCESS); if hService = 0 then exit; ZeroMemory(@buf[0], sizeof(buf)); if not QueryServiceConfig(hService, @buf[0], sizeof(buf), BytesNeeded) then exit; result := PQueryServiceConfig(@buf[0])^.lpBinaryPathName; end; function GetServiceVersion(AServiceName: string): string; begin result := GetFileVersion(GetServiceAppPath(AServiceName)); end; end.
unit Pies; interface uses Classes, Controls, Forms, Graphics, StdCtrls; type TAngles = class(TPersistent) private FStartAngle: Integer; FEndAngle: Integer; FOnChange: TNotifyEvent; procedure SetStart(Value: Integer); procedure SetEnd(Value: Integer); public procedure Assign(Value: TAngles); procedure Changed; published property StartAngle: Integer read FStartAngle write SetStart; property EndAngle: Integer read FEndAngle write SetEnd; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TPie = class(TGraphicControl) FPen: TPen; FBrush: TBrush; FEdit: TEdit; FAngles: TAngles; constructor Create(AOwner: TComponent); override; procedure Paint; override; procedure SetBrush(Value: TBrush); procedure SetPen(Value: TPen); procedure SetAngles(Value: TAngles); procedure StyleChanged(Sender: TObject); published property Angles: TAngles read FAngles write SetAngles; property Brush: TBrush read FBrush write SetBrush; property Pen: TPen read FPen write SetPen; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; implementation uses Windows; procedure TAngles.Assign(Value: TAngles); begin StartAngle := Value.StartAngle; EndAngle := Value.EndAngle; end; procedure TAngles.SetStart(Value: Integer); begin if Value <> FStartAngle then begin FStartAngle := Value; Changed; end; end; procedure TAngles.SetEnd(Value: Integer); begin if Value <> FEndAngle then begin FEndAngle := Value; Changed; end; end; procedure TAngles.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; constructor TPie.Create(AOwner: TComponent); begin inherited Create(AOwner); Width := 100; Height := 100; FPen := TPen.Create; FPen.OnChange := StyleChanged; FBrush := TBrush.Create; FBrush.OnChange := StyleChanged; FAngles := TAngles.Create; FAngles.OnChange := StyleChanged; FAngles.StartAngle := 180; FAngles.EndAngle := 90; end; procedure TPie.StyleChanged(Sender: TObject); begin Invalidate; end; procedure TPie.SetBrush(Value: TBrush); begin FBrush.Assign(Value); end; procedure TPie.SetPen(Value: TPen); begin FPen.Assign(Value); end; procedure TPie.SetAngles(Value: TAngles); begin FAngles.Assign(Value); Invalidate; end; procedure TPie.Paint; var StartA, EndA: Integer; midX, midY, stX, stY, endX, endY: Integer; sX, sY, eX, eY: Real; begin StartA := FAngles.StartAngle; EndA := FAngles.EndAngle; midX := Width div 2; midY := Height div 2; sX := Cos((StartA / 180.0) * pi); sY := Sin((StartA / 180.0) * pi); eX := Cos((EndA / 180.0) * pi); eY := Sin((EndA / 180.0) * pi); stX := Round(sX * 100); stY := Round(sY * 100); endX := Round(eX * 100); endY := Round(eY * 100); with Canvas do begin Pen := FPen; Brush := FBrush; Pie(0,0, Width,Height, midX + stX, midY - stY, midX + endX, midY - endY); end; end; end.
{*********************************************************************** Unit gfx_RotResize.PAS v1.2 0801 (c) by Andreas Moser, amoser@amoser.de, except the Resample function (c) by Anders Melander, anders@melander.dk Delphi version : Delphi 4 gfx_RotResize is part of the gfx_library collection You may use this sourcecode for your freewareproducts. You may modify this source-code for your own use. You may recompile this source-code for your own use. All functions, procedures and classes may NOT be used in commercial products without the permission of the author. For parts of this library not written by me, you have to ask for permission by their respective authors. Disclaimer of warranty: "This software is supplied as is. The author disclaims all warranties, expressed or implied, including, without limitation, the warranties of merchantability and of fitness for any purpose. The author assumes no liability for damages, direct or consequential, which may result from the use of this software." All brand and product names are marks or registered marks of their respective companies. Please report bugs to: Andreas Moser amoser@amoser.de The Resample algorythm is taken from the sources from Bitmap resampler v1.02 release 3, written and (c) by Anders Melander, anders@melander.dk ********************************************************************************} unit gfx_RotResize; interface uses Windows,Classes,Graphics,gfx_basedef; type TFilterProc = function(Value: Single): Single; TResampleCallBack = procedure (const Min,Max,Pos:Integer); TSizeMode= (smUseZoomValue,smOriginal,smFitBoth,smFitWidth,smFitHeight); TCropMode=(crLeft,crRight,crTop,crBottom,CrLeftRight, crTopBottom,crAll); PROCEDURE StretchResize(SrcBitmap,DestBitmap:TBitmap;dWidth,dHeight:LongInt;WithBorder:Boolean;BorderColor:TColor;Thumb:Boolean); PROCEDURE FitResize(SrcBitmap,DestBitmap:TBitmap;dWidth,dHeight:LongInt;WithBorder:Boolean;BorderColor:TColor;Mode:Integer); PROCEDURE RotateBitmap(SrcBitmap,DestBitmap:TBitmap;Degrees,CenterX,CenterY:Integer;EnlargeCanvas:Boolean;BackGrndColor:TColor; ResampleCallback:TResampleCallBack); PROCEDURE FlipBitmap(SrcBitmap,DestBitmap:TBitmap;ResampleCallback:TResampleCallBack); PROCEDURE MirrorBitmap(SrcBitmap,DestBitmap:TBitmap;ResampleCallback:TResampleCallBack); procedure Resample(SrcBitmap, DstBitmap: TBitmap;NewWidth,NewHeight:LongInt;Filter: TFilterProc; fwidth: single; ResampleCallback:TResampleCallBack); procedure CropBitmap(SrcBitmap,DestBitmap:TBitmap;Pixels:Integer;CropMode:TCropMode); procedure CropBitmapToSelection(SrcBitmap,DestBitmap:TBitmap;SelectRect:TRect); procedure EnlargeCanvas(SrcBitmap,DestBitmap:TBitmap;X,Y:Integer;Center:Boolean); // Sample filters for use with Resample() function SplineFilter(Value: Single): Single; function BellFilter(Value: Single): Single; function TriangleFilter(Value: Single): Single; function BoxFilter(Value: Single): Single; function HermiteFilter(Value: Single): Single; function Lanczos3Filter(Value: Single): Single; function MitchellFilter(Value: Single): Single; implementation // ----------------------------------------------------------------------------- // // Stretchresize Bitmap // // ----------------------------------------------------------------------------- PROCEDURE StretchResize(SrcBitmap,DestBitmap:TBitmap;dWidth,dHeight:LongInt;WithBorder:Boolean;BorderColor:TColor;Thumb:Boolean); var aWidth,aHeight,dx,dy,mWidth,mHeight:LongInt; x:Extended; begin aWidth:=SrcBitmap.Width; aHeight:=SrcBitmap.Height; mWidth:=dWidth; mHeight:=dHeight; if (aWidth>=mWidth) or (aHeight>=mHeight) then begin if aWidth> aHeight then begin x:=aWidth/mWidth; aWidth:=mWidth; if x <> 0 then aHeight:=round(aHeight*(1/x)); if aHeight=0 then aHeight:=1; end else begin x:=aHeight/mHeight; aHeight:=mHeight; if x <> 0 then aWidth:=round(aWidth*(1/x)); if aWidth=0 then aWidth:=1; end; if Assigned(DestBitmap) then with DestBitmap do begin PixelFormat:=SrcBitmap.PixelFormat; dx:=0; dy:=0; if WithBorder then begin dx:=Round((mWidth-aWidth)/2); dy:=Round((mHeight-aHeight)/2); end; Width:=mWidth; Height:=mHeight; Canvas.Brush.Color:=BorderColor; Canvas.FillRect(Rect(0,0,mWidth,mHeight)); Canvas.Brush.Color:=clNone; Canvas.CopyMode:=cmSrcCopy; Canvas.StretchDraw(Rect(dx,dy,dx+aWidth,dy+aHeight),SrcBitmap) end; end else if (aWidth<mWidth) and (aHeight<mHeight) then begin // if picture should be shown as thumb, then use the original imagedimensions if Thumb then begin if Assigned(DestBitmap) then with DestBitmap do begin Width:=mWidth; Height:=mHeight; Canvas.Brush.Color:=BorderColor; Canvas.FillRect(Rect(0,0,mWidth,mHeight)); Canvas.Brush.Color:=clNone; Canvas.CopyMode:=cmSrcCopy; Canvas.Draw((mwidth-aWidth )div 2,(mHeight-aHeight )div 2,SrcBitmap); end; end else // otherwise, make result larger than original begin if aWidth> aHeight then begin x:=mWidth/aWidth; aWidth:=mWidth; if x <> 0 then aHeight:=round(aHeight*x); end else begin x:=mHeight/aHeight; aHeight:=mHeight; if x <> 0 then aWidth:=round(aWidth*x); end; if Assigned(DestBitmap) then with DestBitmap do begin dx:=0; dy:=0; if WithBorder then begin dx:=Round((mWidth-aWidth)/2); dy:=Round((mHeight-aHeight)/2); end; Width:=mWidth; Height:=mHeight; Canvas.Brush.Color:=BorderColor; Canvas.FillRect(Rect(0,0,mWidth,mHeight)); Canvas.Brush.Color:=clNone; Canvas.CopyMode:=cmSrcCopy; Canvas.StretchDraw(Rect(dx,dy,dx+aWidth,dy+aHeight),SrcBitmap) end; end; end; end; // ----------------------------------------------------------------------------- // // Stretchresize Bitmap // // ----------------------------------------------------------------------------- PROCEDURE FitResize(SrcBitmap,DestBitmap:TBitmap;dWidth,dHeight:LongInt;WithBorder:Boolean;BorderColor:TColor;Mode:Integer); var aWidth,aHeight,dx,dy,mWidth,mHeight:LongInt; x:Extended; begin if Mode=0 then begin // change nothing DestBitmap.Assign(SrcBitmap); Exit; end; aWidth:=SrcBitmap.Width; aHeight:=SrcBitmap.Height; mWidth:=dWidth; mHeight:=dHeight; // if (aWidth>=mWidth) or (aHeight>=mHeight) then begin x:=1; case Mode of 1:begin // fit both if aWidth> aHeight then begin if aWidth>mWidth then begin x:=aWidth/mWidth; aWidth:=mWidth; if x <> 0 then aHeight:=round(aHeight*(1/x)); mHeight:=aHeight; end else begin x:=mWidth/aWidth; if x <> 0 then aHeight:=round(aHeight*(x)); mHeight:=aHeight; end; end else begin if aHeight>mHeight then begin x:=aHeight/mHeight; aHeight:=mHeight; if x <> 0 then aWidth:=round(aWidth*(1/x)); mWidth:=aWidth; end else begin x:=mHeight/aHeight; if x <> 0 then aWidth:=round(aWidth*(x)); mWidth:=aWidth; end; end; end; 2:begin //fit width if aWidth>mWidth then begin x:=aWidth/mWidth; aWidth:=mWidth; if x <> 0 then aHeight:=round(aHeight*(1/x)); mHeight:=aHeight; end else begin mHeight:=aHeight; mWidth:=aWidth; // x:=mWidth/aWidth; // if x <> 0 then aHeight:=round(aHeight*(x)); end; end; 3:begin //fit height if aHeight>mHeight then begin x:=aHeight/mHeight; aHeight:=mHeight; if x <> 0 then aWidth:=round(aWidth*(1/x)); mWidth:=aWidth; end else begin mHeight:=aHeight; mWidth:=aWidth; end; end; end; if Assigned(DestBitmap) then with DestBitmap do begin PixelFormat:=SrcBitmap.PixelFormat; dx:=0; dy:=0; if WithBorder then begin dx:=Round((mWidth-aWidth)/2); if dx<0 then dx:=0; dy:=Round((mHeight-aHeight)/2); if dy<0 then dy:=0; end; Width:=mWidth; Height:=mHeight; Canvas.Brush.Color:=BorderColor; Canvas.FillRect(Rect(0,0,mWidth,mHeight)); Canvas.Brush.Color:=clNone; Canvas.CopyMode:=cmSrcCopy; Canvas.StretchDraw(Rect(dx,dy,dx+aWidth,dy+aHeight),SrcBitmap) end; end end; // ----------------------------------------------------------------------------- // // Rotate Bitmap // // ----------------------------------------------------------------------------- PROCEDURE RotateBitmap(SrcBitmap,DestBitmap:TBitmap;Degrees,CenterX,CenterY:Integer;EnlargeCanvas:Boolean;BackGrndColor:TColor; ResampleCallback:TResampleCallBack); VAR cosTheta,sinTheta,Theta : DOUBLE; Delta : INTEGER; ecX1,ecY1: Integer; ecX2,ecY2: Integer; ecX3,ecY3: Integer; ecX4,ecY4: Integer; xDiff,yDiff: Integer; minX,maxX:Integer; minY,maxY:Integer; i,j : INTEGER; iSrc,jSrc : INTEGER; iSrcPrime,iDestPrime : INTEGER; jSrcPrime,jDestPrime : INTEGER; SrcRow,DestRow : pRGBArray; function GetRotatedY(OrgX,OrgY:Integer;SinTheta,CosTheta:Double):Integer; begin Result:=(ROUND((2*(OrgX) + 1) * sinTheta + (2*(OrgY) + 1) * cosTheta) - 1) div 2; end; function GetRotatedX(OrgX,OrgY:Integer;SinTheta,CosTheta:Double):Integer; begin Result:=(ROUND((2*(OrgX) + 1) * CosTheta - (2*(OrgY) + 1) * sinTheta) - 1) div 2; end; begin SrcBitmap.PixelFormat := pf24bit; DestBitmap.PixelFormat := pf24bit; Theta := -Degrees * PI / 180; sinTheta := SIN(Theta); cosTheta := COS(Theta); if EnlargeCanvas then begin ecX1 := GetRotatedX(0,0,SinTheta,CosTheta); ecY1 := GetRotatedY(0,0,SinTheta,CosTheta); ecX2 := GetRotatedX(SrcBitmap.Width,0,SinTheta,CosTheta); ecY2 := GetRotatedY(SrcBitmap.Width,0,SinTheta,CosTheta); ecX3 := GetRotatedX(SrcBitmap.Width,SrcBitmap.Height,SinTheta,CosTheta); ecY3 := GetRotatedY(SrcBitmap.Width,SrcBitmap.Height,SinTheta,CosTheta); ecX4 := GetRotatedX(0,SrcBitmap.Height,SinTheta,CosTheta); ecY4 := GetRotatedY(0,SrcBitmap.Height,SinTheta,CosTheta); if ecX1>=ecX2 then begin maxX:=ecX1;minX:=ecX2;end else begin maxX:=ecX2;minX:=ecX1; end; if ecY1>=ecY2 then begin maxY:=ecY1;minY:=ecY2;end else begin maxY:=ecY2;minY:=ecY1; end; if ecX3>=maxX then maxX:=ecX3 else if ecX3<=minX then minX:=ecX3; if ecY3>=maxY then maxY:=ecY3 else if ecY3<=minY then minY:=ecY3; if ecX4>=maxX then maxX:=ecX4 else if ecX4<=minX then minX:=ecX4; if ecY4>=maxY then maxY:=ecY4 else if ecY4<=minY then minY:=ecY4; DestBitmap.Width:=Abs(MaxX-MinX); DestBitmap.Height:=Abs(MaxY-MinY); XDiff :=(DestBitmap.Width-SrcBitmap.Width) div 2; YDiff :=(DestBitmap.height-SrcBitmap.Height) div 2; end else begin DestBitmap.Width := SrcBitmap.Width; DestBitmap.Height := SrcBitmap.Height; yDiff:=0; xDiff:=0; end; FOR j := DestBitmap.Height-1 DOWNTO 0 DO BEGIN DestRow := DestBitmap.Scanline[j]; jSrcPrime := 2*(j - (YDiff+CenterY)) + 1; if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round(((DestBitmap.Height-j)/DestBitmap.Height)*100)); FOR i := DestBitmap.Width-1 DOWNTO 0 DO BEGIN iSrcPrime := 2*(i - (XDiff+CenterX)) + 1; iDestPrime := ROUND(iSrcPrime * CosTheta - jSrcPrime * sinTheta); jDestPrime := ROUND(iSrcPrime * sinTheta + jSrcPrime * cosTheta); iSrc := (iDestPrime - 1) div 2 + CenterX; jSrc := (jDestPrime - 1) div 2 + CenterY; IF (iSrc >= 0) AND (iSrc <= SrcBitmap.Width-1) AND (jSrc >= 0) AND (jSrc <= SrcBitmap.Height-1) THEN BEGIN SrcRow := SrcBitmap.Scanline[jSrc]; DestRow[i] := SrcRow[iSrc] END ELSE WITH DestRow[i] DO BEGIN rgbtBlue := (BackgrndColor and $00ff0000) shr 16; rgbtGreen := (BackgrndColor and $0000ff00) shr 8; rgbtRed := (BackgrndColor and $000000ff); END END END; END; // ----------------------------------------------------------------------------- // // Flip Bitmap // // ----------------------------------------------------------------------------- PROCEDURE FlipBitmap(SrcBitmap,DestBitmap:TBitmap;ResampleCallback:TResampleCallBack); var i,j :Integer; SrcRow,DestRow :pRGBArray; begin SetBitmapsEql(SrcBitmap,DestBitmap); for i:=DestBitmap.Height-1 downto 0 do begin SrcRow:=SrcBitmap.ScanLine[DestBitmap.Height-i-1]; DestRow:=DestBitmap.ScanLine[i]; if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((i/SrcBitmap.Height)*100)); for j:=0 to DestBitmap.Width-1 do begin DestRow[j].rgbtBlue:=SrcRow[j].rgbtBlue; DestRow[j].rgbtGreen:=SrcRow[j].rgbtGreen; DestRow[j].rgbtRed:=SrcRow[j].rgbtRed; end; end; end; // ----------------------------------------------------------------------------- // // Mirror Bitmap // // ----------------------------------------------------------------------------- PROCEDURE MirrorBitmap(SrcBitmap,DestBitmap:TBitmap;ResampleCallback:TResampleCallBack); var i,j :Integer; SrcRow,DestRow :pRGBArray; begin SetBitmapsEql(SrcBitmap,DestBitmap); for i:=DestBitmap.Height-1 downto 0 do begin SrcRow:=SrcBitmap.ScanLine[i]; DestRow:=DestBitmap.ScanLine[i]; if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((i/SrcBitmap.Height)*100)); for j:=0 to DestBitmap.Width-1 do begin DestRow[j].rgbtBlue:=SrcRow[SrcBitmap.Width-j-1].rgbtBlue; DestRow[j].rgbtGreen:=SrcRow[SrcBitmap.Width-j-1].rgbtGreen; DestRow[j].rgbtRed:=SrcRow[SrcBitmap.Width-j-1].rgbtRed; end; end; end; { RESAMPLE PART } // ----------------------------------------------------------------------------- // // Filter functions // (c) by Anders Melander, anders@melander.dk // ----------------------------------------------------------------------------- // Hermite filter function HermiteFilter(Value: Single): Single; begin // f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 if (Value < 0.0) then Value := -Value; if (Value < 1.0) then Result := (2.0 * Value - 3.0) * Sqr(Value) + 1.0 else Result := 0.0; end; // Box filter // a.k.a. "Nearest Neighbour" filter // anme: I have not been able to get acceptable // results with this filter for subsampling. function BoxFilter(Value: Single): Single; begin if (Value > -0.5) and (Value <= 0.5) then Result := 1.0 else Result := 0.0; end; // Triangle filter function TriangleFilter(Value: Single): Single; begin if (Value < 0.0) then Value := -Value; if (Value < 1.0) then Result := 1.0 - Value else Result := 0.0; end; // Bell filter function BellFilter(Value: Single): Single; begin if (Value < 0.0) then Value := -Value; if (Value < 0.5) then Result := 0.75 - Sqr(Value) else if (Value < 1.5) then begin Value := Value - 1.5; Result := 0.5 * Sqr(Value); end else Result := 0.0; end; // B-spline filter function SplineFilter(Value: Single): Single; var tt : single; begin if (Value < 0.0) then Value := -Value; if (Value < 1.0) then begin tt := Sqr(Value); Result := 0.5*tt*Value - tt + 2.0 / 3.0; end else if (Value < 2.0) then begin Value := 2.0 - Value; Result := 1.0/6.0 * Sqr(Value) * Value; end else Result := 0.0; end; // Lanczos3 filter function Lanczos3Filter(Value: Single): Single; function SinC(Value: Single): Single; begin if (Value <> 0.0) then begin Value := Value * Pi; Result := sin(Value) / Value end else Result := 1.0; end; begin if (Value < 0.0) then Value := -Value; if (Value < 3.0) then Result := SinC(Value) * SinC(Value / 3.0) else Result := 0.0; end; function MitchellFilter(Value: Single): Single; const B = (1.0 / 3.0); C = (1.0 / 3.0); var tt : single; begin if (Value < 0.0) then Value := -Value; tt := Sqr(Value); if (Value < 1.0) then begin Value := (((12.0 - 9.0 * B - 6.0 * C) * (Value * tt)) + ((-18.0 + 12.0 * B + 6.0 * C) * tt) + (6.0 - 2 * B)); Result := Value / 6.0; end else if (Value < 2.0) then begin Value := (((-1.0 * B - 6.0 * C) * (Value * tt)) + ((6.0 * B + 30.0 * C) * tt) + ((-12.0 * B - 48.0 * C) * Value) + (8.0 * B + 24 * C)); Result := Value / 6.0; end else Result := 0.0; end; procedure Resample(SrcBitmap, DstBitmap: TBitmap;NewWidth,NewHeight:LongInt;Filter: TFilterProc; fwidth: single; ResampleCallback:TResampleCallBack); // ----------------------------------------------------------------------------- // // Interpolator // based on algorythm from Anders Melander, anders@melander.dk // ----------------------------------------------------------------------------- type // Contributor for a pixel TContributor = record pixel: integer; // Source pixel weight: single; // Pixel weight end; TContributorList = array[0..0] of TContributor; PContributorList = ^TContributorList; // List of source pixels contributing to a destination pixel TCList = record n : integer; p : PContributorList; end; TCListList = array[0..0] of TCList; PCListList = ^TCListList; TRGB = packed record r, g, b : single; end; // Physical bitmap scanline (row) TRGBList = packed array[0..0] of TColorRGB; PRGBList = ^TRGBList; var xscale, yscale : single; // Zoom scale factors i, j, k : integer; // Loop variables center : single; // Filter calculation variables width, fscale, weight : single; // Filter calculation variables left, right : integer; // Filter calculation variables n : integer; // Pixel number Work : TBitmap; // Temporary Bitmap contrib : PCListList; // Contributor pointer rgb : TRGB; // RGBTriple color : TColorRGB; // COlorRGBTriple SourceLine , DestLine : PRGBList; SourcePixel , DestPixel : PColorRGB; Delta , DestDelta : integer; SrcWidth , SrcHeight , DstWidth , DstHeight : integer; sMode : Boolean; begin DstWidth := NewWidth; DstHeight := NewHeight; DstBitmap.Width:=NewWidth; DstBitmap.Height:=NewHeight; SrcWidth := SrcBitmap.Width; SrcHeight := SrcBitmap.Height; if (SrcWidth < 1) or (SrcHeight < 1) then exit; Work := TBitmap.Create; try Work.Height := SrcHeight; Work.Width := DstWidth; if (SrcWidth = 1) then xscale:= DstWidth / SrcWidth else xscale:= (DstWidth - 1) / (SrcWidth - 1); if (SrcHeight = 1) then yscale:= DstHeight / SrcHeight else yscale:= (DstHeight - 1) / (SrcHeight - 1); SrcBitmap.PixelFormat := pf24bit; DstBitmap.PixelFormat := SrcBitmap.PixelFormat; Work.PixelFormat := SrcBitmap.PixelFormat; //----------------------------------------------------------- // // HORIZONTAL PART // // //----------------------------------------------------------- // -------------------------------------------- // Pre-calculate filter contributions for a row // ----------------------------------------------- GetMem(contrib, DstWidth* sizeof(TCList)); // Horizontal sub-/supersampling // set different modes depending on scaling factor sMode:=xscale < 1.0; if sMode then width := fwidth / xscale else width:=fWidth; if sMode then fscale := 1.0 / xscale else fScale:=1; for i := 0 to DstWidth-1 do begin if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((i/DstWidth)*100)); contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(width * 2.0 + 1) * sizeof(TContributor)); center := i / xscale; left := xFloor(center - width); right := xCeil(center + width); for j := left to right do begin weight := filter((center - j) / fscale) / fscale; if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcWidth) then n := SrcWidth - j + SrcWidth - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; // ---------------------------------------------------- // Apply filter to sample horizontally from Src to Work // ---------------------------------------------------- for k := 0 to SrcHeight-1 do begin if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((k/SrcHeight)*100)); SourceLine := SrcBitmap.ScanLine[k]; DestPixel := Work.ScanLine[k]; for i := 0 to DstWidth-1 do begin rgb.r := 0.0; rgb.g := 0.0; rgb.b := 0.0; for j := 0 to contrib^[i].n-1 do begin color := SourceLine^[contrib^[i].p^[j].pixel]; weight := contrib^[i].p^[j].weight; if (weight = 0.0) then continue; rgb.r := rgb.r + color.r * weight; rgb.g := rgb.g + color.g * weight; rgb.b := rgb.b + color.b * weight; end; color.r:=TrimReal(0,255,RGB.r); color.g:=TrimReal(0,255,RGB.g); color.b:=TrimReal(0,255,RGB.b); // Set new pixel value DestPixel^ := color; // Move on to next column inc(DestPixel); end; end; // Free the memory (horizontal filter weights) for i := 0 to DstWidth-1 do FreeMem(contrib^[i].p); FreeMem(contrib); //----------------------------------------------------------- // // VERTICAL PART // // //----------------------------------------------------------- // ----------------------------------------------- // Pre-calculate filter contributions for a column // ----------------------------------------------- GetMem(contrib, DstHeight* sizeof(TCList)); // Vertical sub-/supersampling sMode:=yscale < 1.0; if sMode then width := fwidth / yscale else width:=fWidth; if sMode then fscale := 1.0 / yscale else fScale:=1; for i := 0 to DstHeight-1 do begin if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((i/DstHeight)*100)); contrib^[i].n := 0; GetMem(contrib^[i].p, trunc(width * 2.0 + 1) * sizeof(TContributor)); center := i / yscale; left := xFloor(center - width); right := xCeil(center + width); for j := left to right do begin weight := filter((center - j) / fscale) / fscale; if (weight = 0.0) then continue; if (j < 0) then n := -j else if (j >= SrcHeight) then n := SrcHeight - j + SrcHeight - 1 else n := j; k := contrib^[i].n; contrib^[i].n := contrib^[i].n + 1; contrib^[i].p^[k].pixel := n; contrib^[i].p^[k].weight := weight; end; end; // -------------------------------------------------- // Apply filter to sample vertically from Work to Dst // -------------------------------------------------- SourceLine := Work.ScanLine[0]; Delta := integer(Work.ScanLine[1]) - integer(SourceLine); DestLine := DstBitmap.ScanLine[0]; DestDelta := integer(DstBitmap.ScanLine[1]) - integer(DestLine); for k := 0 to DstWidth-1 do begin if Assigned(ResampleCallBack) then ResampleCallBack(0,100,Round((k/DstWidth)*100)); DestPixel := pointer(DestLine); for i := 0 to DstHeight-1 do begin rgb.r := 0; rgb.g := 0; rgb.b := 0; for j := 0 to contrib^[i].n-1 do begin color := PColorRGB(integer(SourceLine)+contrib^[i].p^[j].pixel*Delta)^; weight := contrib^[i].p^[j].weight; if (weight = 0.0) then continue; rgb.r := rgb.r + color.r * weight; rgb.g := rgb.g + color.g * weight; rgb.b := rgb.b + color.b * weight; end; color.r:=TrimReal(0,255,RGB.r); color.g:=TrimReal(0,255,RGB.g); color.b:=TrimReal(0,255,RGB.b); DestPixel^ := color; inc(integer(DestPixel), DestDelta); end; Inc(SourceLine, 1); Inc(DestLine, 1); end; // Free the memory (vertical filter weights) for i := 0 to DstHeight-1 do FreeMem(contrib^[i].p); FreeMem(contrib); finally Work.Free; end; end; procedure EnlargeCanvas(SrcBitmap,DestBitmap:TBitmap;X,Y:Integer;Center:Boolean); begin SetBitmapsEql(SrcBitmap,DestBitmap); DestBitmap.Width:=X; DestBitmap.Height:=Y; if not Center then begin DestBitmap.Canvas.Draw(0,0,SrcBitmap); end else begin DestBitmap.Canvas.Draw((DestBitmap.Width-SrcBitmap.Width)div 2 , (DestBitmap.Height-SrcBitmap.Height) div 2 , SrcBitmap); end; end; procedure CropBitmap(SrcBitmap,DestBitmap:TBitmap;Pixels:Integer;CropMode:TCropMode); var x1,x2:Integer; y1,y2:Integer; SrcRect, DestRect: TRect; begin SetBitmapsEql(SrcBitmap,DestBitmap); x1:=0; x2:=0; y1:=0; y2:=0; case CropMode of crLeft: x1:=Pixels; crRight:x2:=Pixels; crTop:y1:=Pixels; crBottom:y2:=Pixels; crTopBottom: begin y1:=Pixels; y2:=Pixels; end; crLeftRight: begin x1:=Pixels; x2:=Pixels; end; crAll: begin y1:=Pixels; y2:=Pixels; x1:=Pixels; x2:=Pixels; end; end; DestBitmap.Width:=SrcBitmap.Height-x1-x2; DestBitmap.Height:=SrcBitmap.Width-y1-y2; DestRect:=Rect(0,0,DestBitmap.Width,DestBitmap.Height); SrcRect:=Rect(x1,y1,SrcBitmap.Width-x2,SrcBitmap.Height-y2); DestBitmap.Canvas.CopyRect(DestRect,SrcBitmap.Canvas,SrcRect); end; procedure CropBitmapToSelection(SrcBitmap,DestBitmap:TBitmap;SelectRect:TRect); var x1,x2:Integer; y1,y2:Integer; SrcRect, DestRect: TRect; begin SetBitmapsEql(SrcBitmap,DestBitmap); DestBitmap.Width:=SelectRect.Right-SelectRect.Left; DestBitmap.Height:=SelectRect.Bottom-SelectRect.Top; DestRect:=Rect(0,0,DestBitmap.Width,DestBitmap.Height); DestBitmap.Canvas.CopyRect(DestRect,SrcBitmap.Canvas,SelectRect); end; end.
UNIT WishListUnit; INTERFACE TYPE WishNodePtr = ^WishNode; PersonNodePtr = ^PersonNode; WishNode = record prev, next: WishNodePtr; wish: string; n: integer; (*number of occurences of the wish*) children: PersonNodePtr; end; (*RECORD*) PersonNode = record next: PersonNodePtr; childName: string; end; (* RECORD *) WishList = WishNodePtr; PersonList = PersonNodePtr; PROCEDURE AddPresent(var wl: WishList; childName: string; present: string); PROCEDURE WriteWishList(wl: WishList); PROCEDURE NewWishList(var wl: WishList); IMPLEMENTATION PROCEDURE WritePersonList(pl: PersonList); BEGIN (* WritePersonList *) while pl <> NIL do begin Write(pl^.childName, ' '); pl := pl^.next; end; END; (* WritePersonList *) PROCEDURE WriteWishList(wl: WishList); var cur: WishNodePtr; BEGIN wl^.wish := ''; cur := wl^.next; while cur^.wish <> '' do begin Write(cur^.n, '*', cur^.wish, ': '); WritePersonList(cur^.children); WriteLn(); cur := cur^.next; end; (* WHILE *) END; PROCEDURE NewWishList(var wl: WishList); BEGIN (* NewWishList *) New(wl); wl^.wish := ''; wl^.n := 0; wl^.children := NIL; wl^.next := wl; wl^.prev := wl; END; (* NewWishList *) FUNCTION FindWishNode(l: WishList; present: string): WishNodePtr; var node: WishNodePtr; BEGIN (* FindWishNode *) node := l^.next; l^.wish := present; if node <> NIL then begin while node^.wish <> present do node := node^.next; if node = l then FindWishNode := NIL else FindWishNode := node; end else FindWishNode := NIL; END; (* FindWishNode *) FUNCTION FindChildNode(l: PersonList; childName: string): PersonNodePtr; BEGIN (* FindChildNode *) while (l <> NIL) AND (l^.childName <> childName) do l := l^.next; FindChildNode := l; END; (* FindChildNode *) PROCEDURE AppendPersonList(var l: PersonList; n: PersonNodePtr); var cur: PersonNodePtr; BEGIN (* AppendPersonList *) if l = NIL then l := n else begin cur := l; while cur^.next <> nil do cur := cur^.next; cur^.next := n; end; END; (* AppendPersonList *) PROCEDURE NewPersonNode(var l: PersonList; childName: string); var node: PersonNodePtr; BEGIN (* NewPersonNode *) New(node); node^.childName := childName; node^.next := NIL; AppendPersonList(l, node); END; (* NewPersonNode *) PROCEDURE AppendWishList(var l: WishList; n: WishNodePtr); BEGIN (* AppendWishList *) n^.prev := l^.prev; n^.next := l; l^.prev^.next := n; l^.prev := n; END; (* AppendWishList *) PROCEDURE NewWishNode(var l: WishList; present: string); var node: WishNodePtr; BEGIN (* NewWishNode *) New(node); node^.wish := present; node^.n := 1; node^.prev := NIL; node^.next := NIL; AppendWishList(l, node); END; (* NewWishNode *) PROCEDURE AddPresent(var wl: WishList; childName: string; present: string); var presentNode: WishNodePtr; childNode: PersonNodePtr; BEGIN presentNode := FindWishNode(wl, present); if presentNode <> NIL then begin Inc(presentNode^.n); childNode := FindChildNode(presentNode^.children, childName); if childNode = NIL then begin NewPersonNode(presentNode^.children, childName); end; (* IF *) end else begin NewWishNode(wl, present); presentNode := FindWishNode(wl, present); if presentNode <> NIL then begin childNode := FindChildNode(presentNode^.children, childName); if childNode = NIL then begin NewPersonNode(presentNode^.children, childName); end; (* IF *) end; (* IF *) end; (* IF *) END; BEGIN (* WishListUnit *) END. (* WishListUnit *)
unit keyb_obj; { OOP keyboard unit. Uses the BIOS whenever possible for maximum compatibility (this may be a factor in supporting Tandy 1000 and PCjr properly). Targeted towards the lowest-common denominator (83-key keyboard) for maximum audience. } {{DEFINE TRUEIBM} {if you don't care about clones, define this for max speed} interface uses objects; type ScanCodeArray=Array [0..127] Of Boolean; {table for 128 scan codes} LabelString=string[32]; KeyType=record scancode,flags,ASCII:byte; keylabel:labelstring; end; PKeyboard=^TKeyboard; TKeyboard=object(TObject) LastKeyPressed:KeyType; ScanCodes:^scancodearray; Constructor Init; Destructor Done; virtual; Procedure HookInterrupt; Procedure UnhookInterrupt; Function Keypressed:boolean; Function HumanReadable(scancode,flags:byte):labelstring; {turns scancode+flags into human-readble string} private Hooked:boolean; {whether or not we're intercepting the BIOS keyboard interrupt} end; implementation uses dos, strings; var kbd:ScanCodeArray; old9:Procedure; const maxLabel=132; { KeyLabels is a human-readable label of the key pressed, indexed by scancode. It is neither perfect nor complete because not all BIOSes will produce codes for every combination. For example, the IBM PC/XT 5160 BIOS will not produce Control-Insert or Control-=; catching those particular combinations requires hooking the keyboard interrupt and processing them on your own. The following table was determined through empirical evidence (ie. I pressed every single key combo and recorded the result) on an IBM PC/XT keyboard and IBM PC/XT 5160 BIOS. While not complete (AT BIOSes and keyboards produce more combinations), it is an adequate baseline for all computers claiming "IBM PC compatibility" including the Compaq, AT&T PC 6300, Amstrad, and other "xt clones". } KeyLabels:array[0..maxLabel] of PChar=( '(undefined)', {we should never see 0 unless user is screwing around with alt-keypad} 'Esc','1','2','3','4','5','6','7','8','9','0','-','=','BackSpace', 'Tab','Q','W','E','R','T','Y','U','I','O','P','[',']','Enter','', 'A','S','D','F','G','H','J','K','L',';','''','`','', '\','Z','X','C','V','B','N','M',',','.','/','', '*','', 'SpaceBar','CapsLock', 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10','NumLock','ScrollLock', 'Home','Up','PgUp','kMinus', 'Left','k5','Right','kPlus', 'End','Down','PgDn', 'Ins','Del', {what follows are the result of key combos for non-ascii-producing keys} 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10', 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10', 'F1','F2','F3','F4','F5','F6','F7','F8','F9','F10','PrtSc', 'Left','Right','End','PgDn','Home', '1','2','3','4','5','6','7','8','9','0','-','=', 'PgUp' ); RSHPressed=1; LSHPressed=2; CTLPressed=4; ALTPressed=8; Procedure New9handler; interrupt; var port60h:byte; begin port60h:=port[$60]; kbd[port60h and $7f] := (port60h < 128); { record current status } asm pushf; end; { must precede call to old int } old9; { call old interrupt } asm cli; end; { disable hardware interrupts } memw[$0040:$001a] := memw[$0040:$001c]; { clear the keyboard buffer } asm sti; end; { enable hardware interrupts } end; Constructor TKeyboard.Init; begin Hooked:=false; ScanCodes:=@kbd; {pointer to interrupt-routine scancode array from KEYBOARD unit} with LastKeyPressed do begin scancode:=0; flags:=0; ASCII:=0; keylabel:=''; end; end; Destructor TKeyboard.Done; begin if hooked then UnHookInterrupt; end; Procedure TKeyboard.HookInterrupt; begin FillChar (kbd, 128, 0); { fill the keyboard table with false } GetIntVec ($09, @old9); SetIntVec ($09, @New9handler); Hooked:=true; end; Procedure TKeyboard.UnhookInterrupt; begin SetIntVec ($09, @old9); Hooked:=false; end; Function TKeyboard.HumanReadable; var foo:labelstring; begin foo:=StrPas(KeyLabels[scancode]); if (flags and RSHPressed)=RSHPressed then foo:='RShift+'+foo; if (flags and LSHPressed)=LSHPressed then foo:='LShift+'+foo; if (flags and CTLPressed)=CTLPressed then foo:='Ctrl+'+foo; if (flags and ALTPressed)=ALTPressed then foo:='Alt+'+foo; HumanReadable:=foo; end; Function TKeyboard.Keypressed:boolean; Function kbd_keypressed:boolean; var loop:byte; begin kbd_keypressed:=false; {assume "no"} for loop:=0 to 127 do begin if kbd[loop] then begin kbd_keypressed:=true; break; {exit out of loop} end; end; end; var localpress:boolean; loop, lkps,lkpa,lkpf:byte; {this is necessary because I don't understand how to deal with the Self pointer + OOP + BASM. All suggestions appreciated!} begin if Hooked {if keyboard int hooked, call custom hook; otherwise, call BIOS} then begin localpress:=false; for loop:=0 to 127 do if kbd[loop] then begin localpress:=true; break; {exit out of loop} end; end else begin {procedure to get keyboard status from BIOS and stick in lastkey} asm mov localpress,0 {assume false} mov ah,01h {get keyboard status} int 16h jz @done {if zf set, no key was pressed} inc localpress {1=true} mov lkps,ah {store scancode} mov lkpa,al {store ascii value} mov ah,2 int 16h {Read Keyboard Flags} and al,00001111b; {we don't care about caps/num/etc. status} mov lkpf,al {store flags} xor ax,ax {$IFDEF TRUEIBM} mov es,ax mov bx,0417h mov es:[bx],al {manipulates queue size} {$ELSE} int 16h {read key to get it out of BIOS/buffer and discard} {$ENDIF} @done: end; if localpress then begin with LastKeyPressed do begin flags:=lkpf; ascii:=lkpa; scancode:=lkps; {now that we've got our scancode, lkps becomes label index} if lkps>maxLabel then lkps:=maxLabel; keylabel:=HumanReadable(lkps,lkpf); end; end; end; Keypressed:=localpress; end; end.
unit TechnoGenerator; interface uses GeneratorInterface, Generator, classes ; type TTechnoClassGenerator = class(TObject, iClassGenerator) private FCountRef: integer; protected FGenerator: TGenerator; public constructor Create; overload; constructor Create(const aGenerator: TGenerator); overload; destructor Destroy; override; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; function generate: TStringList; virtual; abstract; class function UpperFirstLetter(const aString: string): string; end; implementation { TTechnoClassGenerator } uses sysUtils; constructor TTechnoClassGenerator.Create; begin FGenerator := nil; FCountRef := 0; end; constructor TTechnoClassGenerator.Create(const aGenerator: TGenerator); begin FGenerator := aGenerator; FCountRef := 0; end; destructor TTechnoClassGenerator.Destroy; begin inherited; end; function TTechnoClassGenerator.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := S_FALSE; end; class function TTechnoClassGenerator.UpperFirstLetter( const aString: string): string; begin result := ''; if aString <> '' then begin result := UpperCase(Copy(aString, 1, 1)); if Length(aString) > 1 then begin result := result + Copy(aString, 2, Length(aString) - 1); end; end; end; function TTechnoClassGenerator._AddRef: Integer; begin inc(FCountRef); Result := S_OK; end; function TTechnoClassGenerator._Release: Integer; begin dec(FCountRef); Result := S_OK; end; end.
unit StatusFrm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TStatusForm = class(TForm) DocGroupBox: TGroupBox; SendDateEdit: TEdit; RecvDateEdit: TEdit; DocTypeEdit: TEdit; SendDateLabel: TLabel; RecvDateLabel: TLabel; DocTypeLabel: TLabel; OpGroupBox: TGroupBox; BillDateLabel: TLabel; OpNumberLabel: TLabel; OpTypeLabel: TLabel; BillDateEdit: TEdit; OpNumberEdit: TEdit; OpTypeEdit: TEdit; PurposeLabel: TLabel; PurposeMemo: TMemo; OkBtn: TBitBtn; OperNameLabel: TLabel; OperNameEdit: TEdit; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var StatusForm: TStatusForm; implementation {$R *.DFM} procedure TStatusForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then Close; end; procedure TStatusForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit ResizerCommonTypesUnit; //////////////////////////////////////////////////////////////////// // // // Description: Types, enumerated or otherwise, useful to Resizer // // Conversion functions for stated types // // // //////////////////////////////////////////////////////////////////// interface type TSourceMethod = (zsmFiles, zsmDirectory, zsmRecursiveDirectory); TFiletypeMethod = (zftmPreserve, zftmConvert); TScalingMethod = (zsmFactor, zsmCalculate); TFiletypeConversion = (zftcJPEG, zftcBMP, zftcGIF, zftcPNG); TFileHandling = (zfhOverwrite, zfhSkip); function StringToSourceMethod(const sValue: String): TSourceMethod; function StringToFiletypeMethod(const sValue: String): TFiletypeMethod; function StringToScalingMethod(const sValue: String): TScalingMethod; function StringToFiletypeConversion(const sValue: String): TFiletypeConversion; function StringToFileHandling(const sValue: String): TFileHandling; implementation uses SysUtils, ResizerConstsUnit; function StringToSourceMethod(const sValue: String): TSourceMethod; var smTemp: TSourceMethod; sLowerValue: String; begin smTemp := zsmFiles; sLowerValue := LowerCase(sValue); if CompareText(sLowerValue, COMPARE_DIRECTORY) = 0 then smTemp := zsmDirectory else if CompareText(sLowerValue, COMPARE_RECURSIVE_DIRECTORY) = 0 then smTemp := zsmRecursiveDirectory; Result := smTemp; end; // StringToSourceMethod function StringToFiletypeMethod(const sValue: String): TFiletypeMethod; var ftmTemp: TFiletypeMethod; sLowerValue: String; begin ftmTemp := zftmConvert; sLowerValue := LowerCase(sValue); if CompareText(sLowerValue, COMPARE_PRESERVE) = 0 then ftmTemp := zftmPreserve; Result := ftmTemp; end; // StringToFiletypeMethod function StringToScalingMethod(const sValue: String): TScalingMethod; var smTemp: TScalingMethod; sLowerValue: String; begin smTemp := zsmCalculate; sLowerValue := LowerCase(sValue); if CompareText(sLowerValue, COMPARE_FACTOR) = 0 then smTemp := zsmFactor; Result := smTemp; end; // StringToScalingMethod function StringToFiletypeConversion(const sValue: String): TFiletypeConversion; var ftcTemp: TFiletypeConversion; sLowerValue: String; begin ftcTemp := zftcJPEG; sLowerValue := LowerCase(sValue); if CompareText(sLowerValue, COMPARE_CONV_BMP) = 0 then ftcTemp := zftcBMP; ////////////////////////// // Not implemented yet: // ////////////////////////// { else if CompareText(sLowerValue, COMPARE_CONV_GIF) = 0 then ftcTemp := zftcGIF else if CompareText(sLowerValue, COMPARE_CONV_PNG) = 0 then ftcTemp := zftcPNG; } Result := ftcTemp; end; // StringToFiletypeConversion function StringToFileHandling(const sValue: String): TFileHandling; var fhTemp: TFileHandling; sLowerValue: String; begin fhTemp := zfhSkip; sLowerValue := LowerCase(sValue); if CompareText(sLowerValue, COMPARE_OVERWRITE) = 0 then fhTemp := zfhOverwrite; Result := fhTemp; end; // StringToFileHandling end.
1 program ISBN; 2 { (c) 2002, Tom Verhoeff, TUE } 3 { 2006, Etienne van Delden, TUE} 4 { Programma om te controleren of het ingegeven ISBN een geldig ISBN is. } 5 6 var 7 input: String; // string om ISBN in te lezen 8 9 const 10 AantalCijfersInISBN = 10; // aantal ISBN-cijfers in een ISBN 11 12 type 13 CijferWaarde = 0 .. 10; // verz. waarden van ISBN-cijfers 14 15 function charToCijferWaarde ( const c: Char ): CijferWaarde; 16 // converteer karakter dat ISBN-cijfer voorstelt naar zijn waarde 17 // pre: c in [ '0' .. '9', 'X' ] 18 // ret: 0 .. 9, of 10 al naar gelang c = '0' .. '9', of 'X' 19 20 begin 21 if c in [ '0' .. '9' ] then 22 Result := ord ( c ) - ord ( '0' ) 23 else { c = 'X' } 24 Result := 10 25 end; // end charToCijferWaarde 26 27 function isGeldigISBN ( const code: String ): Boolean; 28 // controleer of code een geldig ISBN is } 29 // pre: code bestaat uit precies 10 ISBN-cijfers 30 // ret: of code een geldig ISBN is, d.w.z. of 31 // (som k: 1 <= k <= 10: (11-k) code_k) een 11-voud is 32 33 var 34 s: Integer; // gewogen cijfer-som 35 i: Integer; // hulp var: teller 36 37 begin 38 s := 0; // int. var s: cijfer som 39 i := 1; // int. hulp var i:teller 40 41 // controleer of het i-de getal een X is en vervang met 10 42 // vermenigvuldig het i-de getal met i en tel dit op bij de vorige uitkomst 43 44 for i := Length( code ) downto 1 do 45 begin 46 s := s + charToCijferWaarde( code[ i ] ) * i 47 end; 48 49 Result := ( s mod 11 = 0 ) 50 end; // end isGeldigISBN 51 52 procedure alleenISBNcijfers ( var regel: String ); 53 // pre: Zij regel = R en 1 <= Length( R ) <= 40 54 // post: regel = rijtje van alle ISBN-cijfers uit R 55 56 var 57 i: Integer; // teller variabele 58 59 begin 60 i := 1; // init i 61 62 while i <= Length( regel ) do 63 begin // verwijder char i als char i geen 64 // geldig cijfer of X is 65 if not ((regel[ i ] >= '0') and (regel[ i ] <= '9' ) 66 or (regel[i]='X')) then 67 begin 68 Delete( regel, i, 1 ); 69 end 70 else 71 begin 72 i := i + 1 73 end; // end if 74 75 end; // end while 76 77 end; // end procedure alleenISBNCijfers 78 79 function okX ( const code: String): Boolean; 80 // pre: code bestaat uit precies 10 ISBN-cijfers 81 // ret: of er geen 'x' in code voorkomt op positie 1 t/m 9 82 83 var 84 i: Integer; // teller variabele 85 86 begin 87 Result := True; // we gaan uit vna juiste code 88 89 for i := 1 to Length( code ) - 1 do 90 begin 91 92 if code[ i ] = 'X' then 93 begin 94 Result := False // X staat op de verkeerde plaats 95 end; // end if 96 97 end; // end for 98 99 end; // end function okX 100 101 procedure verwerkRegel ( regel: String ); 102 // pre: regel bevat een code wat een ISBN zou kunnen zijn 103 // post: regel is geschreven, 104 // met erachter de tekst ' is een geldig ISBN' of ' is niet een geldig ISBN' 105 // al naar gelang regel een geldig ISBN bevat of niet 106 107 begin 108 alleenISBNcijfers( regel ); // input omzetten naar cijfers+X 109 write( regel ); 110 111 if Length( regel ) < 10 then // controle: is regel te kort? 112 begin 113 write(' is te kort'); 114 end 115 else if Length( regel ) > 10 then // controle: is regel te lang? 116 begin 117 write(' is te lang'); 118 end 119 else if okX( regel ) = False then // controle: staat x juist geplaatst? 120 begin 121 write( ' bevat X op verkeerde plaats' ); 122 end 123 else if isGeldigISBN (regel) = false then begin 124 write( ' is niet geldig' ); // controle: is code geldig? 125 end 126 else begin 127 write( ' is geldig' ); 128 end; // end if 129 130 writeln 131 end; // end verwerkRegel 132 133 134 135 begin // het uiteindelijke programma 136 readln ( input ); 137 138 while input <> '.' do begin // zolang het einde niet is bereikt 139 verwerkRegel( input ); 140 readln ( input ) 141 end; // end while 142 143 end.
unit OpenDialogEx; interface uses SysUtils, Classes, Dialogs, ExtCtrls; type TOpenDialogEx = class(TOpenDialog) private FOnCreate : TNotifyEvent; FOnDestroy : TNotifyEvent; FExPanel : TPanel; procedure SetExPanel(APanel : TPanel); protected // Fast access for ofen used common features property ExPanel : TPanel read FExPanel write SetExPanel; property PreviewImage : TImage read FPreviewImage write FPreviewImage; property PreviewLabel : TLabel read FPreviewLabel write FPreviewLabel; protected procedure DoClose; override; procedure DoSelectionChange; override; procedure DoShow; override; public constructor Create(AOwner: TComponent); override; procedure AfterConstruction; virtual; procedure BeforeDestruction; virtual; published property OnCreate : TNotifyEvent read FOnCreate write FOnCreate; property OnDestroy : TNotifyEvent read FOnDestroy write FOnDestroy; end; procedure Register; implementation type TSilentPaintPanel = class(TPanel) protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; procedure TSilentPaintPanel.WMPaint(var Msg: TWMPaint); begin try inherited; except Caption := SInvalidImage; end; end; constructor TOpenDialogEx.Create(AOwner : TComponent); begin inherited Create(AOwner); FOnCreate := nil; FOnDestroy := nil; FExPanel := nil; end; procedure TOpenDialogEx.AfterConstruction; begin if Assigned(FOnCreate) then FOnCreate(Self); end; procedure TOpenDialogEx.BeforeDestruction; begin if Assigned(FOnDestroy) then FOnDestroy(Self); end; procedure TOpenDialogEx.SetExPanel(APanel : TPanel); begin if not Assigned(FExPanel) then begin TSplitter.Create(Self); end; FExPanel := APanel; FExPanel.Align := alLeft; end; procedure OpenDialogEx.DoClose; begin inherited DoClose; { Hide any hint windows left behind } Application.HideHint; end; procedure Register; begin RegisterComponents('Dialogues', [TOpenDialogEx]); end; end.
unit Display; 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.Controls.Presentation, FMX.StdCtrls, Turtle, FMX.Edit, FMX.EditBox, FMX.NumberBox, DefinedGrammars, Parser, FMX.Menus, FMX.ExtCtrls; type TForm1 = class(TForm) Image1: TImage; MenuBar1: TMenuBar; Grammar: TMenuItem; RunButton: TButton; DragonCurve: TMenuItem; SierpinskiTriangle: TMenuItem; KochCurve: TMenuItem; ItNumBox: TNumberBox; Text1: TText; procedure FormCreate(Sender: TObject); procedure DragonCurveClick(Sender: TObject); procedure RunButtonClick(Sender: TObject); procedure KochCurveClick(Sender: TObject); procedure SierpinskiTriangleClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} uses Grammar; var testTurtle: TTurtle; selectedGrammar: TGrammar; startPoint: TPointF; drawSize: Integer; procedure TForm1.FormCreate(Sender: TObject); begin Image1.Bitmap.SetSize(Round(Image1.Width), Round(Image1.Height)); Image1.Bitmap.Clear(TAlphaColors.White); // Initialise grammars InitialiseGrammars; end; // Grammar menu items // Koch curve menu item selected procedure TForm1.KochCurveClick(Sender: TObject); begin selectedGrammar := kochCurveGrammar; drawSize := 7; startPoint := TPointF.Create(15, 300); // Reccomended max iterations ItNumBox.Max := 4; end; // Dragon curve menu item selected procedure TForm1.DragonCurveClick(Sender: TObject); begin selectedGrammar := dragonCurveGrammar; drawSize := 5; startPoint := TPointF.Create(425, 250); // Recommended max iterations for canvas size ItNumBox.Max := 12; end; // Sierpinski triangle menu item selected procedure TForm1.SierpinskiTriangleClick(Sender: TObject); begin selectedGrammar := sierpinskiGrammar; drawSize := 7; startPoint := TPointF.Create(75, 0); // Reccomended max iterations ItNumBox.Max := 6; end; // When Run button clicked, draw fractal with turtle procedure TForm1.RunButtonClick(Sender: TObject); var production: String; movements: TStringList; begin if not Assigned(selectedGrammar) then ShowMessage('Please select a grammar') else if ItNumBox.Value = 0 then ShowMessage('Please select desired iteration') else begin // Clear screen Image1.Bitmap.Clear(TAlphaColors.White); // Initialise turtle testTurtle := TTurtle.Create(startPoint, drawSize); // Produce production at desired iteration step production := Parse(selectedGrammar, Round(ItNumBox.Value)); // Fetch corresponding movements using the production string movements := FetchMovements(selectedGrammar, production); // Instruct turtle to draw fractal by interpreting given movements testTurtle.InterpretMoves(movements); end; end; end.
unit IdSimpleServer; interface uses Classes, IdSocketHandle, IdTCPConnection, IdStackConsts; type TIdSimpleServer = class(TIdTCPConnection) protected FAbortedRequested: Boolean; FAcceptWait: Integer; // FBinding: TIdSocketHandle; FBoundIP: String; FBoundPort: Integer; FListenHandle: TIdStackSocketHandle; FListening: Boolean; // function GetBinding: TIdSocketHandle; public procedure Abort; virtual; procedure BeginListen; virtual; procedure Bind; virtual; constructor Create(AOwner: TComponent); override; procedure CreateBinding; procedure EndListen; virtual; function Listen: Boolean; virtual; procedure ResetConnection; override; // property AcceptWait: integer read FAcceptWait write FAcceptWait; property Binding: TIdSocketHandle read GetBinding; property ListenHandle: TIdStackSocketHandle read FListenHandle; published property BoundIP: string read FBoundIP write FBoundIP; property BoundPort: Integer read FBoundPort write FBoundPort; end; implementation uses IdGlobal, IdStack, IdIOHandlerSocket, SysUtils; { TIdSimpleServer } procedure TIdSimpleServer.Abort; begin FAbortedRequested := True; end; procedure TIdSimpleServer.BeginListen; begin // Must be before IOHandler as it resets it if not Assigned(Binding) then begin ResetConnection; CreateBinding; end; try if ListenHandle = Id_INVALID_SOCKET then begin Bind; end; Binding.Listen(15); FListening := True; except FreeAndNil(FIOHandler); raise; end; end; procedure TIdSimpleServer.Bind; begin with Binding do begin try AllocateSocket; FListenHandle := Handle; IP := BoundIP; Port := BoundPort; Bind; except FListenHandle := Id_INVALID_SOCKET; raise; end; end; end; constructor TIdSimpleServer.Create(AOwner: TComponent); begin inherited; FListenHandle := Id_INVALID_SOCKET; end; procedure TIdSimpleServer.CreateBinding; begin IOHandler := TIdIOHandlerSocket.Create(Self); IOHandler.Open; end; procedure TIdSimpleServer.EndListen; begin ResetConnection; end; function TIdSimpleServer.GetBinding: TIdSocketHandle; begin if Assigned(IOHandler) then begin Result := TIdIOHandlerSocket(IOHandler).Binding; end else begin Result := nil; end; end; function TIdSimpleServer.Listen: Boolean; begin //TODO: Add a timeout to this function. Result := False; if not FListening then begin BeginListen; end; with Binding do begin if FAbortedRequested = False then begin while (FAbortedRequested = False) and (Result = False) do begin Result := Readable(AcceptWait); end; end; if Result then begin binding.listen(1); binding.Accept(binding.Handle); end; GStack.WSCloseSocket(ListenHandle); FListenHandle := Id_INVALID_SOCKET; end; end; procedure TIdSimpleServer.ResetConnection; begin inherited ResetConnection; FAbortedRequested := False; FListening := False; FreeAndNil(FIOHandler); end; end.
{$MODE OBJFPC} program Triangles; const InputFile = 'TRIANGLES.INP'; OutputFile = 'TRIANGLES.OUT'; maxN = 5000; var a, b, freq: array[1..maxN + 1] of Integer; n, m: Integer; res: Int64; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n); for i := 1 to n do Read(f, a[i]); a[n + 1] := MaxInt; finally CloseFile(f); end; end; procedure Sort(L, H: Integer); var i, j: Integer; Pivot: Integer; begin if L >= H then Exit; i := L + Random(H - L + 1); Pivot := a[i]; a[i] := a[L]; i := L; j :=H; repeat while (a[j] > Pivot) and (i < j) do Dec(j); if i < j then begin a[i] := a[j]; Inc(i); end else Break; while (a[i] < Pivot) and (i < j) do Inc(i); if i < j then begin a[j] := a[i]; Dec(j); end else Break; until i = j; a[i] := Pivot; Sort(L, i - 1); Sort(i + 1, H); end; procedure Refine; var j, i: Integer; begin m := 0; j := 0; for i := 1 to n do if a[i] <> a[i + 1] then begin Inc(m); b[m] := a[i]; freq[m] := i - j; j := i; end; end; procedure Solve; var i, j, k: Integer; Old: Integer; begin Res := 0; //Dem so tam giac deu for i := 1 to m do if freq[i] >= 3 then Inc(Res); //Dem so tam giac can nhung khong deu j := 1; for i := 1 to m do if freq[i] >= 2 then begin while (j <= m) and (b[j] < 2 * b[i]) do Inc(j); Inc(Res, j - 2); end; //Dem so tam giac khong can for i := 1 to m - 2 do begin k := i + 2; for j := i + 1 to m - 1 do begin while (k <= m) and (b[k] < b[i] + b[j]) do Inc(k); Inc(Res, k - 1 - j); end; end; end; procedure PrintResult; var f: TextFile; begin AssignFile(f, OutputFile); Rewrite(f); try WriteLn(f, Res); finally CloseFile(f); end; end; begin Enter; Sort(1, n); Refine; Solve; PrintResult; end. 6 11 22 22 22 44 55
unit microdom; interface uses Classes; type TuDomElementList = class; TuDomElement = class(TObject) {$IFDEF __TEST__}public{$ELSE}private{$ENDIF} function GetValue: string; {$IFDEF __TEST__}public{$ELSE}protected{$ENDIF} m_name: string; m_values: TStringList; m_nodes: TuDomElementList; public constructor Create; destructor Destroy; override; function Parse(const sXML: string): Boolean; virtual; property Name: string read m_name; property Value: string read GetValue; property ChildNodes: TuDomElementList read m_nodes; end; TuDomElementList = class(TList) end; TuDomDocument = class(TuDomElement) end; type TXMLTokenKind = ( tokEOF, tokError, tokText, tokTag, tokOpenTag, tokCloseTag, tokHeader, tokDoctype, tokComment, tokCDATA, tokPCDATA ); TXMLToken = record kind: TXMLTokenKind; value: string; procedure ParseTag(const tag: string); end; procedure SkipSpaces(const s: string; var ipos: integer); function GetXMLToken(const xml: string; var ipos: integer): TXMLToken; function ScanChar(const s: string; ipos: integer; c: char): integer; implementation uses Windows, SysUtils, StrUtils; procedure _p(const fmt: string; const args: array of const); var s: string; begin s:=Format(fmt, args); OutputDebugString(PWideChar(s)); end; procedure SkipSpaces(const s: string; var ipos: integer); begin while (ipos<=Length(s)) and CharInSet(s[ipos], [' ', #9, #10, #13]) do Inc(ipos); end; function ScanChar(const s: string; ipos: integer; c: char): integer; var cc, // cc - current char sd: char; // sd - string delimiter sqb: integer; begin Result:=ipos; sd:=#0; sqb:=0; while Result<=Length(s) do begin cc:=s[Result]; if sd<>#0 then begin if cc=sd then // end of string sd:=#0; // clear the flag 'in string' end else if (sqb=0) and (cc=c) then // found Break else if cc='[' then Inc(sqb) else if cc=']' then Dec(sqb) else if CharInSet(cc, ['''', '"']) then sd:=cc; // flag 'in string' Inc(Result); end; if Result>Length(s) then Result:=0; end; function GetXMLToken(const xml: string; var ipos: integer): TXMLToken; var npos: integer; begin if ipos>Length(xml) then Result.kind:=tokEOF else if xml[ipos]='<' then begin npos:=ScanChar(xml, ipos, '>'); if npos=0 then begin Result.kind:=tokError; Result.value:='''>'' not found'; end else begin Result.ParseTag(Copy(xml, ipos, npos-ipos+1)); ipos:=npos+1; end; end else begin npos:=ScanChar(xml, ipos, '<'); if npos=0 then npos:=Length(xml)+1; Result.kind:=tokText; Result.value:=Copy(xml, ipos, npos-ipos); ipos:=npos; end; end; { can be: <a/> tokTag <a> tokOpenTag </a> tokCloseTag <?xml...> tokHeader <!DOCTYPE...> tokDoctype <!-- --> tokComment } procedure TXMLToken.ParseTag(const tag: string); var l: integer; s: string; begin l:=Length(tag); _p('> ParseTag(tag="%s")', [tag]); Assert(l>2, 'wrong length: "'+tag+'"'); Assert(tag[1]='<', '< at begin expected: "'+tag+'"'); Assert(tag[l]='>', '> at end expected: "'+tag+'"'); kind:=tokError; value:='Syntax error'; s:=Trim(Copy(tag, 2, l-2)); l:=Length(s); _p(' ParseTag: content=[%s]', [s]); _p(' ParseTag: StartsStr(s, ?xml)=%d, EndsStr(s, ?)=%d', [ord(StartsStr('?xml ', s)), ord(EndsStr('?', s))]); if s[l]='/' then begin kind:=tokTag; Delete(s, l, 1); end else if s[1]='/' then begin kind:=tokCloseTag; Delete(s, 1, 1); end else if StartsStr('?xml ', s) and EndsStr('?', s) then begin kind:=tokHeader; Delete(s, l, 1); Delete(s, 1, 5); end else if StartsStr('!DOCTYPE', s) then begin kind:=tokDoctype; Delete(s, 1, 8); end else begin kind:=tokOpenTag; end; value:=Trim(s); _p('< ParseTag: value="%s"', [value]); end; { TuDomElement } constructor TuDomElement.Create; begin inherited Create; m_values:=TStringList.Create; m_nodes:=TuDomElementList.Create; end; destructor TuDomElement.Destroy; begin FreeAndNil(m_nodes); FreeAndNil(m_values); inherited Destroy; end; function TuDomElement.GetValue: string; begin if m_values.Count=0 then Result:='' else if m_values.Count=1 then Result:=m_values[0] else Result:=Trim(m_values.Text); end; function TuDomElement.Parse(const sXML: string): Boolean; begin Result:=false; end; end.
// isctype.h - Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details // "msvcrt.dll" partial implementation for Delphi + some functions extended (C) 2013 - Snow Panther Unit isctype; Interface Function isalnum(c : Integer) : Integer; Function isalpha(c : Integer) : Integer; Function isprint(c : Integer) : Integer; Function isspace(c : Integer) : Integer; Function tolower(c : Integer) : Integer; Function isalnumB(c : Integer) : Boolean; Function isalphaB(c : Integer) : Boolean; Function isprintB(c : Integer) : Boolean; Function isspaceB(c : Integer) : Boolean; Implementation Const _UPPER = $01; _LOWER = $02; _DIGIT = $04; _SPACE = $08; _PUNCT = $10; _CONTROL = $20; _BLANK = $40; _HEX = $80; _LEADBYTE = $8000; _ALPHA = ($0100 or _UPPER or _LOWER); _ctype : Packed Array[0..255]of Word = ( // 0, // <EOF>, 0xFFFF */ _CONTROL, // CTRL+@, 0x00 */ _CONTROL, // CTRL+A, 0x01 */ _CONTROL, // CTRL+B, 0x02 */ _CONTROL, // CTRL+C, 0x03 */ _CONTROL, // CTRL+D, 0x04 */ _CONTROL, // CTRL+E, 0x05 */ _CONTROL, // CTRL+F, 0x06 */ _CONTROL, // CTRL+G, 0x07 */ _CONTROL, // CTRL+H, 0x08 */ _CONTROL or _SPACE, // CTRL+I, 0x09 */ _CONTROL or _SPACE, // CTRL+J, 0x0a */ _CONTROL or _SPACE, // CTRL+K, 0x0b */ _CONTROL or _SPACE, // CTRL+L, 0x0c */ _CONTROL or _SPACE, // CTRL+M, 0x0d */ _CONTROL, // CTRL+N, 0x0e */ _CONTROL, // CTRL+O, 0x0f */ _CONTROL, // CTRL+P, 0x10 */ _CONTROL, // CTRL+Q, 0x11 */ _CONTROL, // CTRL+R, 0x12 */ _CONTROL, // CTRL+S, 0x13 */ _CONTROL, // CTRL+T, 0x14 */ _CONTROL, // CTRL+U, 0x15 */ _CONTROL, // CTRL+V, 0x16 */ _CONTROL, // CTRL+W, 0x17 */ _CONTROL, // CTRL+X, 0x18 */ _CONTROL, // CTRL+Y, 0x19 */ _CONTROL, // CTRL+Z, 0x1a */ _CONTROL, // CTRL+[, 0x1b */ _CONTROL, // CTRL+\, 0x1c */ _CONTROL, // CTRL+], 0x1d */ _CONTROL, // CTRL+^, 0x1e */ _CONTROL, // CTRL+_, 0x1f */ _SPACE or _BLANK, // ` ', 0x20 */ _PUNCT, // `!', 0x21 */ _PUNCT, // 0x22 */ _PUNCT, // `#', 0x23 */ _PUNCT, // `$', 0x24 */ _PUNCT, // `%', 0x25 */ _PUNCT, // `&', 0x26 */ _PUNCT, // 0x27 */ _PUNCT, // `(', 0x28 */ _PUNCT, // `)', 0x29 */ _PUNCT, // `*', 0x2a */ _PUNCT, // `+', 0x2b */ _PUNCT, // `,', 0x2c */ _PUNCT, // `-', 0x2d */ _PUNCT, // `.', 0x2e */ _PUNCT, // `/', 0x2f */ _DIGIT or _HEX, // `0', 0x30 */ _DIGIT or _HEX, // `1', 0x31 */ _DIGIT or _HEX, // `2', 0x32 */ _DIGIT or _HEX, // `3', 0x33 */ _DIGIT or _HEX, // `4', 0x34 */ _DIGIT or _HEX, // `5', 0x35 */ _DIGIT or _HEX, // `6', 0x36 */ _DIGIT or _HEX, // `7', 0x37 */ _DIGIT or _HEX, // `8', 0x38 */ _DIGIT or _HEX, // `9', 0x39 */ _PUNCT, // `:', 0x3a */ _PUNCT, // `;', 0x3b */ _PUNCT, // `<', 0x3c */ _PUNCT, // `=', 0x3d */ _PUNCT, // `>', 0x3e */ _PUNCT, // `?', 0x3f */ _PUNCT, // `@', 0x40 */ _UPPER or _HEX, // `A', 0x41 */ _UPPER or _HEX, // `B', 0x42 */ _UPPER or _HEX, // `C', 0x43 */ _UPPER or _HEX, // `D', 0x44 */ _UPPER or _HEX, // `E', 0x45 */ _UPPER or _HEX, // `F', 0x46 */ _UPPER, // `G', 0x47 */ _UPPER, // `H', 0x48 */ _UPPER, // `I', 0x49 */ _UPPER, // `J', 0x4a */ _UPPER, // `K', 0x4b */ _UPPER, // `L', 0x4c */ _UPPER, // `M', 0x4d */ _UPPER, // `N', 0x4e */ _UPPER, // `O', 0x4f */ _UPPER, // `P', 0x50 */ _UPPER, // `Q', 0x51 */ _UPPER, // `R', 0x52 */ _UPPER, // `S', 0x53 */ _UPPER, // `T', 0x54 */ _UPPER, // `U', 0x55 */ _UPPER, // `V', 0x56 */ _UPPER, // `W', 0x57 */ _UPPER, // `X', 0x58 */ _UPPER, // `Y', 0x59 */ _UPPER, // `Z', 0x5a */ _PUNCT, // `[', 0x5b */ _PUNCT, // 0x5c */ _PUNCT, // `]', 0x5d */ _PUNCT, // `^', 0x5e */ _PUNCT, // `_', 0x5f */ _PUNCT, // 0x60 */ _LOWER or _HEX, // `a', 0x61 */ _LOWER or _HEX, // `b', 0x62 */ _LOWER or _HEX, // `c', 0x63 */ _LOWER or _HEX, // `d', 0x64 */ _LOWER or _HEX, // `e', 0x65 */ _LOWER or _HEX, // `f', 0x66 */ _LOWER, // `g', 0x67 */ _LOWER, // `h', 0x68 */ _LOWER, // `i', 0x69 */ _LOWER, // `j', 0x6a */ _LOWER, // `k', 0x6b */ _LOWER, // `l', 0x6c */ _LOWER, // `m', 0x6d */ _LOWER, // `n', 0x6e */ _LOWER, // `o', 0x6f */ _LOWER, // `p', 0x70 */ _LOWER, // `q', 0x71 */ _LOWER, // `r', 0x72 */ _LOWER, // `s', 0x73 */ _LOWER, // `t', 0x74 */ _LOWER, // `u', 0x75 */ _LOWER, // `v', 0x76 */ _LOWER, // `w', 0x77 */ _LOWER, // `x', 0x78 */ _LOWER, // `y', 0x79 */ _LOWER, // `z', 0x7a */ _PUNCT, // `{', 0x7b */ _PUNCT, // `|', 0x7c */ _PUNCT, // `}', 0x7d */ _PUNCT, // `~', 0x7e */ _CONTROL, // 0x7f */ 0, // 0x80 */ 0, // 0x81 */ 0, // 0x82 */ 0, // 0x83 */ 0, // 0x84 */ 0, // 0x85 */ 0, // 0x86 */ 0, // 0x87 */ 0, // 0x88 */ 0, // 0x89 */ 0, // 0x8a */ 0, // 0x8b */ 0, // 0x8c */ 0, // 0x8d */ 0, // 0x8e */ 0, // 0x8f */ 0, // 0x90 */ 0, // 0x91 */ 0, // 0x92 */ 0, // 0x93 */ 0, // 0x94 */ 0, // 0x95 */ 0, // 0x96 */ 0, // 0x97 */ 0, // 0x98 */ 0, // 0x99 */ 0, // 0x9a */ 0, // 0x9b */ 0, // 0x9c */ 0, // 0x9d */ 0, // 0x9e */ 0, // 0x9f */ 0, // 0xa0 */ 0, // 0xa1 */ 0, // 0xa2 */ 0, // 0xa3 */ 0, // 0xa4 */ 0, // 0xa5 */ 0, // 0xa6 */ 0, // 0xa7 */ 0, // 0xa8 */ 0, // 0xa9 */ 0, // 0xaa */ 0, // 0xab */ 0, // 0xac */ 0, // 0xad */ 0, // 0xae */ 0, // 0xaf */ 0, // 0xb0 */ 0, // 0xb1 */ 0, // 0xb2 */ 0, // 0xb3 */ 0, // 0xb4 */ 0, // 0xb5 */ 0, // 0xb6 */ 0, // 0xb7 */ 0, // 0xb8 */ 0, // 0xb9 */ 0, // 0xba */ 0, // 0xbb */ 0, // 0xbc */ 0, // 0xbd */ 0, // 0xbe */ 0, // 0xbf */ 0, // 0xc0 */ 0, // 0xc1 */ 0, // 0xc2 */ 0, // 0xc3 */ 0, // 0xc4 */ 0, // 0xc5 */ 0, // 0xc6 */ 0, // 0xc7 */ 0, // 0xc8 */ 0, // 0xc9 */ 0, // 0xca */ 0, // 0xcb */ 0, // 0xcc */ 0, // 0xcd */ 0, // 0xce */ 0, // 0xcf */ 0, // 0xd0 */ 0, // 0xd1 */ 0, // 0xd2 */ 0, // 0xd3 */ 0, // 0xd4 */ 0, // 0xd5 */ 0, // 0xd6 */ 0, // 0xd7 */ 0, // 0xd8 */ 0, // 0xd9 */ 0, // 0xda */ 0, // 0xdb */ 0, // 0xdc */ 0, // 0xdd */ 0, // 0xde */ 0, // 0xdf */ 0, // 0xe0 */ 0, // 0xe1 */ 0, // 0xe2 */ 0, // 0xe3 */ 0, // 0xe4 */ 0, // 0xe5 */ 0, // 0xe6 */ 0, // 0xe7 */ 0, // 0xe8 */ 0, // 0xe9 */ 0, // 0xea */ 0, // 0xeb */ 0, // 0xec */ 0, // 0xed */ 0, // 0xee */ 0, // 0xef */ 0, // 0xf0 */ 0, // 0xf1 */ 0, // 0xf2 */ 0, // 0xf3 */ 0, // 0xf4 */ 0, // 0xf5 */ 0, // 0xf6 */ 0, // 0xf7 */ 0, // 0xf8 */ 0, // 0xf9 */ 0, // 0xfa */ 0, // 0xfb */ 0, // 0xfc */ 0, // 0xfd */ 0, // 0xfe */ 0 // 0xff */ ); { unsigned short *_pctype = _ctype + 1; unsigned short *_pwctype = _ctype + 1; Function __p__pctype : Pointer; Begin Result:=@_pctype; End; Function __p__pwctype : Pointer; Begin Result:=@_pwctype; End; } Function _isctype(c : Longword; ctypeFlags : Integer) : Integer; Begin Result:=_ctype[c and $FF] and ctypeFlags; End; {Function iswctype(wint_t wc, wctype_t wctypeFlags) : Integer; Begin Result:=_pwctype[wc and $FF] and wctypeFlags; End;} //------------------------------------------------------------------------------ Function isprint(c : Integer) : Integer; Begin Result:=_isctype(c,_BLANK or _PUNCT or _ALPHA or _DIGIT); End; {Function iswprint(wint_t c) : Integer; Begin Result:=iswctype((unsigned short)c,_BLANK | _PUNCT | _ALPHA | _DIGIT); End;} Function isspace(c : Integer) : Integer; Begin Result:=_isctype(c,_SPACE); End; {Function iswspace(wint_t c) : Integer; Begin Result:=iswctype(c,_SPACE); End;} Function tolower(c : Integer) : Integer; Begin if _isctype(c,_UPPER)<>0 then Result:=(c - ord('A') - ord('a')) else Result:=c; End; {wchar_t towlower(wchar_t c) Begin if (iswctype (c, _UPPER)) return (c - (L'A' - L'a')); return(c); End;} Function isalpha(c : Integer) : Integer; Begin Result:=_isctype(c,_ALPHA); End; {int iswalpha(wint_t c) Result:=iswctype(c,_ALPHA);} Function isalnum(c : Integer) : Integer; Begin Result:=_isctype(c,_ALPHA or _DIGIT); End; {int iswalnum(wint_t c) Result:=iswctype(c,_ALPHA | _DIGIT); } Function isprintB(c : Integer) : Boolean; Begin Result:=_isctype(c,_BLANK or _PUNCT or _ALPHA or _DIGIT)<>0; End; Function isspaceB(c : Integer) : Boolean; Begin Result:=_isctype(c,_SPACE)<>0; End; Function isalphaB(c : Integer) : Boolean; Begin Result:=_isctype(c,_ALPHA)<>0; End; Function isalnumB(c : Integer) : Boolean; Begin Result:=_isctype(c,_ALPHA or _DIGIT)<>0; End; End.
unit adot.Grammar.Types; interface uses adot.Types, adot.Collections, adot.Collections.Vectors, adot.Collections.Sets, adot.Collections.Trees, adot.Tools, adot.Tools.IO, adot.Tools.Rtti, adot.Strings, {$IF Defined(LogExceptions)} {$Define LogGrammar} adot.Log, {$ENDIF} System.Generics.Collections, System.Character, System.SysUtils, System.StrUtils; const infinitely = High(integer); type TGrammarClass = class; TRuleId = int64; TParseTreeItem = record Rule: TGrammarClass; Position: TTokenPos; procedure Init(ARule: TGrammarClass; AStart,ALen: integer); overload; procedure Init(const ASrc: TParseTreeItem); overload; end; TEnumTreeProc = reference to procedure(TreeNode: integer; var Cancel: boolean); TFilterTreeProc = reference to procedure(Tree: TTreeArrayClass<TParseTreeItem>; Node: integer; var Accept: boolean); TParseTree = class public type { Enumerates subtree starting from specified node } TSubtreeEnumerator = TTreeArrayClass<TParseTreeItem>.TSubtreeEnumerator; TSubtreeCollection = TTreeArrayClass<TParseTreeItem>.TSubtreeCollection; { Snumerates ParseTree starting from specified node, returns only matches of specified rule } TRuleMatchesEnumerator = record private Enum: TSubtreeEnumerator; Nodes: TTreeArrayClass<TParseTreeItem>; RuleId: TruleId; function CurrentNode: integer; public procedure Init(ANodes: TTreeArrayClass<TParseTreeItem>; ARoot: integer; const ARuleId: TruleId); function MoveNext: Boolean; property Current: integer read CurrentNode; end; { collection for TRuleMatchesEnumerator } TRuleMatchesCollection = record Tree: TTreeArrayClass<TParseTreeItem>; Root: integer; RuleId: TruleId; procedure Init(ATree: TTreeArrayClass<TParseTreeItem>; ARoot: integer; const ARuleId: TruleId); function GetEnumerator: TRuleMatchesEnumerator; end; private function GetItem(n: integer): TParseTreeItem; procedure SetItem(n: integer; const Item: TParseTreeItem); function GetCount: integer; function GetChilds(ARoot: integer): TSubtreeCollection; function GetRuleMatches(RootNode: integer; const RuleId: TRuleId): TRuleMatchesCollection; function GetFirstChild(Node: integer): integer; function GetNextSibling(Node: integer): integer; function GetTotalSizeBytes: int64; public Tree: TTreeArrayClass<TParseTreeItem>; Root: integer; constructor Create; destructor Destroy; override; function Add(ARule: TGrammarClass; AStart, ALen: integer): integer; function Append(ARule: TGrammarClass; AStart, ALen: integer): integer; overload; function Append: integer; overload; function Commit(ARule: TGrammarClass; AStart, ALen: integer): integer; overload; function Commit: integer; overload; procedure Rollback; { clear Tree and set Root=-1 } procedure Clear; { support for "for" syntax: for I in Tree do ... } function GetEnumerator: TSubtreeEnumerator; { build tree from subset of nodes according to the filter (original tree where filtered nodes are ommited) } function GetSubTree(StartNode: integer; FilterProc: TFilterTreeProc): TParseTree; procedure LogTextInputParseTree(var InputData: TBuffer); { shortcuts to Tree.Items / Tree.Count } property TreeItems[RootNode: integer]:TParseTreeItem read GetItem write SetItem; default; property Count: integer read GetCount; { enumerable collection of child nodes (including specified Root) } property Matches[Root: integer]: TSubtreeCollection read GetChilds; { enumerable collection of child nodes (including specified Root), only matched of specified rule returned } property RuleMatches[RootNode: integer; const RuleId: TRuleId]:TRuleMatchesCollection read GetRuleMatches; property FirstChild[Node: integer]: integer read GetFirstChild; property NextSibling[Node: integer]: integer read GetNextSibling; property TotalSizeBytes: int64 read GetTotalSizeBytes; end; { grammar based parser } TGrammarParser = class abstract protected function GetDataToken(const P: TTokenPos): string; function GetTreeToken(ParseTreeNode: integer): string; function GetTotalSizeBytes: int64; public Data: TBuffer; { input data (text or bytes) } Grammar: TGrammarClass; { main rule of the grammar (class doesn't own that grammar) } ParseTree: TParseTree; { parse tree (available if .Accepted returns True) } constructor Create(AMainRule: TGrammarClass); overload; virtual; constructor Create(AMainRule: IInterfacedObject<TGrammarClass>); overload; destructor Destroy; override; procedure Clear; virtual; function Accepted: Boolean; overload; virtual; abstract; function Accepts(const AData: TBuffer): Boolean; overload; function Accepts(const AData: string): Boolean; overload; procedure LogParseTree; virtual; abstract; { for any TTokenPos (position and length in bytes) returns corresponding string from Data } property DataToken[const P: TTokenPos]: string read GetDataToken; { returns string corresponding to element of ParseTree (position and length in bytes) } property TreeToken[ParseTreeNode: integer]: string read GetTreeToken; property TotalSizeBytes: int64 read GetTotalSizeBytes; end; TGrammarType = ( gtUnknown, { invalid/not initialized properly } gtLink, { link to another rule } gtString, { Delphi-compatible string (2 bytes per char) + CaseSensitive flag } gtChar, { range of chars + CaseSensitive flag } gtCharClass, { char class (letter, digit, whitespace etc) } gtCharSet, { set of chars + CaseSensitive flag } gtBytes, { any sequence/array of bytes } gtSequence, { sequence of rules (accepted if all rules in the sequence are accepted in defined order) } gtSelection, { selection from several rules (accepted when first rule in the list is accepted) } gtRepeat, { greedy repeater (accepted if operand rule is accepted N times and N is in the range) } gtNot, { negation, doesn't consume data from the input buffer (accepted if operand rule is not accepted) } gtEOF); { accepted if all data is read from the input (input buffer is empty already) } { basic class for grammar definition } TGrammarClass = class abstract(TEnumerable<IInterfacedObject<TGrammarClass>>) protected type TCustomGrammarEnumerator = class(TEnumerator<IInterfacedObject<TGrammarClass>>) protected FItems: TVector<IInterfacedObject<TGrammarClass>>; FPos: integer; function DoGetCurrent: IInterfacedObject<TGrammarClass>; override; function DoMoveNext: Boolean; override; public constructor Create(AGrammar: TGrammarClass); end; TAllRulesEnumeratorPreProcessing = class(TEnumerator<TGrammarClass>) protected Queue: TVector<IInterfacedObject<TGrammarClass>>; IdSet: TSet<TRuleId>; CurrentItemInt: IInterfacedObject<TGrammarClass>; CurrentItem: TGrammarClass; Operands: TVector<IInterfacedObject<TGrammarClass>>; StartGrammar: TGrammarClass; function DoGetCurrent: TGrammarClass; override; function DoMoveNext: Boolean; override; public constructor Create(AStartGrammar: TGrammarClass); end; TAllRulesEnumeratorPostProcessing = class(TEnumerator<TGrammarClass>) protected Queue: TVector<IInterfacedObject<TGrammarClass>>; IdSet: TSet<TRuleId>; CurrentItemInt: IInterfacedObject<TGrammarClass>; CurrentItem: TGrammarClass; Operands: TVector<IInterfacedObject<TGrammarClass>>; StartGrammar: TGrammarClass; function DoGetCurrent: TGrammarClass; override; function DoMoveNext: Boolean; override; public constructor Create(AStartGrammar: TGrammarClass); end; TAllRulesCollection = class(TEnumerable<TGrammarClass>) protected StartGrammar: TGrammarClass; PreProcess: Boolean; function DoGetEnumerator: TEnumerator<TGrammarClass>; override; public constructor Create(AStartGrammar: TGrammarClass; APreProcess: Boolean); end; class var FIdCnt: TRuleId; FActiveInstCount: int64; var FGrammarType: TGrammarType; FId: TRuleId; FIncludeIntoParseTree: Boolean; FName: string; { Enumerates all operands (child rules without recursion). Implements TEnumerate using GetOperands } function DoGetEnumerator: TEnumerator<IInterfacedObject<TGrammarClass>>; override; function GetInfo: string; virtual; class function GetOperandInfo(Operand: TGrammarClass): string; overload; static; class function GetOperandInfo(const Operand: IInterfacedObject<TGrammarClass>): string; overload; static; procedure SetIncludeIntoParseTree(const Value: Boolean); virtual; procedure DoRelease; virtual; abstract; function GetAllRulesCollection(PreProcess: Boolean): TAllRulesCollection; public constructor Create(AGrammarType: TGrammarType); destructor Destroy; override; { release internal links (IInterfacedObject<TGrammarClass> etc) to avoid circular references etc } procedure Release; { add operands to the collections } procedure GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>); virtual; abstract; { called once for main rule by parser (TPegParser for example) } procedure SetupMainRule; virtual; { called by SetupMainRule for every rule in the tree (one time when parser is initializing) } procedure SetupRule; virtual; property GrammarType: TGrammarType read FGrammarType; { global (process-wide) identifier of the instance } property Id: TRuleId read FId; { descriptive/readable text presentation (for logging etc) } property Info: string read GetInfo; { Default = True for TGrammar rules and False for other (intermediate) rules. } property IncludeIntoParseTree: Boolean read FIncludeIntoParseTree write SetIncludeIntoParseTree; { user friendly name (can be set by user) } property Name: string read FName write FName; { Non-recursive enumerator for all subrules including rule where method is called. PreProcess=True : rule is returned first, after that subrules are enlisted (when we initialize subrules for example) PreProcess=False : subrules are enlisted first, after that rule is returned (when we finalize subrules for example) } property AllRules[PreProcess: Boolean]: TAllRulesCollection read GetAllRulesCollection; class property ActiveInstCount: int64 read FActiveInstCount; end; implementation { TParseTreeItem } procedure TParseTreeItem.Init(ARule: TGrammarClass; AStart,ALen: integer); begin {$IF SizeOf(TParseTreeItem)<>SizeOf(Rule)+SizeOf(Position)} Self := Default(TParseTreeItem); {$ENDIF} Rule := ARule; Position.SetPos(AStart, ALen); end; procedure TParseTreeItem.Init(const ASrc: TParseTreeItem); begin {$IF SizeOf(TParseTreeItem)<>SizeOf(Rule)+SizeOf(Position)} Self := Default(TParseTreeItem); {$ENDIF} Rule := ASrc.Rule; Position := ASrc.Position; end; { TParseTree.TRuleMatchesCollection } procedure TParseTree.TRuleMatchesCollection.Init(ATree: TTreeArrayClass<TParseTreeItem>; ARoot: integer; const ARuleId: TruleId); begin {$IF SizeOf(TRuleMatchesCollection)<>SizeOf(Tree)+SizeOf(Root)+SizeOf(RuleId)} Self := Default(TRuleMatchesCollection); {$ENDIF} Tree := ATree; Root := ARoot; RuleId := ARuleId; end; function TParseTree.TRuleMatchesCollection.GetEnumerator: TRuleMatchesEnumerator; begin result.Init(Tree, Root, RuleId); end; { TParseTree.TRuleMatchesEnumerator } procedure TParseTree.TRuleMatchesEnumerator.Init(ANodes: TTreeArrayClass<TParseTreeItem>; ARoot: integer; const ARuleId: TruleId); begin {$IF SizeOf(TRuleMatchesEnumerator)<>SizeOf(Enum)+SizeOf(Nodes)+SizeOf(RuleId)} Self := Default(TRuleMatchesEnumerator); {$ENDIF} Enum.Init(ANodes.Nodes, ARoot); Nodes := ANodes; RuleId := ARuleId; end; function TParseTree.TRuleMatchesEnumerator.MoveNext: Boolean; begin repeat result := Enum.MoveNext; until not result or (Nodes[Enum.Current].Rule.Id=RuleId); end; function TParseTree.TRuleMatchesEnumerator.CurrentNode: integer; begin result := Enum.Current; end; { TParseTree } function TParseTree.Add(ARule: TGrammarClass; AStart, ALen: integer): integer; var Node: TParseTreeItem; begin Node.Rule := ARule; Node.Position.Start := AStart; Node.Position.Len := ALen; result := Tree.Add(Node); end; function TParseTree.Append(ARule: TGrammarClass; AStart, ALen: integer): integer; var Node: TParseTreeItem; begin Node.Rule := ARule; Node.Position.Start := AStart; Node.Position.Len := ALen; result := Tree.Append(Node); end; function TParseTree.Append: integer; begin result := Tree.Append; end; function TParseTree.Commit(ARule: TGrammarClass; AStart, ALen: integer): integer; begin result := Tree.Commit; Tree.Nodes.Items[result].Data.Init(ARule, AStart, ALen); end; function TParseTree.Commit: integer; begin result := Tree.Commit(False); end; procedure TParseTree.Rollback; begin Tree.Rollback; end; procedure TParseTree.Clear; begin Tree.Clear; Root := -1; end; constructor TParseTree.Create; begin inherited Create; Tree := TTreeArrayClass<TParseTreeItem>.Create; end; destructor TParseTree.Destroy; begin FreeAndNil(Tree); inherited; end; function TParseTree.GetChilds(ARoot: integer): TSubtreeCollection; begin result.Init(Tree.Nodes, ARoot); end; function TParseTree.GetRuleMatches(RootNode: integer; const RuleId: TRuleId): TRuleMatchesCollection; begin result.Init(Tree, RootNode, RuleId); end; function TParseTree.GetCount: integer; begin result := Tree.Count; end; function TParseTree.GetEnumerator: TSubtreeEnumerator; begin result.Init(Tree.Nodes, Root); end; function TParseTree.GetItem(n: integer): TParseTreeItem; begin result := Tree.Nodes[n].Data; end; function TParseTree.GetFirstChild(Node: integer): integer; begin result := Tree.Nodes[Node].FirstChild; end; function TParseTree.GetNextSibling(Node: integer): integer; begin result := Tree.Nodes[Node].NextSibling; end; function TParseTree.GetSubTree(StartNode: integer; FilterProc: TFilterTreeProc): TParseTree; var Stack: TVector<TCompound<integer,integer>>; { Src, DstParent } DstLastChild: TVector<integer>; { indices in Dst } I: TCompound<integer,integer>; J: integer; Accept: Boolean; begin Result := TParseTree.Create; Stack.Clear; DstLastChild.Clear; if Root >= 0 then Stack.Add(TCompound<integer,integer>.Create(Root, -1)); while Stack.Count>0 do begin I := Stack.ExtractLast; Accept := True; FilterProc(Tree, I.A, Accept); if Accept then begin J := Result.Tree.Add; Result.Tree.Nodes[J].Data.Init(Tree.Nodes[I.A].Data); DstLastChild.Add(-1); if I.B >= 0 then begin if Result.Tree.Nodes[I.B].FirstChild < 0 then Result.Tree.Nodes.Items[I.B].FirstChild := J else Result.Tree.Nodes.Items[DstLastChild[I.B]].NextSibling := J; DstLastChild[I.B] := J; end; I.B := J; end; J := Stack.Count; I.A := Tree.Nodes[I.A].FirstChild; while I.A >= 0 do begin Stack.Add(I); I.A := Tree.Nodes[I.A].NextSibling; end; if Stack.Count > J then TArrayUtils.Inverse<TCompound<integer,integer>>(Stack.Items, J, Stack.Count-J); end; Result.Tree.Nodes.TrimExcess; end; function TParseTree.GetTotalSizeBytes: int64; begin result := Tree.TotalSizeBytes + SizeOf(Root); end; procedure TParseTree.LogTextInputParseTree(var InputData: TBuffer); procedure L(const S: string; const Args: array of const; Margin: integer); begin {$IF Defined(LogGrammar)} AppLog.Log(StringOfChar(' ', Margin) + Format(S, Args)); {$ENDIF} end; function ShowWS(const S: string): String; const CWhiteSpace = #$2591 { shade char to show trailing spaces }; { arrows are not available for most of mono fonts, we use russian char instead } //#$2B10; { arrow char to show empty string position } CEmptyStrPos = 'Ã'; var I: Integer; begin result := S; { we replace trailing whitespaces to make them visible } for I := Low(Result) to High(Result) do if Result[I].IsWhiteSpace then Result[I] := CWhiteSpace else Break; for I := High(Result) downto Low(Result) do if Result[I].IsWhiteSpace then Result[I] := CWhiteSpace else Break; { we replace empty string to indicate position } if Result='' then Result := CEmptyStrPos; end; procedure LogTree(ResIndex, Margin: integer); var R: TParseTreeItem; S,T: string; begin while ResIndex>=0 do begin R := Tree.Nodes.Items[ResIndex].Data; Assert(R.Position.Len mod SizeOf(Char)=0); L('%s Pos: %d Len: %d)', [R.Rule.Info, R.Position.Start, R.Position.Len], Margin); InputData.Position := R.Position.Start; InputData.Read(S, R.Position.Len div SizeOf(Char)); T := InputData.Text; if T=S then L(' %s', [TEnc.GetPrintable(S)], Margin) else begin L(' %s', [StringOfChar(' ', R.Position.Start div 2) + ShowWS(TEnc.GetPrintable(S)) ], Margin); L(' %s', [ShowWS(TEnc.GetPrintable(T))], Margin); end; LogTree(Tree.Nodes.Items[ResIndex].FirstChild, Margin + 2); ResIndex := Tree.Nodes.Items[ResIndex].NextSibling; end; end; begin {$IF Defined(LogEnabled)} LogTree(0, 0); {$ENDIF} end; procedure TParseTree.SetItem(n: integer; const Item: TParseTreeItem); begin Tree.Nodes.Items[N].Data := Item; end; { TGrammarClass.TCustomGrammarEnumerator } constructor TGrammarClass.TCustomGrammarEnumerator.Create(AGrammar: TGrammarClass); begin FItems.Clear; AGrammar.GetOperands(FItems); FPos := 0; end; function TGrammarClass.TCustomGrammarEnumerator.DoGetCurrent: IInterfacedObject<TGrammarClass>; begin result := FItems[FPos-1]; end; function TGrammarClass.TCustomGrammarEnumerator.DoMoveNext: Boolean; begin result := FPos < FItems.Count; if result then inc(FPos); end; { TGrammarClass.TAllRulesEnumeratorPreProcessing } constructor TGrammarClass.TAllRulesEnumeratorPreProcessing.Create(AStartGrammar: TGrammarClass); begin inherited Create; StartGrammar := AStartGrammar; end; function TGrammarClass.TAllRulesEnumeratorPreProcessing.DoGetCurrent: TGrammarClass; begin result := CurrentItem; end; function TGrammarClass.TAllRulesEnumeratorPreProcessing.DoMoveNext: Boolean; var I: Integer; Item: IInterfacedObject<TGrammarClass>; begin if StartGrammar<>nil then begin CurrentItemInt := nil; CurrentItem := StartGrammar; StartGrammar := nil; Queue.Clear; IdSet.Init; IdSet.Add(CurrentItem.Id); Exit(True); end; if CurrentItem=nil then Exit(False); { We return current item (rule) first and only at next iteration we ask for operands. It allows caller to initialize/preprocess operands. } Operands.Clear; CurrentItem.GetOperands(Operands); for I := 0 to Operands.Count-1 do begin Item := Operands[I]; Assert(Item<>nil, 'Operand is not initialized'); if not (Item.Data.Id in IdSet) then begin IdSet.Add(Item.Data.Id); Queue.Add(Item); end; end; result := not Queue.Empty; if result then begin CurrentItemInt := Queue.ExtractLast; CurrentItem := CurrentItemInt.Data; end else begin CurrentItemInt := nil; CurrentItem := nil; end; end; { TGrammarClass.TAllRulesEnumeratorPostProcessing } constructor TGrammarClass.TAllRulesEnumeratorPostProcessing.Create(AStartGrammar: TGrammarClass); begin inherited Create; StartGrammar := AStartGrammar; end; function TGrammarClass.TAllRulesEnumeratorPostProcessing.DoGetCurrent: TGrammarClass; begin result := CurrentItem; end; function TGrammarClass.TAllRulesEnumeratorPostProcessing.DoMoveNext: Boolean; var I: Integer; Item: IInterfacedObject<TGrammarClass>; begin if StartGrammar<>nil then begin CurrentItemInt := nil; CurrentItem := StartGrammar; StartGrammar := nil; Queue.Clear; IdSet.Init; IdSet.Add(CurrentItem.Id); end else begin if Queue.Empty then Exit(False); CurrentItemInt := Queue.ExtractLast; CurrentItem := CurrentItemInt.Data; end; { We ask for operands and only after that return the item (rule). It allows caller to process childs even if item is finilazied. } Operands.Clear; CurrentItem.GetOperands(Operands); for I := 0 to Operands.Count-1 do begin Item := Operands[I]; Assert(Item<>nil, 'Operand is not initialized'); if not (Item.Data.Id in IdSet) then begin IdSet.Add(Item.Data.Id); Queue.Add(Item); end; end; result := true; end; { TGrammarClass.TAllRulesCollection } constructor TGrammarClass.TAllRulesCollection.Create(AStartGrammar: TGrammarClass; APreProcess: Boolean); begin inherited Create; StartGrammar := AStartGrammar; PreProcess := APreProcess; end; function TGrammarClass.TAllRulesCollection.DoGetEnumerator: TEnumerator<TGrammarClass>; begin if PreProcess then result := TAllRulesEnumeratorPreProcessing.Create(StartGrammar) else result := TAllRulesEnumeratorPostProcessing.Create(StartGrammar); end; { TGrammarClass } constructor TGrammarClass.Create(AGrammarType: TGrammarType); begin {$IFDEF Debug} Inc(FActiveInstCount); {$ENDIF} inc(FIdCnt); FId := FIdCnt; FGrammarType := AGrammarType; FIncludeIntoParseTree := False; end; destructor TGrammarClass.Destroy; begin {$IFDEF Debug} Dec(FActiveInstCount); {$ENDIF} inherited; end; function TGrammarClass.DoGetEnumerator: TEnumerator<IInterfacedObject<TGrammarClass>>; begin result := TCustomGrammarEnumerator.Create(Self); end; function TGrammarClass.GetAllRulesCollection(PreProcess: Boolean): TAllRulesCollection; begin result := TAllRulesCollection.Create(Self, PreProcess); end; function TGrammarClass.GetInfo: string; begin result := Format('%s#%d %s (%s)', [IfThen(Name='','',Format('{%s} ',[Name])), Id, TEnumeration<TGrammarType>.ToString(FGrammarType), ClassName]); end; class function TGrammarClass.GetOperandInfo(const Operand: IInterfacedObject<TGrammarClass>): string; begin if Operand=nil then result := 'Op:nil' else result := GetOperandInfo(Operand.Data); end; procedure TGrammarClass.Release; var Item: TGrammarClass; begin for Item in AllRules[False] do Item.DoRelease; end; class function TGrammarClass.GetOperandInfo(Operand: TGrammarClass): string; var Operands: TVector<IInterfacedObject<TGrammarClass>>; begin if Operand=nil then result := 'Op:nil' else if Operand.FGrammarType=gtLink then begin Operands.Clear; Operand.GetOperands(Operands); Assert(Operands.Count=1); result := Format('Op:%s(#%d)={#%d: %s}', [ TEnumeration<TGrammarType>.ToString(Operand.GrammarType), Operand.Id, Operands[0].Data.Id, TEnumeration<TGrammarType>.ToString(Operands[0].Data.GrammarType) ]) end else result := Format('Op:%s (#%d)', [TEnumeration<TGrammarType>.ToString(Operand.GrammarType), Operand.Id]); end; procedure TGrammarClass.SetIncludeIntoParseTree(const Value: Boolean); begin FIncludeIntoParseTree := Value; end; procedure TGrammarClass.SetupMainRule; var Item: TGrammarClass; begin inherited; for Item in AllRules[True] do Item.SetupRule; end; procedure TGrammarClass.SetupRule; begin end; { TGrammarParser } constructor TGrammarParser.Create(AMainRule: TGrammarClass); begin inherited Create; Grammar := AMainRule; Grammar.SetupMainRule; ParseTree := TParseTree.Create; end; constructor TGrammarParser.Create(AMainRule: IInterfacedObject<TGrammarClass>); begin Create(AMainRule.Data); end; destructor TGrammarParser.Destroy; begin if Grammar<>nil then Grammar.Release; FreeAndNil(ParseTree); inherited; end; function TGrammarParser.GetTotalSizeBytes: int64; begin result := Data.Size + ParseTree.TotalSizeBytes; end; function TGrammarParser.GetTreeToken(ParseTreeNode: integer): string; begin Result := DataToken[ParseTree.Tree.Nodes[ParseTreeNode].Data.Position]; end; function TGrammarParser.GetDataToken(const P: TTokenPos): string; begin Assert(P.Len mod SizeOf(Char) = 0); Data.Position := P.Start; Data.Read(Result, P.Len div SizeOf(Char)); end; function TGrammarParser.Accepts(const AData: TBuffer): Boolean; begin Data := AData; Data.Position := 0; Result := Accepted; end; function TGrammarParser.Accepts(const AData: string): Boolean; begin Data.Text := AData; Result := Accepted; end; procedure TGrammarParser.Clear; begin Data.Clear; end; end.
unit JD.Weather.WUnderground; interface uses System.Classes, System.SysUtils, System.Generics.Collections, System.Types, System.UITypes, Vcl.Graphics, Vcl.Imaging.Jpeg, Vcl.Imaging.PngImage, Vcl.Imaging.GifImg, JD.Weather, JD.Weather.Intf, SuperObject; type TWUEndpoint = (weAll, weAlerts, weAlmanac, weAstronomy, weConditions, weCurrentHurricane, weForecast, weForecast10Day, weGeoLookup, weHistory, weHourly, weHourly10Day, wePlanner, weRawTide, weTide, weWebCams, weYesterday, weRadar, weSatellite, weRadarSatellite, weAniRadar, weAniSatellite, weAniRadarSatellite); TWUWeatherThread = class(TJDWeatherThread) public procedure FillConditions(const O: ISuperObject; Conditions: TWeatherConditions); procedure FillForecast(const O: ISuperObject; Forecast: TWeatherForecast); procedure FillForecastHourly(const O: ISuperObject; Forecast: TWeatherForecast); procedure FillForecastDaily(const O: ISuperObject; Forecast: TWeatherForecast); procedure FillAlerts(const O: ISuperObject; Alerts: TWeatherAlerts); procedure FillMaps(const O: ISuperObject; Maps: TWeatherMaps); function GetEndpointUrl(const Endpoint: TWUEndpoint): String; private function StrToAlertType(const S: String): TWeatherAlertType; public function GetUrl: String; override; function DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast; ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; override; function DoConditions(Conditions: TWeatherConditions): Boolean; override; function DoForecast(Forecast: TWeatherForecast): Boolean; override; function DoForecastHourly(Forecast: TWeatherForecast): Boolean; override; function DoForecastDaily(Forecast: TWeatherForecast): Boolean; override; function DoAlerts(Alerts: TWeatherAlerts): Boolean; override; function DoMaps(Maps: TWeatherMaps): Boolean; override; end; implementation uses DateUtils, StrUtils, Math; { TWUWeatherThread } function TWUWeatherThread.GetUrl: String; begin Result:= 'http://api.wunderground.com/api/'+Owner.Key+'/'; end; function TWUWeatherThread.GetEndpointUrl(const Endpoint: TWUEndpoint): String; var S: String; begin case Endpoint of weAll: S:= 'conditions/alerts/hourly/forecast10day'; weAlerts: S:= 'alerts'; weAlmanac: S:= 'almanac'; weAstronomy: S:= 'astronomy'; weConditions: S:= 'conditions'; weCurrentHurricane: S:= 'currenthurricane'; weForecast: S:= 'forecast'; weForecast10Day: S:= 'forecast10day'; weGeoLookup: S:= 'geolookup'; weHistory: S:= 'history'; weHourly: S:= 'hourly'; weHourly10Day: S:= 'hourly10day'; wePlanner: S:= 'planner'; weRawTide: S:= 'rawtide'; weTide: S:= 'tide'; weWebCams: S:= 'webcams'; weYesterday: S:= 'yesterday'; weRadar: S:= 'radar'; weSatellite: S:= 'satellite'; weRadarSatellite: S:= 'radar/satellite'; weAniRadar: S:= 'animatedradar'; weAniSatellite: S:= 'animatedsatellite'; weAniRadarSatellite: S:= 'animatedradar/animatedsatellite'; end; Result:= GetUrl + S + '/q/'; end; function TWUWeatherThread.DoAll(Conditions: TWeatherConditions; Forecast: TWeatherForecast; ForecastDaily: TWeatherForecast; ForecastHourly: TWeatherForecast; Alerts: TWeatherAlerts; Maps: TWeatherMaps): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weAll); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; wlCityCode: ; wlCountryCity: ; wlAirportCode: ; wlPWS: ; end; S:= Web.Get(U); O:= SO(S); FillConditions(O, Conditions); FillForecast(O, Forecast); FillForecastHourly(O, ForecastHourly); FillForecastDaily(O, ForecastDaily); FillAlerts(O, Alerts); DoMaps(Maps); Result:= True; except on E: Exception do begin end; end; end; function TWUWeatherThread.DoConditions(Conditions: TWeatherConditions): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weConditions); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; end; S:= Web.Get(U); O:= SO(S); FillConditions(O, Conditions); Result:= True; except on E: Exception do begin end; end; end; function TWUWeatherThread.DoForecast(Forecast: TWeatherForecast): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weForecast); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; end; S:= Web.Get(U); O:= SO(S); FillForecast(O, Forecast); Result:= True; except on E: Exception do begin end; end; end; function TWUWeatherThread.DoForecastDaily(Forecast: TWeatherForecast): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weForecast10Day); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; end; S:= Web.Get(U); O:= SO(S); FillForecastDaily(O, Forecast); Result:= True; except on E: Exception do begin end; end; end; function TWUWeatherThread.DoForecastHourly(Forecast: TWeatherForecast): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weHourly); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; end; S:= Web.Get(U); O:= SO(S); FillForecastHourly(O, Forecast); Result:= True; except on E: Exception do begin end; end; end; function TWUWeatherThread.DoAlerts(Alerts: TWeatherAlerts): Boolean; var U: String; S: String; O: ISuperObject; begin Result:= False; try U:= GetEndpointUrl(TWUEndpoint.weAlerts); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.json'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.json'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.json'; wlAutoIP: U:= U + 'autoip.json'; end; S:= Web.Get(U); O:= SO(S); FillAlerts(O, Alerts); Result:= True; except on E: Exception do begin end; end; end; function MapOptions( const Width: Integer = 400; const Height: Integer = 400; const NumFrames: Integer = 10; const Delay: Integer = 50; const FrameIndex: Integer = 0; const NoClutter: Boolean = True; const SmoothColors: Boolean = True; const RainSnow: Boolean = True; const TimeLabel: Boolean = True; const TimeLabelX: Integer = 10; const TimeLabelY: Integer = 20): String; begin Result:= 'newmaps=1'; Result:= Result + '&width='+IntToStr(Width); Result:= Result + '&height='+IntToStr(Height); Result:= Result + '&delay='+IntToStr(Delay); Result:= Result + '&num='+IntToStr(NumFrames); Result:= Result + '&frame='+IntToStr(FrameIndex); Result:= Result + '&noclutter='+IfThen(NoClutter, '1','0'); Result:= Result + '&smooth='+IfThen(SmoothColors, '1','0'); Result:= Result + '&rainsnow='+IfThen(RainSnow, '1','0'); if TimeLabel then begin Result:= Result + '&timelabel=1'; Result:= Result + '&timelabel.x='+IntToStr(TimeLabelX); Result:= Result + '&timelabel.y='+IntToStr(TimeLabelY); end; end; function TWUWeatherThread.DoMaps(Maps: TWeatherMaps): Boolean; var S: TMemoryStream; U: String; I: TGifImage; procedure GetMap(const EP: TWUEndpoint; const MT: TWeatherMapType); begin U:= GetEndpointUrl(EP); case Owner.LocationType of wlZip: U:= U + Owner.LocationDetail1+'.gif'; wlCityState: U:= U + Owner.LocationDetail2+'/'+Owner.LocationDetail1+'.gif'; wlCoords: U:= U + Owner.LocationDetail1+','+Owner.LocationDetail2+'.gif'; wlAutoIP: U:= U + 'autoip.gif'; end; U:= U + '?'+MapOptions(700, 700, 15, 60); Web.Get(U, S); S.Position:= 0; I.LoadFromStream(S); S.Clear; S.Position:= 0; {$IFDEF USE_VCL} Maps.Maps[MT].Assign(I); {$ELSE} {$ENDIF} end; begin Result:= False; try S:= TMemoryStream.Create; try I:= TGifImage.Create; try if mpRadar in Owner.WantedMaps then GetMap(weRadar, mpRadar); if mpSatellite in Owner.WantedMaps then GetMap(weSatellite, mpSatellite); if mpSatelliteRadar in Owner.WantedMaps then GetMap(weRadarSatellite, mpSatelliteRadar); if mpAniRadar in Owner.WantedMaps then GetMap(weAniRadar, mpAniRadar); Result:= True; finally I.Free; end; finally S.Free; end; except end; end; procedure TWUWeatherThread.FillConditions(const O: ISuperObject; Conditions: TWeatherConditions); var OB, L: ISuperObject; function LD(const O: ISuperObject; const N: String): Double; var T: String; begin T:= O.S[N]; Result:= StrToFloatDef(T, 0); end; begin OB:= O.O['current_observation']; if not Assigned(OB) then Exit; L:= OB.O['display_location']; if not Assigned(L) then Exit; Conditions.FLocation.FDisplayName:= L.S['full']; Conditions.FLocation.FCity:= L.S['city']; Conditions.FLocation.FState:= L.S['state_name']; Conditions.FLocation.FStateAbbr:= L.S['state']; Conditions.FLocation.FCountry:= L.S['country']; Conditions.FLocation.FCountryAbbr:= L.S['country_iso3166']; Conditions.FLocation.FLongitude:= LD(L, 'longitude'); Conditions.FLocation.FLatitude:= LD(L, 'latitude'); Conditions.FLocation.FElevation:= LD(L, 'elevation'); Conditions.FLocation.FZipCode:= L.S['zip']; case Owner.Units of wuKelvin: begin //Not Supported end; wuImperial: begin Conditions.FTemp:= OB.D['temp_f']; Conditions.FVisibility:= LD(OB, 'visibility_mi'); Conditions.FDewPoint:= OB.D['dewpoint_f']; end; wuMetric: begin Conditions.FTemp:= OB.D['temp_c']; Conditions.FVisibility:= LD(OB, 'visibility_km'); Conditions.FDewPoint:= OB.D['dewpoint_c']; end; end; Conditions.FDateTime:= Now; //TODO Conditions.FHumidity:= LD(OB, 'relative_humidity'); Conditions.FPressure:= LD(OB, 'pressure_mb'); Conditions.FCondition:= OB.S['weather']; Conditions.FDescription:= OB.S['weather']; Conditions.FWindSpeed:= OB.D['wind_mph']; Conditions.FWindDir:= OB.D['wind_degrees']; {$IFDEF USE_VCL} LoadPicture(OB.S['icon_url'], Conditions.FPicture); {$ENDIF} end; procedure TWUWeatherThread.FillForecast(const O: ISuperObject; Forecast: TWeatherForecast); var OB: ISuperObject; A: TSuperArray; I: TWeatherForecastItem; X: Integer; function LD(const O: ISuperObject; const N: String): Double; var T: String; begin T:= O.S[N]; Result:= StrToFloatDef(T, 0); end; begin A:= O.A['hourly_forecast']; if not Assigned(A) then begin Exit; end; for X := 0 to A.Length-1 do begin OB:= A.O[X]; I:= TWeatherForecastItem.Create(Forecast); try case Owner.Units of wuKelvin: begin //TODO: NOT SUPPORTED - Calculate? I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0); I.FWindSpeed:= OB.O['wspd'].D['metric']; end; wuImperial: begin I.FTempMin:= StrToFloatDef(OB.O['temp'].S['english'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['english'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['english'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['english'], 0); end; wuMetric: begin I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['metric'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0); end; end; I.FDateTime:= EpochLocal(StrToIntDef(OB.O['FCTTIME'].S['epoch'], 0)); I.FTemp:= I.FTempMax; //TODO I.FHumidity:= StrToFloatDef(OB.S['humidity'], 0); I.FPressure:= 0; I.FCondition:= OB.S['condition']; I.FDescription:= OB.S['condition']; I.FWindDir:= StrToFloatDef(OB.O['wdir'].S['degrees'], 0); I.FVisibility:= 0; {$IFDEF USE_VCL} LoadPicture(OB.S['icon_url'], I.FPicture); {$ENDIF} finally Forecast.FItems.Add(I); end; end; end; procedure TWUWeatherThread.FillForecastDaily(const O: ISuperObject; Forecast: TWeatherForecast); var OB: ISuperObject; A: TSuperArray; I: TWeatherForecastItem; X: Integer; function LD(const O: ISuperObject; const N: String): Double; var T: String; begin T:= O.S[N]; Result:= StrToFloatDef(T, 0); end; begin OB:= O.O['forecast']; if not Assigned(OB) then begin Exit; end; OB:= OB.O['simpleforecast']; if not Assigned(OB) then begin Exit; end; A:= OB.A['forecastday']; if not Assigned(A) then begin Exit; end; for X := 0 to A.Length-1 do begin OB:= A.O[X]; I:= TWeatherForecastItem.Create(Forecast); try case Owner.Units of wuKelvin: begin //TODO: NOT SUPPORTED - Calculate? I.FTempMin:= StrToFloatDef(OB.O['low'].S['celsius'], 0); I.FTempMax:= StrToFloatDef(OB.O['high'].S['celsius'], 0); I.FWindSpeed:= OB.O['avewind'].D['kph']; I.FDewPoint:= 0; //Not Supported end; wuImperial: begin I.FTempMin:= StrToFloatDef(OB.O['low'].S['ferenheit'], 0); I.FTempMax:= StrToFloatDef(OB.O['high'].S['ferenheit'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['avewind'].S['mph'], 0); I.FDewPoint:= 0; //Not Supported end; wuMetric: begin I.FTempMin:= StrToFloatDef(OB.O['low'].S['celsius'], 0); I.FTempMax:= StrToFloatDef(OB.O['high'].S['celsius'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['avewind'].S['kph'], 0); I.FDewPoint:= 0; //Not Supported end; end; I.FDateTime:= EpochLocal(StrToIntDef(OB.O['date'].S['epoch'], 0)); I.FTemp:= I.FTempMax; //TODO I.FHumidity:= StrToFloatDef(OB.S['avehumidity'], 0); I.FPressure:= 0; I.FCondition:= OB.S['conditions']; I.FDescription:= OB.S['conditions']; I.FWindDir:= StrToFloatDef(OB.O['avewind'].S['degrees'], 0); I.FVisibility:= 0; //Not Supported {$IFDEF USE_VCL} LoadPicture(OB.S['icon_url'], I.FPicture); {$ENDIF} finally Forecast.FItems.Add(I); end; end; end; procedure TWUWeatherThread.FillForecastHourly(const O: ISuperObject; Forecast: TWeatherForecast); var OB: ISuperObject; A: TSuperArray; I: TWeatherForecastItem; X: Integer; function LD(const O: ISuperObject; const N: String): Double; var T: String; begin T:= O.S[N]; Result:= StrToFloatDef(T, 0); end; begin A:= O.A['hourly_forecast']; if not Assigned(A) then begin Exit; end; for X := 0 to A.Length-1 do begin OB:= A.O[X]; I:= TWeatherForecastItem.Create(Forecast); try case Owner.Units of wuKelvin: begin //TODO: NOT SUPPORTED - Calculate? I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0); I.FWindSpeed:= OB.O['wspd'].D['metric']; end; wuImperial: begin I.FTempMin:= StrToFloatDef(OB.O['temp'].S['english'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['english'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['english'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['english'], 0); end; wuMetric: begin I.FTempMin:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FTempMax:= StrToFloatDef(OB.O['temp'].S['metric'], 0); I.FWindSpeed:= StrToFloatDef(OB.O['wspd'].S['metric'], 0); I.FDewPoint:= StrToFloatDef(OB.O['dewpoint'].S['metric'], 0); end; end; I.FDateTime:= EpochLocal(StrToIntDef(OB.O['FCTTIME'].S['epoch'], 0)); I.FTemp:= I.FTempMax; //TODO I.FHumidity:= StrToFloatDef(OB.S['humidity'], 0); I.FPressure:= 0; I.FCondition:= OB.S['condition']; I.FDescription:= OB.S['condition']; I.FWindDir:= StrToFloatDef(OB.O['wdir'].S['degrees'], 0); I.FVisibility:= 0; {$IFDEF USE_VCL} LoadPicture(OB.S['icon_url'], I.FPicture); {$ENDIF} finally Forecast.FItems.Add(I); end; end; end; function TWUWeatherThread.StrToAlertType(const S: String): TWeatherAlertType; procedure Chk(const Val: String; const T: TWeatherAlertType); begin if SameText(S, Val) then begin Result:= T; end; end; begin Chk('', TWeatherAlertType.waNone); Chk('HUR', TWeatherAlertType.waHurricaneStat); Chk('TOR', TWeatherAlertType.waTornadoWarn); Chk('TOW', TWeatherAlertType.waTornadoWatch); Chk('WRN', TWeatherAlertType.waSevThundWarn); Chk('SEW', TWeatherAlertType.waSevThundWatch); Chk('WIN', TWeatherAlertType.waWinterAdv); Chk('FLO', TWeatherAlertType.waFloodWarn); Chk('WAT', TWeatherAlertType.waFloodWatch); Chk('WND', TWeatherAlertType.waHighWind); Chk('SVR', TWeatherAlertType.waSevStat); Chk('HEA', TWeatherAlertType.waHeatAdv); Chk('FOG', TWeatherAlertType.waFogAdv); Chk('SPE', TWeatherAlertType.waSpecialStat); Chk('FIR', TWeatherAlertType.waFireAdv); Chk('VOL', TWeatherAlertType.waVolcanicStat); Chk('HWW', TWeatherAlertType.waHurricaneWarn); Chk('REC', TWeatherAlertType.waRecordSet); Chk('REP', TWeatherAlertType.waPublicRec); Chk('PUB', TWeatherAlertType.waPublicStat); end; procedure TWUWeatherThread.FillAlerts(const O: ISuperObject; Alerts: TWeatherAlerts); var A: TSuperArray; Tmp: Int64; I: TWeatherAlert; Obj: ISuperObject; X: Integer; function LD(const O: ISuperObject; const N: String): Double; var T: String; begin T:= O.S[N]; Result:= StrToFloatDef(T, 0); end; begin A:= O.A['alerts']; if not Assigned(A) then Exit; for X := 0 to A.Length-1 do begin Obj:= A.O[X]; I:= TWeatherAlert.Create; try I.FAlertType:= StrToAlertType(Obj.S['type']); I.FDescription:= Obj.S['description']; Tmp:= StrToIntDef(Obj.S['date_epoch'], 0); I.FDateTime:= EpochLocal(Tmp); Tmp:= StrToIntDef(Obj.S['expires_epoch'], 0); I.FExpires:= EpochLocal(Tmp); I.FMsg:= Obj.S['message']; I.FPhenomena:= Obj.S['phenomena']; I.FSignificance:= Obj.S['significance']; //Zones //Storm finally Alerts.FItems.Add(I); end; end; end; procedure TWUWeatherThread.FillMaps(const O: ISuperObject; Maps: TWeatherMaps); begin end; end.
unit SortExtendedArrayBenchmark1Unit; {$mode delphi} interface uses Windows, BenchmarkClassUnit, Classes, Math; type TSortExtendedArrayThreads = class(TFastcodeMMBenchmark) public procedure RunBenchmark; override; class function GetBenchmarkName: string; override; class function GetBenchmarkDescription: string; override; class function GetSpeedWeight: Double; override; class function GetCategory: TBenchmarkCategory; override; end; implementation uses SysUtils; type TSortExtendedArrayThread = class(TThread) FBenchmark: TFastcodeMMBenchmark; procedure Execute; override; end; TExtended = record X : Extended; Pad1, Pad2, Pad3, Pad4, Pad5, Pad6 : Byte; end; TExtendedArray = array[0..1000000] of TExtended; PExtendedArray = ^TExtendedArray; procedure TSortExtendedArrayThread.Execute; var ExtArray : PExtendedArray; Size, I1, I2, I3, IndexMax, RunNo, LowIndex, HighIndex : Integer; Temp, Max : Extended; const MAXRUNNO : Integer = 8; MAXELEMENTVALUE : Integer = MAXINT; MINSIZE : Integer = 100; MAXSIZE : Integer = 10000; begin GetMem(ExtArray, MINSIZE * SizeOf(TExtended)); for RunNo := 1 to MAXRUNNO do begin Size := Random(MAXSIZE-MINSIZE) + MINSIZE; //SetLength(ExtArray, Size); ReallocMem(ExtArray, Size * SizeOf(TExtended)); //Fill array with random values for I1 := 0 to Size-1 do begin ExtArray[I1].X := Random(MAXELEMENTVALUE); end; //Sort array just to create an acces pattern //Using some weird DKC sort algorithm LowIndex := 0; HighIndex := Size-1; repeat if ExtArray[LowIndex].X > ExtArray[HighIndex].X then begin //Swap Temp := ExtArray[LowIndex].X; ExtArray[LowIndex].X := ExtArray[HighIndex].X; ExtArray[HighIndex].X := Temp; end; Inc(LowIndex); Dec(HighIndex); until(LowIndex >= HighIndex); for I2 := Size-1 downto 1 do begin //Find biggest element in unsorted part of array Max := ExtArray[I2].X; IndexMax := I2; for I3 := I2-1 downto 0 do begin if ExtArray[I3].X > Max then begin Max := ExtArray[I3].X; IndexMax := I3; end; end; //Swap current element with biggest remaining element Temp := ExtArray[I2].X; ExtArray[I2].X := ExtArray[IndexMax].X; ExtArray[IndexMax].X := Temp; end; end; //Free array FreeMem(ExtArray); FBenchmark.UpdateUsageStatistics; end; class function TSortExtendedArrayThreads.GetBenchmarkDescription: string; begin Result := 'A benchmark that measures read and write speed to an array of Extendeds. ' + 'The Extended type is padded to be 16 byte. ' + 'Bonus is given for 16 byte alignment of array ' + 'Will also reveil cache set associativity related issues. ' + 'Access pattern is created by X sorting array of random values. ' + 'Measures memory usage after all blocks have been freed. ' + 'Benchmark submitted by Dennis Kjaer Christensen.'; end; class function TSortExtendedArrayThreads.GetBenchmarkName: string; begin Result := 'SortExtendedArrayBenchmark'; end; class function TSortExtendedArrayThreads.GetCategory: TBenchmarkCategory; begin Result := bmMemoryAccessSpeed; end; class function TSortExtendedArrayThreads.GetSpeedWeight: Double; begin Result := 0.75; end; procedure TSortExtendedArrayThreads.RunBenchmark; var SortExtendedArrayThread1, SortExtendedArrayThread2 : TSortExtendedArrayThread; SortExtendedArrayThread3, SortExtendedArrayThread4 : TSortExtendedArrayThread; begin inherited; SortExtendedArrayThread1 := TSortExtendedArrayThread.Create(True); SortExtendedArrayThread2 := TSortExtendedArrayThread.Create(True); SortExtendedArrayThread3 := TSortExtendedArrayThread.Create(True); SortExtendedArrayThread4 := TSortExtendedArrayThread.Create(True); SortExtendedArrayThread1.FreeOnTerminate := False; SortExtendedArrayThread2.FreeOnTerminate := False; SortExtendedArrayThread3.FreeOnTerminate := False; SortExtendedArrayThread4.FreeOnTerminate := False; SortExtendedArrayThread1.Priority := tpLower; SortExtendedArrayThread2.Priority := tpNormal; SortExtendedArrayThread3.Priority := tpHigher; SortExtendedArrayThread4.Priority := tpHighest; SortExtendedArrayThread1.FBenchmark := Self; SortExtendedArrayThread2.FBenchmark := Self; SortExtendedArrayThread3.FBenchmark := Self; SortExtendedArrayThread4.FBenchmark := Self; SortExtendedArrayThread1.Resume; SortExtendedArrayThread2.Resume; SortExtendedArrayThread3.Resume; SortExtendedArrayThread4.Resume; SortExtendedArrayThread1.WaitFor; SortExtendedArrayThread2.WaitFor; SortExtendedArrayThread3.WaitFor; SortExtendedArrayThread4.WaitFor; SortExtendedArrayThread1.Free; SortExtendedArrayThread2.Free; SortExtendedArrayThread3.Free; SortExtendedArrayThread4.Free; end; end.
{----------------------------------------------------------------------------- Unit Name: ShellUtilities This software and source code are distributed on an as is basis, without warranty of any kind, either express or implied. This file can be redistributed, modified if you keep this header. Copyright © Erwien Saputra 2005 All Rights Reserved. Author: Erwien Saputra Purpose: History: 02/18/2005 - Fixed the problem with RunDelphi. It incorrectly added double quotes around the parameter. It is not necessary and caused a bug when the custom setting has space in it. -----------------------------------------------------------------------------} unit ShellUtilities; interface uses ShlObj, ActiveX, ComObj, SysUtils, Windows, ShellAPI, Forms; //Create a shortcut at the desired location. This procedure is adapted from //Creating shortcuts with Delphi at delphi.about.com. //ShortcutName = the path and the file name of the shortcut //Target = The executable name. //Parameter = parameter for the executable. //Description (Optional) = set the description of the link. procedure CreateLink (const ShortcutName, Target, Parameter : string; const Description : string = ''); forward; procedure RunDelphi (const DelphiExecutable, Parameter : string); forward; procedure GotoLink (const Link: string); forward; implementation procedure CreateLink (const ShortcutName, Target, Parameter : string; const Description : string = ''); var IObject : IUnknown; ISLink : IShellLink; IPFile : IPersistFile; begin IObject := CreateComObject (CLSID_ShellLink); ISLink := IObject as IShellLink; IPFile := IObject as IPersistFile; if FileExists (Target) = false then raise Exception.Create ('Target does not exist.'); ISLink.SetPath (PChar (Target)); ISLink.SetWorkingDirectory (PChar (ExtractFilePath (Target))); if SameText (Trim (Parameter), EmptyStr) = false then ISLink.SetArguments (PChar (Parameter)); if SameText (Trim (Description), EmptyStr) = false then ISLink.SetDescription (PCHar (Description)); IPFile.Save (PWideChar (WideString (ShortcutName)), false); end; procedure RunDelphi (const DelphiExecutable, Parameter : string); var StartupInfo : TStartupInfo; ProcessInformation : TProcessInformation; begin FillChar (StartupInfo, SizeOf (TStartupInfo), #0); FillChar (ProcessInformation, SizeOf (TProcessInformation), #0); StartupInfo.cb := SizeOf (TStartupInfo); if not CreateProcess (nil, PChar ('"' + DelphiExecutable + '" ' + Parameter), nil, nil, false, CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInformation) then raise Exception.Create ('Cannot run Delphi.'); end; procedure GotoLink (const Link: string); begin if SameText (Link, EmptyStr) = false then ShellExecute (0, 'Open', PChar (Link), nil, nil, SW_SHOWNORMAL); end; end.
unit oCoverSheetParam_CPRS_Vitals; { ================================================================================ * * Application: CPRS - CoverSheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-04 * * Description: Inherited from base. This parameter is used to override * the NewCoverSheetControl method. * * Notes: * ================================================================================ } interface uses System.Classes, Vcl.Controls, oCoverSheetParam_CPRS, iCoverSheetIntf; type TCoverSheetParam_CPRS_Vitals = class(TCoverSheetParam_CPRS, ICoverSheetParam) protected function NewCoverSheetControl(aOwner: TComponent): TControl; override; public end; implementation uses mCoverSheetDisplayPanel_CPRS_Vitals; { TCoverSheetParam_CPRS_Vitals } function TCoverSheetParam_CPRS_Vitals.NewCoverSheetControl(aOwner: TComponent): TControl; begin Result := TfraCoverSheetDisplayPanel_CPRS_Vitals.Create(aOwner); end; end.
unit fOrdersComplete; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ORFn, ORCtrls, VA508AccessibilityManager; type TfrmCompleteOrders = class(TfrmAutoSz) Label1: TLabel; lstOrders: TCaptionListBox; cmdOK: TButton; cmdCancel: TButton; lblESCode: TLabel; txtESCode: TCaptionEdit; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); private OKPressed: Boolean; ESCode: string; end; function ExecuteCompleteOrders(SelectedList: TList): Boolean; implementation {$R *.DFM} uses XWBHash, rCore, rOrders, VAUtils; function ExecuteCompleteOrders(SelectedList: TList): Boolean; var frmCompleteOrders: TfrmCompleteOrders; i: Integer; begin Result := False; if SelectedList.Count = 0 then Exit; frmCompleteOrders := TfrmCompleteOrders.Create(Application); try ResizeFormToFont(TForm(frmCompleteOrders)); with SelectedList do for i := 0 to Count - 1 do frmCompleteOrders.lstOrders.Items.Add(TOrder(Items[i]).Text); frmCompleteOrders.ShowModal; if frmCompleteOrders.OKPressed then begin with SelectedList do for i := 0 to Count - 1 do CompleteOrder(TOrder(Items[i]), frmCompleteOrders.ESCode); Result := True; end; finally frmCompleteOrders.Release; with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); end; end; procedure TfrmCompleteOrders.FormCreate(Sender: TObject); begin inherited; OKPressed := False; end; procedure TfrmCompleteOrders.cmdOKClick(Sender: TObject); const TX_NO_CODE = 'An electronic signature code must be entered to complete orders.'; TC_NO_CODE = 'Electronic Signature Code Required'; TX_BAD_CODE = 'The electronic signature code entered is not valid.'; TC_BAD_CODE = 'Invalid Electronic Signature Code'; begin inherited; if Length(txtESCode.Text) = 0 then begin InfoBox(TX_NO_CODE, TC_NO_CODE, MB_OK); Exit; end; if not ValidESCode(txtESCode.Text) then begin InfoBox(TX_BAD_CODE, TC_BAD_CODE, MB_OK); txtESCode.SetFocus; txtESCode.SelectAll; Exit; end; ESCode := Encrypt(txtESCode.Text); OKPressed := True; Close; end; procedure TfrmCompleteOrders.cmdCancelClick(Sender: TObject); begin inherited; Close; end; end.
unit HKPaginantion; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, HKPaginationModel; type { THKPaginantion } THKPaginantion = class(TPanel) private FFirstBtn:TButton; FLastBtn:TButton; FNextBtn:TButton; FPrevBtn:TButton; FLabel:TLabel; FPaginationModel: THKPaginationModel; procedure FirstBtnClick(Sender: TObject); procedure LastBtnClick(Sender: TObject); procedure NextBtnClick(Sender: TObject); procedure PageChanged(Sender: TObject); procedure PerPageChanged(Sender: TObject); procedure PrevBtnClick(Sender: TObject); procedure SetPaginationModel(AValue: THKPaginationModel); procedure TotalRecordChanged(Sender: TObject); Function CreateBtn(aCaption:String):TButton; //Procedure CreateLabel(): protected procedure EnDisBtn; procedure UpdateInfo; procedure UpdatePagination; procedure DoOnResize; override; public constructor Create(TheOwner: TComponent); override; procedure CreatePaginationControl; destructor Destroy; override; published property PaginationModel:THKPaginationModel read FPaginationModel write SetPaginationModel; end; { THKPaginationComp } THKPaginationComp=class(TPanel) private FCurrentPage: Integer; FFirstBtn:TButton; FLastBtn:TButton; FNextBtn:TButton; FOnFirstBtnClick: TNotifyEvent; FOnLastBtnClick: TNotifyEvent; FOnNextBtnClick: TNotifyEvent; FOnPrevBtnClick: TNotifyEvent; FPerPage: Integer; FPrevBtn:TButton; FLabel:TLabel; FTotalPage: Integer; FTotalRecords: Integer; procedure FirstBtnClick(Sender: TObject); procedure LastBtnClick(Sender: TObject); procedure NextBtnClick(Sender: TObject); procedure PrevBtnClick(Sender: TObject); Function CreateBtn(aCaption:String):TButton; procedure SetCurrentPage(AValue: Integer); procedure SetOnFirstBtnClick(AValue: TNotifyEvent); procedure SetOnLastBtnClick(AValue: TNotifyEvent); procedure SetOnNextBtnClick(AValue: TNotifyEvent); procedure SetOnPrevBtnClick(AValue: TNotifyEvent); procedure SetPerPage(AValue: Integer); procedure SetTotalRecords(AValue: Integer); protected procedure DoFirstBtnClick;virtual; procedure DoLastBtnClick;virtual; procedure DoPrevstBtnClick;virtual; procedure DoNextBtnClick;virtual; procedure UpdateInfo;virtual; procedure EnDisBtn;virtual; procedure DoOnResize; override; public constructor Create(TheOwner: TComponent); override; procedure CreatePaginationControl; destructor Destroy; override; published property OnFirstBtnClick:TNotifyEvent read FOnFirstBtnClick write SetOnFirstBtnClick; property OnLastBtnClick:TNotifyEvent read FOnLastBtnClick write SetOnLastBtnClick; property OnPrevBtnClick:TNotifyEvent read FOnPrevBtnClick write SetOnPrevBtnClick; property OnNextBtnClick:TNotifyEvent read FOnNextBtnClick write SetOnNextBtnClick; property CurrentPage:Integer read FCurrentPage write SetCurrentPage; property TotalRecords:Integer read FTotalRecords write SetTotalRecords; property PerPage:Integer read FPerPage write SetPerPage; property TotalPage:Integer read FTotalPage; end; procedure Register; implementation uses Math; procedure Register; begin {$I hkpaginantion_icon.lrs} RegisterComponents('HKCompPacks',[THKPaginantion]); {$I hkpaginantioncomp_icon.lrs} RegisterComponents('HKCompPacks',[THKPaginationComp]); end; { THKPaginationComp } procedure THKPaginationComp.FirstBtnClick(Sender: TObject); begin CurrentPage:=1; DoFirstBtnClick; end; procedure THKPaginationComp.LastBtnClick(Sender: TObject); begin FTotalPage:=Math.Ceil(TotalRecords/PerPage); CurrentPage:=FTotalPage; DoLastBtnClick; end; procedure THKPaginationComp.NextBtnClick(Sender: TObject); begin CurrentPage:=CurrentPage+1; DoNextBtnClick; end; procedure THKPaginationComp.PrevBtnClick(Sender: TObject); begin //Dec(CurrentPage); CurrentPage:=CurrentPage-1; DoPrevstBtnClick; end; function THKPaginationComp.CreateBtn(aCaption: String): TButton; begin Result:=TButton.Create(Self); Result.Parent:=Self; Result.Anchors:=[akRight, akTop, akBottom]; Result.Width:=40; Result.Height:=40; Result.Caption:=aCaption; end; procedure THKPaginationComp.SetCurrentPage(AValue: Integer); begin if FCurrentPage=AValue then Exit; FCurrentPage:=AValue; UpdateInfo; end; procedure THKPaginationComp.SetOnFirstBtnClick(AValue: TNotifyEvent); begin if FOnFirstBtnClick=AValue then Exit; FOnFirstBtnClick:=AValue; end; procedure THKPaginationComp.SetOnLastBtnClick(AValue: TNotifyEvent); begin if FOnLastBtnClick=AValue then Exit; FOnLastBtnClick:=AValue; end; procedure THKPaginationComp.SetOnNextBtnClick(AValue: TNotifyEvent); begin if FOnNextBtnClick=AValue then Exit; FOnNextBtnClick:=AValue; end; procedure THKPaginationComp.SetOnPrevBtnClick(AValue: TNotifyEvent); begin if FOnPrevBtnClick=AValue then Exit; FOnPrevBtnClick:=AValue; end; procedure THKPaginationComp.SetPerPage(AValue: Integer); begin if FPerPage=AValue then Exit; FPerPage:=AValue; UpdateInfo; end; procedure THKPaginationComp.SetTotalRecords(AValue: Integer); begin if FTotalRecords=AValue then Exit; FTotalRecords:=AValue; UpdateInfo; end; procedure THKPaginationComp.DoFirstBtnClick; begin if Assigned(OnFirstBtnClick)then OnFirstBtnClick(Self); end; procedure THKPaginationComp.DoLastBtnClick; begin if Assigned(OnLastBtnClick)then OnLastBtnClick(Self); end; procedure THKPaginationComp.DoPrevstBtnClick; begin if Assigned(OnPrevBtnClick)Then OnPrevBtnClick(Self); end; procedure THKPaginationComp.DoNextBtnClick; begin if Assigned(OnNextBtnClick)then OnNextBtnClick(Self); end; procedure THKPaginationComp.UpdateInfo; var recNo, lastRecNo: Integer; begin recNo:=((CurrentPage-1) * PerPage)+1; if TotalRecords>(CurrentPage*PerPage) then lastRecNo:=CurrentPage*PerPage else lastRecNo:=TotalRecords; FTotalPage:=Math.Ceil(TotalRecords/PerPage); FLabel.Caption:=format('%d-%d Of %s Records Page %d Of %d', [recNo, lastRecNo, FormatFloat('#,##0', TotalRecords), CurrentPage, TotalPage]); EnDisBtn; end; procedure THKPaginationComp.EnDisBtn; begin FPrevBtn.Enabled:=CurrentPage>1; FFirstBtn.Enabled:=CurrentPage>1; FNextBtn.Enabled:=CurrentPage<TotalPage; FLastBtn.Enabled:=CurrentPage<TotalPage; end; procedure THKPaginationComp.DoOnResize; begin inherited DoOnResize; FLastBtn.Left:=Width-60; FNextBtn.Left:=Width-105; FPrevBtn.Left:=Width-150; FFirstBtn.Left:=Width-195; end; constructor THKPaginationComp.Create(TheOwner: TComponent); begin inherited Create(TheOwner); Caption:=''; Width:=500; Height:=50; BevelOuter:=bvNone; BevelInner:=bvNone; CreatePaginationControl; PerPage:=25; end; procedure THKPaginationComp.CreatePaginationControl; begin FLastBtn:=CreateBtn('Last'); FLastBtn.Left:=440; FLastBtn.Top:=5; FLastBtn.OnClick:=@LastBtnClick; FNextBtn:=CreateBtn('Next'); FNextBtn.Left:=395; FNextBtn.Top:=5; FNextBtn.OnClick:=@NextBtnClick; FPrevBtn:=CreateBtn('Prev'); FPrevBtn.Left:=350; FPrevBtn.Top:=5; FPrevBtn.OnClick:=@PrevBtnClick; FFirstBtn:=CreateBtn('First'); FFirstBtn.Left:=305; FFirstBtn.Top:=5; FFirstBtn.OnClick:=@FirstBtnClick; FLabel:=TLabel.Create(Self); FLabel.Caption:='0-0 of 0 Records'; FLabel.Parent:=Self; FLabel.Anchors:=[akLeft, akTop, akBottom]; FLabel.Width:=100; FLabel.Height:=20; FLabel.Left:=20; FLabel.Top:=15; end; destructor THKPaginationComp.Destroy; begin FLabel.Free; FFirstBtn.Free; FLastBtn.Free; FNextBtn.Free; FPrevBtn.Free; inherited Destroy; end; { THKPaginantion } procedure THKPaginantion.SetPaginationModel(AValue: THKPaginationModel); begin if FPaginationModel=AValue then Exit; FPaginationModel:=AValue; FPaginationModel.OnPageChanged:=@PageChanged; FPaginationModel.OnPerPageChanged:=@PerPageChanged; FPaginationModel.OnTotalRecordsChanged:=@TotalRecordChanged; end; procedure THKPaginantion.PerPageChanged(Sender: TObject); begin UpdatePagination; end; procedure THKPaginantion.TotalRecordChanged(Sender: TObject); begin if Assigned(PaginationModel) then UpdatePagination; end; procedure THKPaginantion.PageChanged(Sender: TObject); begin if Assigned(PaginationModel) then UpdatePagination; end; procedure THKPaginantion.PrevBtnClick(Sender: TObject); begin if Assigned(PaginationModel) then FPaginationModel.PrevPage; end; procedure THKPaginantion.LastBtnClick(Sender: TObject); begin if Assigned(PaginationModel) then FPaginationModel.LastPage; end; procedure THKPaginantion.FirstBtnClick(Sender: TObject); begin if Assigned(PaginationModel) then FPaginationModel.FirstPage; end; procedure THKPaginantion.NextBtnClick(Sender: TObject); begin if Assigned(PaginationModel) then FPaginationModel.NextPage; end; function THKPaginantion.CreateBtn(aCaption: String): TButton; begin Result:=TButton.Create(Self); Result.Parent:=Self; Result.Anchors:=[akRight, akTop, akBottom]; Result.Width:=40; Result.Height:=40; Result.Caption:=aCaption; end; procedure THKPaginantion.EnDisBtn; begin if Assigned(PaginationModel) then begin FPrevBtn.Enabled:=FPaginationModel.CurrentPage>1; FFirstBtn.Enabled:=FPaginationModel.CurrentPage>1; FNextBtn.Enabled:=FPaginationModel.CurrentPage<FPaginationModel.TotalPage; FLastBtn.Enabled:=FPaginationModel.CurrentPage<FPaginationModel.TotalPage; end; end; procedure THKPaginantion.UpdateInfo; var recNo, lastRecNo: Integer; begin if Assigned(PaginationModel) then begin recNo:=((FPaginationModel.CurrentPage-1) * FPaginationModel.RowPerPage)+1; if FPaginationModel.TotalRecords>(FPaginationModel.CurrentPage*FPaginationModel.RowPerPage) then lastRecNo:=FPaginationModel.CurrentPage*FPaginationModel.RowPerPage else lastRecNo:=FPaginationModel.TotalRecords; FLabel.Caption:=format('%d-%d Of %s Records Page %d Of %d', [recNo, lastRecNo, FormatFloat('#,##0', FPaginationModel.TotalRecords), FPaginationModel.CurrentPage, FPaginationModel.TotalPage]); end; end; procedure THKPaginantion.UpdatePagination; begin EnDisBtn; UpdateInfo; end; procedure THKPaginantion.DoOnResize; begin inherited DoOnResize; FLastBtn.Left:=Width-60; FNextBtn.Left:=Width-105; FPrevBtn.Left:=Width-150; FFirstBtn.Left:=Width-195; end; constructor THKPaginantion.Create(TheOwner: TComponent); begin inherited Create(TheOwner); Caption:=''; Width:=500; Height:=50; BevelOuter:=bvNone; BevelInner:=bvNone; CreatePaginationControl; end; procedure THKPaginantion.CreatePaginationControl; //var //btn: TButton; begin FLastBtn:=CreateBtn('Last'); FLastBtn.Left:=440; FLastBtn.Top:=5; FLastBtn.OnClick:=@LastBtnClick; FNextBtn:=CreateBtn('Next'); FNextBtn.Left:=395; FNextBtn.Top:=5; FNextBtn.OnClick:=@NextBtnClick; FPrevBtn:=CreateBtn('Prev'); FPrevBtn.Left:=350; FPrevBtn.Top:=5; FPrevBtn.OnClick:=@PrevBtnClick; FFirstBtn:=CreateBtn('First'); FFirstBtn.Left:=305; FFirstBtn.Top:=5; FFirstBtn.OnClick:=@FirstBtnClick; FLabel:=TLabel.Create(Self); FLabel.Caption:='0-0 of 0 Records'; FLabel.Parent:=Self; FLabel.Anchors:=[akLeft, akTop, akBottom]; FLabel.Width:=100; FLabel.Height:=20; FLabel.Left:=20; FLabel.Top:=15; end; destructor THKPaginantion.Destroy; begin FLabel.Free; FFirstBtn.Free; FLastBtn.Free; FNextBtn.Free; FPrevBtn.Free; inherited Destroy; end; end.
unit PaymentCash; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh, DB, ComCtrls, ToolWin; type TPaymentCashForm = class(TForm) DBGridEh1: TDBGridEh; Panel1: TPanel; CloseButton: TButton; ToolBar1: TToolBar; ToolButton1: TToolButton; InsertButton: TToolButton; EditButton: TToolButton; DeleteButton: TToolButton; ToolButton2: TToolButton; Edit1: TEdit; ToolButton3: TToolButton; RefreshButton: TToolButton; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CloseButtonClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure EditButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure RefreshButtonClick(Sender: TObject); procedure DBGridEh1DblClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } end; var PaymentCashForm: TPaymentCashForm; implementation uses StoreDM, PaymentCashItem; {$R *.dfm} procedure TPaymentCashForm.FormCreate(Sender: TObject); begin CloseButton.Left := Panel1.Width - CloseButton.Width - 10; with StoreDataModule do begin PaymentCashTransaction.Active := True; PaymentCashDataSet.ParamByName('MainFirm').Value := MainFirm; PaymentCashDataSet.Open; PayOrderCashDataSet.Open; end; Caption := 'Оплата через Кассу (' + TopDate + '-' + BottomDate + ')'; end; procedure TPaymentCashForm.FormClose(Sender: TObject; var Action: TCloseAction); begin CurPaymentID := 0; if StoreDataModule.PaymentCashTransaction.InTransaction then StoreDataModule.PaymentCashTransaction.Commit; StoreDataModule.PaymentCashDataSet.Close; StoreDataModule.PaymentCashDataSet.SelectSQL.Strings[4] := ''; StoreDataModule.PayOrderCashDataSet.Close; // Удаление формы при ее закрытии PaymentCashForm := nil; Action := caFree; end; procedure TPaymentCashForm.CloseButtonClick(Sender: TObject); begin Close; end; procedure TPaymentCashForm.Edit1Change(Sender: TObject); var Find : String; begin Find := AnsiUpperCase(Edit1.Text); with StoreDataModule.PaymentCashDataSet do begin Close; SelectSQL.Strings[4] := 'AND (UPPER("CustomerName") CONTAINING ''' + Find + ''')'; Open; end; end; procedure TPaymentCashForm.InsertButtonClick(Sender: TObject); begin StoreDataModule.PaymentCashDataSet.Append; StoreDataModule.PaymentCashDataSet['Cash'] := 1; StoreDataModule.PaymentCashDataSet['Date'] := Now; StoreDataModule.PaymentCashDataSet['FirmID'] := MainFirm; PaymentCashItemForm := TPaymentCashItemForm.Create(Self); PaymentCashItemForm.ShowModal; end; procedure TPaymentCashForm.EditButtonClick(Sender: TObject); begin StoreDataModule.PaymentCashDataSet.Edit; PaymentCashItemForm := TPaymentCashItemForm.Create(Self); PaymentCashItemForm.ShowModal; end; procedure TPaymentCashForm.DeleteButtonClick(Sender: TObject); var PayStr: String; begin PayStr := StoreDataModule.PaymentCashDataSet['CustomerName']; if Application.MessageBox(PChar('Вы действительно хотите удалить запись оплаты "' + PayStr + '"?'), 'Удаление записи', mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then try StoreDataModule.PaymentCashDataSet.Delete; StoreDataModule.PaymentCashTransaction.CommitRetaining; except Application.MessageBox(PChar('Запись "' + PayStr + '" удалять нельзя.'), 'Ошибка удаления', mb_IconStop); end; end; procedure TPaymentCashForm.RefreshButtonClick(Sender: TObject); begin StoreDataModule.PaymentCashDataSet.Close; StoreDataModule.PaymentCashDataSet.Open; Caption := 'Оплата через Кассу (' + TopDate + '-' + BottomDate + ')'; end; procedure TPaymentCashForm.DBGridEh1DblClick(Sender: TObject); begin EditButton.Click; end; procedure TPaymentCashForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_F2 : InsertButton.Click; VK_F3 : EditButton.Click; VK_F8 : DeleteButton.Click; VK_F4 : Edit1.SetFocus; end; end; end.
unit GrafLib1; interface uses GrafLib0; CONST VectorArraySize = 32; epsilon = 0.0000001; { pi = 3.1415926535 already defined in Turbo} TYPE Vector2 = RECORD x,y : INTEGER END; Vector2Array = ARRAY[1..VectorArraySize] OF Vector2; RealArray = ARRAY[1..VectorArraySize] OF REAL; IntegerArray = ARRAY[1..VectorArraySize] OF Integer; VAR horiz, vert, XYScale : REAL; FUNCTION fx(x : REAL) : INTEGER; { scale units to pixels } FUNCTION fy(y : REAL) : INTEGER; { scale units to pixels } PROCEDURE MoveTo(pt : Vector2); {change the current position pointer} PROCEDURE LineTo(pt : Vector2); {draw a line for the current point to pixel. Update the current pointer } PROCEDURE PolyFill(n : INTEGER; polygon : Vector2Array); {fill a polygon defined by poly having n vertices } PROCEDURE Start(horiz : REAL); { Set up the graphics display } (* =========================================================== *) implementation CONST MaxColorLevel = 63 {with VGA}; VAR MaxCol : INTEGER; FUNCTION fx(x : REAL) : INTEGER; { scale units to pixels } BEGIN fx := TRUNC(x*XYScale+nxpix*0.5-0.5); END {fx}; (*----------------------------------------------------------- *) FUNCTION fy(y : REAL) : INTEGER; { scale units to pixels } BEGIN fy := TRUNC(y*XYScale+nypix*0.5-0.5); END {fy}; (*----------------------------------------------------------- *) PROCEDURE MoveTo(pt : Vector2); {change the current position pointer} VAR pixel : pixelvector; BEGIN pixel.x := fx(pt.x); pixel.y := fy(pt.y); MovePix(pixel); END {MoveTo}; (*----------------------------------------------------------- *) PROCEDURE LineTo(pt : Vector2); {draw a line for the current point to pixel. Update the current pointer } VAR pixel : pixelvector; BEGIN pixel.x := fx(pt.x); pixel.y := fy(pt.y); LinePix(pixel); END {LineTo}; (*----------------------------------------------------------- *) PROCEDURE PolyFill(n : INTEGER; polygon : Vector2Array); {fill a polygon defined by poly having n vertices } VAR i : INTEGER; pixelpolygon : pixelarray; BEGIN { tranlate coordinate scheme } FOR i := 1 TO n DO BEGIN pixelpolygon[i].x := fx(polygon[i].x); pixelpolygon[i].y := fy(polygon[i].y); END; PolyPix(n,pixelpolygon); END {PolyFill}; (*----------------------------------------------------------- *) PROCEDURE Start; { Set up the graphics display } VAR i, GraphDriver, GraphMode : INTEGER; BEGIN PrepIt; IF horiz < 1 THEN horiz := nxpix; {default} vert := horiz*nypix/nxpix; XYScale := (nxpix-1)/horiz; END {Start}; (*----------------------------------------------------------- *) BEGIN horiz := 0; END {GraphLib0}.
unit SocketAppImpl; interface {$MODE OBJFPC} uses {$IFDEF UNIX} cthreads, {$ENDIF} classes, sysutils, sockets, fpAsync, fpSock, ThreadIntf, ThreadPoolIntf; type TSocketWebApplication = class(TInterfacedObject, IWebApplication, IRunnable) private evLoop: TEventLoop; server : TTCPServer; threadPool : IThreadPool; procedure handleConnect(Sender: TConnectionBasedSocket; AStream: TSocketStream); public constructor create(const pool : IThreadPool; const port : integer); destructor destroy(); override; function run() : IRunnable; end; implementation type TSocketThread = class(TThread) private clientStream: TSocketStream; public constructor create(AClientStream: TSocketStream); procedure execute(); override; end; TSocketThreadPoolItem = class(TInterfacedObject, IThread) private actualThread : TSocketThread; public constructor create(); destructor destroy(); override; (*!------------------------------------------------ * get current thread status *------------------------------------------------- * @return true is thread is idle, false if thread is * busy working *-------------------------------------------------*) function idle() : boolean; (*!------------------------------------------------ * tell thread to start running *------------------------------------------------ * If thread already running, multiple call does nothing *-------------------------------------------------*) procedure start(); end; (*!---------------------------------------- * constructor *----------------------------------------- * @param AClientStream socket stream to use *-----------------------------------------*) constructor TSocketThread.create(AClientStream: TSocketStream); begin //create a fire and forget thread instance inherited create(false); FreeOnTerminate := true; clientStream := AClientStream; end; (*!---------------------------------------- * called when thread is running *-----------------------------------------*) procedure TSocketThread.execute(); begin end; constructor TSocketWebApplication.create(const port : integer); begin evLoop := TEventLoop.create; server := TTCPServer.create(nil); server.EventLoop := evLoop; server.Port := port; end; destructor destroy(); begin inherited destroy; evLoop.free(); server.free(); end; procedure TSocketWebApplication.handleConnect(Sender: TConnectionBasedSocket; AStream: TSocketStream); begin writeLn('Handle incoming connection..'); TSocketThread.create(AStream); end; function TSocketWebApplication.run() : IRunnable; begin server.active := true; server.eventLoop.run(); end. end.
PROGRAM TreeCount; TYPE TreeNodePtr = ^TreeNode; TreeNode = RECORD left, right: TreeNodePtr; data: INTEGER; END; TreePtr = TreeNodePtr; PROCEDURE InitTree(VAR t: TreePtr); BEGIN t := NIL; END; PROCEDURE DisposeTree(t: TreePtr); BEGIN IF t = NIL THEN ELSE BEGIN DisposeTree(t^.left); DisposeTree(t^.right); Dispose(t); END; END; PROCEDURE AddValue(VAR t: TreePtr; value: INTEGER); VAR n: TreePtr; BEGIN IF t = NIL THEN BEGIN New(n); n^.data := value; n^.left := NIL; n^.right := NIL; t := n; END ELSE IF value < n^.data THEN AddValue(t^.left, value) ELSE AddValue(t^.right, value); END; PROCEDURE DisplayTree(t: TreePtr); BEGIN IF t = NIL THEN ElSE BEGIN (* in-order*) DisplayTree(t^.left); Write(t^.data, ' '); DisplayTree(t^.right); END; END; FUNCTION CountNodesLessThan(t: TreePtr; x: INTEGER): INTEGER; BEGIN IF t = NIL THEN CountNodesLessThan := 0 ELSE IF x <= t^.data THEN CountNodesLessThan := CountNodesLessThan(t^.left, x) ELSE CountNodesLessThan := CountNodesLessThan(t^.left, x) + CountNodesLessThan(t^.right, x) + 1 END; VAR t: TreePtr; BEGIN InitTree(t); DisplayTree(t); WriteLn; AddValue(t, 10); AddValue(t, 150); AddValue(t, 20); AddValue(t, 5); AddValue(t, 18); AddValue(t, 24); AddValue(t, 3); AddValue(t, 79); DisplayTree(t); WriteLn; WriteLn; WriteLn('Nodes less than value 151: ',CountNodesLessThan(t, 151)); DisposeTree(t); END.
unit Unit2; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TConfigA = class(TObject) strict private FValue:String; function GetValue:String; procedure SetValue(pValue:String); public constructor Create; destructor Destroy;override; property Value:String read GetValue write SetValue; end; TConfigB = class(TObject) strict private FValue:String; function GetValue:String; procedure SetValue(pValue:String); public constructor Create; destructor Destroy;override; property Value:String read GetValue write SetValue; end; TConfigLoadResult = class(TObject) strict private FSuccess:Boolean; FErrorList:TStringList; function GetSuccess:Boolean; procedure SetSuccess(pSuccess:Boolean); function GetErrorList:TStringList; procedure SetErrorList(pErrorList:TStringList); public constructor Create; destructor Destroy;override; property Success:Boolean read GetSuccess write SetSuccess; property ErrorList:TStringList read GetErrorList write SetErrorList; end; TConfig = class(TObject) strict private FA:TConfigA; FB:TConfigB; function GetA:TConfigA; function GetB:TConfigB; procedure LoadFromFileA(pLoadResult:TConfigLoadResult); procedure LoadFromFileB(pLoadResult:TConfigLoadResult); public constructor Create; destructor Destroy;override; property A:TConfigA read GetA; property B:TConfigB read GetB; function LoadFromFile:TConfigLoadResult; end; implementation constructor TConfigA.Create; begin inherited Create; //継承部分を初期化する。 //ここより下に初期化コードを書く。 end; destructor TConfigA.Destroy; begin //ここより上に破棄コードを書く。 inherited Destroy; //継承部分を破棄する。 end; function TConfigA.GetValue:String; begin Result := FValue; end; procedure TConfigA.SetValue(pValue:String); begin FValue := pValue; end; constructor TConfigB.Create; begin inherited Create; //継承部分を初期化する。 //ここより下に初期化コードを書く。 end; destructor TConfigB.Destroy; begin //ここより上に破棄コードを書く。 inherited Destroy; //継承部分を破棄する。 end; function TConfigB.GetValue:String; begin Result := FValue; end; procedure TConfigB.SetValue(pValue:String); begin FValue := pValue; end; constructor TConfigLoadResult.Create; begin inherited Create; //継承部分を初期化する。 //ここより下に初期化コードを書く。 FSuccess := False; FErrorList := TStringList.Create; end; destructor TConfigLoadResult.Destroy; begin if Assigned(FErrorList) then begin FErrorList.Free; end; //ここより上に破棄コードを書く。 inherited Destroy; //継承部分を破棄する。 end; function TConfigLoadResult.GetSuccess:Boolean; begin Result := FSuccess; end; procedure TConfigLoadResult.SetSuccess(pSuccess:Boolean); begin FSuccess := pSuccess; end; function TConfigLoadResult.GetErrorList:TStringList; begin Result := FErrorList; end; procedure TConfigLoadResult.SetErrorList(pErrorList:TStringList); begin FErrorList.Clear; FErrorList.AddStrings(pErrorList); end; //コンストラクタ //http://docwiki.embarcadero.com/RADStudio/XE7/ja/%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89#.E3.82.B3.E3.83.B3.E3.82.B9.E3.83.88.E3.83.A9.E3.82.AF.E3.82.BF constructor TConfig.Create; begin inherited Create; //継承部分を初期化する。 //ここより下に初期化コードを書く。 FA := TConfigA.Create; FB := TConfigB.Create; end; //デストラクタ //http://docwiki.embarcadero.com/RADStudio/XE7/ja/%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89#.E3.83.87.E3.82.B9.E3.83.88.E3.83.A9.E3.82.AF.E3.82.BF destructor TConfig.Destroy; begin if Assigned(FA) then begin FA.Free; end; if Assigned(FB) then begin FB.Free; end; //ここより上に破棄コードを書く。 inherited Destroy; //継承部分を破棄する。 end; function TConfig.GetA:TConfigA; begin Result := FA; end; function TConfig.GetB:TConfigB; begin Result := FB; end; procedure TConfig.LoadFromFileA(pLoadResult:TConfigLoadResult); var slConfigFile:TStringList; begin slConfigFile := nil; try slConfigFile := TStringList.Create; slConfigFile.LoadFromFile(''); finally if Assigned(slConfigFile) then begin slConfigFile.Free; end; end; end; procedure TConfig.LoadFromFileB(pLoadResult:TConfigLoadResult); var slConfigFile:TStringList; begin slConfigFile := nil; try slConfigFile := TStringList.Create; slConfigFile.LoadFromFile(''); finally if Assigned(slConfigFile) then begin slConfigFile.Free; end; end; end; function TConfig.LoadFromFile:TConfigLoadResult; var LoadResult:TConfigLoadResult; begin LoadResult := TConfigLoadResult.Create; LoadFromFileA(LoadResult); LoadFromFileB(LoadResult); Result := LoadResult; end; end.
unit IdURI; {Details of implementation ------------------------- 2002-Apr-14 Peter Mee - Fixed reset. Now resets FParams as well - wasn't before. 2001-Nov Doychin Bondzhev - Fixes in URLEncode. There is difference when encoding Path+Doc and Params 2001-Oct-17 Peter Mee - Minor speed improvement - removed use of NormalizePath in SetURI. - Fixed bug that was cutting off the first two chars of the host when a username / password present. - Fixed bug that prevented username and password being updated. - Fixed bug that was leaving the bookmark in the document when no ? or = parameters existed. 2001-Feb-18 Doychin Bondzhev - Added UserName and Password to support URI's like http://username:password@hostname:port/path/document#bookmark } interface Uses IdException; type TIdURIOptionalFields = (ofAuthInfo, ofBookmark); TIdURIOptionalFieldsSet = set of TIdURIOptionalFields; TIdURI = class protected FDocument: string; FProtocol: string; FURI: String; FPort: string; Fpath: string; FHost: string; FBookmark: string; FUserName: string; FPassword: string; FParams: string; // procedure SetURI(const Value: String); function GetURI: String; public constructor Create(const AURI: string = ''); virtual; {Do not Localize} function GetFullURI(const AOptionalFileds: TIdURIOptionalFieldsSet = [ofAuthInfo, ofBookmark]): String; class procedure NormalizePath(var APath: string); class function URLDecode(ASrc: string): string; class function URLEncode(const ASrc: string): string; class function ParamsEncode(const ASrc: string): string; class function PathEncode(const ASrc: string): string; // property Bookmark : string read FBookmark write FBookMark; property Document: string read FDocument write FDocument; property Host: string read FHost write FHost; property Password: string read FPassword write FPassword; property Path: string read FPath write FPath; property Params: string read FParams write FParams; property Port: string read FPort write FPort; property Protocol: string read FProtocol write FProtocol; property URI: string read GetURI write SetURI; property Username: string read FUserName write FUserName; end; EIdURIException = class(EIdException); implementation uses IdGlobal, IdResourceStrings, SysUtils; constructor TIdURI.Create(const AURI: string = ''); {Do not Localize} begin inherited Create; if length(AURI) > 0 then begin URI := AURI; end; end; class procedure TIdURI.NormalizePath(var APath: string); var i: Integer; begin // Normalize the directory delimiters to follow the UNIX syntax i := 1; while i <= Length(APath) do begin if APath[i] in LeadBytes then begin inc(i, 2) end else if APath[i] = '\' then begin {Do not Localize} APath[i] := '/'; {Do not Localize} inc(i, 1); end else begin inc(i, 1); end; end; end; procedure TIdURI.SetURI(const Value: String); var LBuffer: string; LTokenPos, LPramsPos: Integer; LURI: string; begin FURI := Value; NormalizePath(FURI); LURI := FURI; FHost := ''; {Do not Localize} FProtocol := ''; {Do not Localize} FPath := ''; {Do not Localize} FDocument := ''; {Do not Localize} FPort := ''; {Do not Localize} FBookmark := ''; {Do not Localize} FUsername := ''; {Do not Localize} FPassword := ''; {Do not Localize} FParams := ''; {Do not localise} //Peter Mee LTokenPos := IndyPos('://', LURI); {Do not Localize} if LTokenPos > 0 then begin // absolute URI // What to do when data don't match configuration ?? {Do not Localize} // Get the protocol FProtocol := Copy(LURI, 1, LTokenPos - 1); Delete(LURI, 1, LTokenPos + 2); // Get the user name, password, host and the port number LBuffer := Fetch(LURI, '/', True); {Do not Localize} // Get username and password LTokenPos := IndyPos('@', LBuffer); {Do not Localize} FPassword := Copy(LBuffer, 1, LTokenPos - 1); if LTokenPos > 0 then Delete(LBuffer, 1, LTokenPos); FUserName := Fetch(FPassword, ':', True); {Do not Localize} // Ignore cases where there is only password (http://:password@host/pat/doc) if Length(FUserName) = 0 then begin FPassword := ''; {Do not Localize} end; // Get the host and the port number FHost := Fetch(LBuffer, ':', True); {Do not Localize} FPort := LBuffer; // Get the path LPramsPos := IndyPos('?', LURI); {Do not Localize} if LPramsPos > 0 then begin // The case when there is parameters after the document name '?' {Do not Localize} LTokenPos := RPos('/', LURI, LPramsPos); {Do not Localize} end else begin LPramsPos := IndyPos('=', LURI); {Do not Localize} if LPramsPos > 0 then begin // The case when there is parameters after the document name '=' {Do not Localize} LTokenPos := RPos('/', LURI, LPramsPos); {Do not Localize} end else begin LTokenPos := RPos('/', LURI, -1); {Do not Localize} end; end; FPath := '/' + Copy(LURI, 1, LTokenPos); {Do not Localize} // Get the document if LPramsPos > 0 then begin FDocument := Copy(LURI, 1, LPramsPos - 1); Delete(LURI, 1, LPramsPos - 1); FParams := LURI; end else FDocument := LURI; Delete(FDocument, 1, LTokenPos); FBookmark := FDocument; FDocument := Fetch(FBookmark, '#'); {Do not Localize} end else begin // received an absolute path, not an URI LPramsPos := IndyPos('?', LURI); {Do not Localize} if LPramsPos > 0 then begin // The case when there is parameters after the document name '?' {Do not Localize} LTokenPos := RPos('/', LURI, LPramsPos); {Do not Localize} end else begin LPramsPos := IndyPos('=', LURI); {Do not Localize} if LPramsPos > 0 then begin // The case when there is parameters after the document name '=' {Do not Localize} LTokenPos := RPos('/', LURI, LPramsPos); {Do not Localize} end else begin LTokenPos := RPos('/', LURI, -1); {Do not Localize} end; end; FPath := Copy(LURI, 1, LTokenPos); // Get the document if LPramsPos > 0 then begin FDocument := Copy(LURI, 1, LPramsPos - 1); Delete(LURI, 1, LPramsPos - 1); FParams := LURI; end else begin FDocument := LURI; end; Delete(FDocument, 1, LTokenPos); end; // Parse the # bookmark from the document if Length(FBookmark) = 0 then begin FBookmark := FParams; FParams := Fetch(FBookmark, '#'); {Do not Localize} end; end; function TIdURI.GetURI: String; begin FURI := GetFullURI; // result must contain only the proto://host/path/document // If you need the full URI then you have to call GetFullURI result := GetFullURI([]); end; class function TIdURI.URLDecode(ASrc: string): string; var i: integer; ESC: string[2]; CharCode: integer; begin Result := ''; {Do not Localize} ASrc := StringReplace(ASrc, '+', ' ', [rfReplaceAll]); {do not localize} i := 1; while i <= Length(ASrc) do begin if ASrc[i] <> '%' then begin {do not localize} Result := Result + ASrc[i] end else begin Inc(i); // skip the % char ESC := Copy(ASrc, i, 2); // Copy the escape code Inc(i, 1); // Then skip it. try CharCode := StrToInt('$' + ESC); {do not localize} if (CharCode > 0) and (CharCode < 256) then begin Result := Result + Char(CharCode); end; except end; end; Inc(i); end; end; class function TIdURI.ParamsEncode(const ASrc: string): string; var i: Integer; begin Result := ''; {Do not Localize} for i := 1 to Length(ASrc) do begin if ASrc[i] = ' ' then begin {do not localize} Result := Result + '+'; {do not localize} end else if NOT (ASrc[i] in ['A'..'Z', 'a'..'z', '0'..'9']) then begin {do not localize} Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); {do not localize} end else begin Result := Result + ASrc[i]; end; end; end; class function TIdURI.PathEncode(const ASrc: string): string; const UnsafeChars = ['*', '#', '%', '<', '>', '+', ' ']; {do not localize} var i: Integer; begin Result := ''; {Do not Localize} for i := 1 to Length(ASrc) do begin if (ASrc[i] in UnsafeChars) or (ASrc[i] >= #$80) or (ASrc[1] < #32) then begin Result := Result + '%' + IntToHex(Ord(ASrc[i]), 2); {do not localize} end else begin Result := Result + ASrc[i]; end; end; end; class function TIdURI.URLEncode(const ASrc: string): string; Var LURI: TIdURI; begin LURI := TIdURI.Create(ASrc); try LURI.Path := PathEncode(LURI.Path); LURI.Document := PathEncode(LURI.Document); LURI.Params := ParamsEncode(LURI.Params); finally result := LURI.URI; LURI.Free; end; end; function TIdURI.GetFullURI( const AOptionalFileds: TIdURIOptionalFieldsSet): String; Var LURI: String; begin if Length(FProtocol) = 0 then raise EIdURIException.Create(RSURINoProto); LURI := FProtocol + '://'; {Do not Localize} if (Length(FUserName) > 0) and (ofAuthInfo in AOptionalFileds) then begin LURI := LURI + FUserName; if Length(FPassword) > 0 then begin LURI := LURI + ':' + FPassword; {Do not Localize} end; LURI := LURI + '@'; {Do not Localize} end; if Length(FHost) = 0 then raise EIdURIException.Create(RSURINoHost); LURI := LURI + FHost; if Length(FPort) > 0 then begin LURI := LURI + ':' + FPort; {Do not Localize} end; LURI := LURI + FPath + FDocument + FParams; if (Length(FBookmark) > 0) and (ofBookmark in AOptionalFileds) then begin LURI := LURI + '#' + FBookmark; {Do not Localize} end; result := LURI; end; end.
unit FrmModsManage; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFileUtilities, Vcl.StdCtrls, SuperObject, Vcl.ComCtrls, USettingsManager, sButton, sListBox, sLabel, WinApi.ShellApi, ULanguageLoader; type TFrmModManager = class(TForm) PageControl1: TPageControl; sWebLabel1: TsWebLabel; sWebLabel2: TsWebLabel; procedure FormCreate(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnAddCoreClick(Sender: TObject); procedure btnDelClick(Sender: TObject); procedure btnDelCoreClick(Sender: TObject); procedure Refresh; procedure sWebLabel1Click(Sender: TObject); procedure sWebLabel2Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure SetActiveLanguage(LanguageName:string); private { Private declarations } public { Public declarations } TabMods, TabCoreMods : TTabSheet; lstMods, lstCoreMods : TsListBox; btnAdd, btnAddCore: TsButton; btnDel, btnDelCore: TsButton; Version, Cap:string; ll: TLanguageLoader; t, k: TTabSheet; end; var FrmModManager: TFrmModManager; implementation {$R *.dfm} function FindSelectedIndex(lb:TListBox):integer; var i: Integer; begin for i := 0 to lb.Count - 1 do if lb.Selected[i] then exit(i); exit(-1); end; procedure TFrmModManager.SetActiveLanguage(LanguageName:string); var frmComponent:TComponent; i:Integer; jso, tmp: ISuperObject; s:String; jts: TSuperTableString; begin jso := ll.lang[ll.Find(LanguageName)]; tmp := SOFindField(jso, 'FrmModManager.Self.Caption'); if tmp <> nil then begin cap := tmp.AsString; Self.Caption := Cap + Version; end; for i:=0 to ComponentCount-1 do { 遍历Form组件 } begin frmComponent:=Components[i]; tmp := SOFindField(jso, 'FrmModManager.' + frmComponent.Name + '.Caption'); if tmp <> nil then begin s := WideStringToAnsiString(tmp.AsString); if frmComponent is TsLabelFx then { 如果组件为TLabel型则当作TLabel处理,以下同 } begin (frmComponent as TsLabelFx).Caption:=s; end else if frmComponent is TsWebLabel then begin (frmComponent as TsWebLabel).Caption:=s; end else if frmComponent is TsButton then begin (frmComponent as TsButton).Caption:=s; end; end; end; tmp := SOFindField(jso, 'FrmModManager.TabModsManage.Caption'); if tmp <> nil then begin t.Caption := tmp.AsString; end; tmp := SOFindField(jso, 'FrmModManager.TabCoreModsManage.Caption'); if tmp <> nil then begin k.Caption := tmp.AsString; end; end; procedure TFrmModManager.Refresh; var s:TStringList; i:Integer; begin lstMods.Clear; lstCoreMods.Clear; s := TFileUtilities.FindAllFiles(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\mods\'); for i := 0 to s.Count - 1 do lstMods.AddItem(s[i], nil); s := TFileUtilities.FindAllFiles(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\coremods\'); for i := 0 to s.Count - 1 do lstCoreMods.AddItem(s[i], nil); end; procedure TFrmModManager.sWebLabel1Click(Sender: TObject); begin ShellExecute(Self.Handle, nil, PWideChar(WideString('http://files.minecraftforge.net/')), nil, nil, SW_SHOWNORMAL); end; procedure TFrmModManager.sWebLabel2Click(Sender: TObject); begin ShellExecute(Self.Handle, nil, PWideChar(WideString('http://www.mcbbs.net/forum-mod-1.html')), nil, nil, SW_SHOWNORMAL); end; procedure TFrmModManager.btnAddClick(Sender: TObject); var dlg: TOpenDialog; begin dlg := TOpenDialog.Create(self); dlg.Filter := 'Mod File|*.zip,*.jar'; dlg.Title := '选择模组'; if dlg.Execute then begin ForceDirectories(PWideChar(WideString(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\mods\'))); CopyFile(PWideChar(WideString(dlg.FileName)), PWideChar(WideString(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\mods\' + ExtractFileName(dlg.FileName))), false); end; Refresh; end; procedure TFrmModManager.btnAddCoreClick(Sender: TObject); var dlg: TOpenDialog; begin dlg := TOpenDialog.Create(self); dlg.Filter := 'Mod File|*.zip,*.jar'; dlg.Title := '选择模组'; if dlg.Execute then begin ForceDirectories(PWideChar(WideString(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\coremods\'))); CopyFile(PWideChar(WideString(dlg.FileName)), PWideChar(WideString(TFileUtilities.AddSeparator(SMPMinecraftPath) + 'versions\' + Version + '\coremods\' + ExtractFileName(dlg.FileName))), false); end; Refresh; end; procedure TFrmModManager.btnDelClick(Sender: TObject); var name, oldpath, newpath, realpath: String; begin name := lstMods.Items[FindSelectedIndex(lstMods)]; realPath := TFileUtilities.AddSeparator(SMPMinecraftPath); ForceDirectories(PWideChar(WideString(SMPMinecraftPath + '\mods-del\'))); oldpath := realpath + 'versions\' + Version + '\mods\'+ name; newpath := realPath + 'versions\' + Version + '\mods-del\'+ name; MoveFile(PWideChar(WideString(oldpath)), PWideChar(WideString(newpath))); Refresh; end; procedure TFrmModManager.btnDelCoreClick(Sender: TObject); var name, realpath, oldpath, newpath: String; begin name := lstMods.Items[FindSelectedIndex(lstMods)]; realPath := TFileUtilities.AddSeparator(SMPMinecraftPath); ForceDirectories(PWideChar(WideString(realPath + 'coremods-del\'))); oldpath := realpath + 'versions\' + Version + '\coremods\'+ name; newpath := realpath + 'versions\' + Version + '\coremods-del\'+ name; MoveFile(PWideChar(WideString(oldpath)), PWideChar(WideString(newpath))); Refresh; end; procedure TFrmModManager.FormCreate(Sender: TObject); var s:TStringList; i: Integer; begin Self.Caption := Cap + Version; t := TTabSheet.Create(self); t.PageControl := PageControl1; t.TabVisible := true; t.Caption := 'Mods管理'; t.Name := 'TabModsManage'; lstMods := TsListBox.Create(t); lstMods.Parent := t; lstMods.Left := 8; lstMods.Top := 8; lstMods.Height := t.Height - 16; lstMods.Width := 200; lstMods.Name := 'lstMods'; btnAdd := TsButton.Create(t); btnAdd.Parent := t; btnAdd.Top := 8; btnAdd.Left := 216; btnAdd.Caption := '增加'; btnAdd.OnClick := btnAddClick; btnAdd.Name := 'btnAdd'; btnDel := TsButton.Create(t); btnDel.Parent := t; btnDel.Top := 8*2+25; btnDel.Left := 216; btnDel.Caption := '删除'; btnDel.OnClick := btnDelClick; btnDel.Name := 'btnDel'; k := TTabSheet.Create(self); k.PageControl := PageControl1; k.TabVisible := true; k.Caption := 'CoreMods管理'; k.Name := 'TabCoreModsManage'; lstCoreMods := TsListBox.Create(k); lstCoreMods.Parent := k; lstCoreMods.Left := 8; lstCoreMods.Top := 8; lstCoreMods.Height := k.Height - 16; lstCoreMods.Width := 200; lstCoreMods.Name := 'lstCoreMods'; btnAddCore := TsButton.Create(k); btnAddCore.Parent := k; btnAddCore.Top := 8; btnAddCore.Left := 216; btnAddCore.Caption := '增加'; btnAddCore.OnClick := btnAddCoreClick; btnAddCore.Name := 'btnAddCore'; btnDelCore := TsButton.Create(k); btnDelCore.Parent := k; btnDelCore.Top := 8*2+25; btnDelCore.Left := 216; btnDelCore.Caption := '删除'; btnDelCore.OnClick := btnDelCoreClick; btnDelCore.Name := 'btnDelCore'; Refresh; ll := TLanguageLoader.Create(TFileUtilities.ReadToEnd('lang.json')); end; procedure TFrmModManager.FormShow(Sender: TObject); begin Refresh; SetActiveLanguage(SMPLanguage); end; end.
unit CommonConst; interface const REG_APP_NAME = 'DsgLib.1'; FILE_EXT = '.zcb'; NEW_FILE_NAME_NO_EXT = 'Элементы схем'; NEW_FILE_NAME = NEW_FILE_NAME_NO_EXT + FILE_EXT; MSG_CONSIST_NAME = 'Совпадение имен.'; HELP_CONSIST_NAME = 0; MSG_DELETE_PARAM = 'Удалить параметр ?'; HELP_DELETE_PARAM = 0; MSG_NO_FILE = 'Файл не существует.'; HELP_NO_FILE = 0; MSG_NO_SAVE = 'Невозможно сохранить данные.'; HELP_NO_SAVE = 0; MSG_FILE_EDIT = 'Файл был изменен. Сохранить изменения ?'; HELP_FILE_EDIT = 0; implementation end.
unit IdMessageClient; { 2001-Oct-29 Don Siders Modified TIdMessageClient.SendMsg to use AHeadersOnly argument. 2001-Dec-1 Don Siders Save ContentDisposition in TIdMessageClient.ProcessAttachment } interface uses Classes, IdGlobal, IdMessage, IdTCPClient, IdHeaderList; type TIdMessageClient = class(TIdTCPClient) protected // The length of the folded line FMsgLineLength: integer; // The string to be pre-pended to the next line FMsgLineFold: string; // procedure ReceiveBody(AMsg: TIdMessage; const ADelim: string = '.'); virtual; function ReceiveHeader(AMsg: TIdMessage; const AAltTerm: string = ''): string; virtual; procedure SendBody(AMsg: TIdMessage); virtual; procedure SendHeader(AMsg: TIdMessage); virtual; procedure WriteBodyText(AMsg: TIdMessage); virtual; procedure WriteFoldedLine(const ALine : string); public constructor Create(AOwner : TComponent); override; procedure ProcessMessage(AMsg: TIdMessage; AHeaderOnly: Boolean = False); overload; procedure ProcessMessage(AMsg: TIdMessage; const AStream: TStream; AHeaderOnly: Boolean = False); overload; procedure ProcessMessage(AMsg: TIdMessage; const AFilename: string; AHeaderOnly: Boolean = False); overload; procedure SendMsg(AMsg: TIdMessage; const AHeadersOnly: Boolean = False); virtual; // property MsgLineLength: integer read FMsgLineLength write FMsgLineLength; property MsgLineFold: string read FMsgLineFold write FMsgLineFold; end; implementation uses //TODO: Remove these references and make it completely pluggable. Check other spots in Indy as well IdCoderQuotedPrintable, IdMessageCoderMIME, IdMessageCoderUUE, IdMessageCoderXXE, // IdCoder, IdCoder3to4, IdCoderHeader, IdMessageCoder, IdComponent, IdException, IdResourceStrings, IdTCPConnection, IdTCPStream, IdIOHandlerStream, IdIOHandler, SysUtils; function GetLongestLine(var ALine : String; ADelim : String) : String; var i, fnd, lineLen, delimLen : Integer; begin i := 0; fnd := -1; delimLen := length(ADelim); lineLen := length(ALine); while i < lineLen do begin if ALine[i] = ADelim[1] then begin if Copy(ALine, i, delimLen) = ADelim then begin fnd := i; end; end; Inc(i); end; if fnd = -1 then begin result := ''; end else begin result := Copy(ALine, 1, fnd - 1); ALine := Copy(ALine, fnd + delimLen, lineLen); end; end; /////////////////// // TIdMessageClient /////////////////// constructor TIdMessageClient.Create; begin inherited; FMsgLineLength := 79; FMsgLineFold := TAB; end; procedure TIdMessageClient.WriteFoldedLine; var ins, s, line, spare : String; msgLen, insLen : Word; begin s := ALine; // To give an amount of thread-safety ins := FMsgLineFold; insLen := Length(ins); msgLen := FMsgLineLength; // Do first line if length(s) > FMsgLineLength then begin spare := Copy(s, 1, msgLen); line := GetLongestLine(spare, ' '); s := spare + Copy(s, msgLen + 1, length(s)); WriteLn(line); // continue with the folded lines while length(s) > (msgLen - insLen) do begin spare := Copy(s, 1, (msgLen - insLen)); line := GetLongestLine(spare, ' '); s := ins + spare + Copy(s, (msgLen - insLen) + 1, length(s)); WriteLn(line); end; // complete the output with what's left if Trim(s) <> '' then begin WriteLn(ins + s); end; end else begin WriteLn(s); end; end; procedure TIdMessageClient.ReceiveBody(AMsg: TIdMessage; const ADelim: string = '.'); var LMsgEnd: Boolean; LActiveDecoder: TIdMessageDecoder; LLine: string; function ProcessTextPart(ADecoder: TIdMessageDecoder): TIdMessageDecoder; var LDestStream: TStringStream; begin LDestStream := TStringStream.Create(''); try Result := ADecoder.ReadBody(LDestStream, LMsgEnd); with TIdText.Create(AMsg.MessageParts) do begin ContentType := ADecoder.Headers.Values['Content-Type']; ContentTransfer := ADecoder.Headers.Values['Content-Transfer-Encoding']; Body.Text := LDestStream.DataString; end; ADecoder.Free; finally FreeAndNil(LDestStream); end; end; function ProcessAttachment(ADecoder: TIdMessageDecoder): TIdMessageDecoder; var LDestStream: TFileStream; LTempPathname: string; begin LTempPathname := MakeTempFilename; LDestStream := TFileStream.Create(LTempPathname, fmCreate); try Result := ADecoder.ReadBody(LDestStream, LMsgEnd); with TIdAttachment.Create(AMsg.MessageParts) do begin ContentType := ADecoder.Headers.Values['Content-Type']; ContentTransfer := ADecoder.Headers.Values['Content-Transfer-Encoding']; // dsiders 2001.12.01 ContentDisposition := ADecoder.Headers.Values['Content-Disposition']; Filename := ADecoder.Filename; StoredPathname := LTempPathname; end; ADecoder.Free; finally FreeAndNil(LDestStream); end; end; const wDoublePoint = ord('.') shl 8 + ord('.'); Begin LMsgEnd := False; if AMsg.NoDecode then begin Capture(AMsg.Body, ADelim); end else begin BeginWork(wmRead); try LActiveDecoder := nil; repeat LLine := ReadLn; if LLine = ADelim then begin Break; end; if LActiveDecoder = nil then begin LActiveDecoder := TIdMessageDecoderList.CheckForStart(AMsg, LLine); end; if LActiveDecoder = nil then begin if PWord(PChar(LLine))^= wDoublePoint then begin Delete(LLine,1,1); end;//if '..' AMsg.Body.Add(LLine); end else begin while LActiveDecoder <> nil do begin LActiveDecoder.SourceStream := TIdTCPStream.Create(Self); LActiveDecoder.ReadHeader; case LActiveDecoder.PartType of mcptUnknown: begin raise EIdException.Create(RSMsgClientUnkownMessagePartType); end; mcptText: begin LActiveDecoder := ProcessTextPart(LActiveDecoder); end; mcptAttachment: begin LActiveDecoder := ProcessAttachment(LActiveDecoder); end; end; end; end; until LMsgEnd; finally EndWork(wmRead); end; end; end; procedure TIdMessageClient.SendHeader(AMsg: TIdMessage); var LHeaders: TIdHeaderList; begin LHeaders := AMsg.GenerateHeader; try WriteStrings(LHeaders); finally FreeAndNil(LHeaders); end; end; procedure TIdMessageClient.SendBody(AMsg: TIdMEssage); var i: Integer; LAttachment: TIdAttachment; LBoundary: string; LDestStream: TIdTCPStream; LMIMEAttachments: boolean; ISOCharset: string; HeaderEncoding: Char; { B | Q } TransferEncoding: TTransfer; procedure WriteTextPart(ATextPart: TIdText); var Data: string; i: Integer; begin if Length(ATextPart.ContentType) = 0 then ATextPart.ContentType := 'text/plain'; {do not localize} if Length(ATextPart.ContentTransfer) = 0 then ATextPart.ContentTransfer := 'quoted-printable'; {do not localize} WriteLn('Content-Type: ' + ATextPart.ContentType); {do not localize} WriteLn('Content-Transfer-Encoding: ' + ATextPart.ContentTransfer); {do not localize} WriteStrings(ATextPart.ExtraHeaders); WriteLn(''); // TODO: Provide B64 encoding later // if AnsiSameText(ATextPart.ContentTransfer, 'base64') then begin // LEncoder := TIdEncoder3to4.Create(nil); if AnsiSameText(ATextPart.ContentTransfer, 'quoted-printable') then begin for i := 0 to ATextPart.Body.Count - 1 do begin if Copy(ATextPart.Body[i], 1, 1) = '.' then begin ATextPart.Body[i] := '.' + ATextPart.Body[i]; end; Data := TIdEncoderQuotedPrintable.EncodeString(ATextPart.Body[i] + EOL); if TransferEncoding = iso2022jp then Write(Encode2022JP(Data)) else Write(Data); end; end else begin WriteStrings(ATextPart.Body); end; WriteLn(''); end; begin LMIMEAttachments := AMsg.Encoding = meMIME; LBoundary := ''; InitializeISO(TransferEncoding, HeaderEncoding, ISOCharSet); BeginWork(wmWrite); try if AMsg.MessageParts.AttachmentCount > 0 then begin if LMIMEAttachments then begin WriteLn('This is a multi-part message in MIME format'); {do not localize} WriteLn(''); if AMsg.MessageParts.RelatedPartCount > 0 then begin LBoundary := IndyMultiPartRelatedBoundary; end else begin LBoundary := IndyMIMEBoundary; end; WriteLn('--' + LBoundary); end else begin // It's UU, write the body WriteBodyText(AMsg); WriteLn(''); end; if AMsg.MessageParts.TextPartCount > 1 then begin WriteLn('Content-Type: multipart/alternative; '); {do not localize} WriteLn(' boundary="' + IndyMultiPartAlternativeBoundary + '"'); {do not localize} WriteLn(''); for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts.Items[i] is TIdText then begin WriteLn('--' + IndyMultiPartAlternativeBoundary); DoStatus(hsStatusText, [RSMsgClientEncodingText]); WriteTextPart(AMsg.MessageParts.Items[i] as TIdText); WriteLn(''); end; end; WriteLn('--' + IndyMultiPartAlternativeBoundary + '--'); end else begin if LMIMEAttachments then begin WriteLn('Content-Type: text/plain'); {do not localize} WriteLn('Content-Transfer-Encoding: 7bit'); {do not localize} WriteLn(''); WriteBodyText(AMsg); end; end; // Send the attachments for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts[i] is TIdAttachment then begin LAttachment := TIdAttachment(AMsg.MessageParts[i]); DoStatus(hsStatusText, [RSMsgClientEncodingAttachment]); if LMIMEAttachments then begin WriteLn(''); WriteLn('--' + LBoundary); if Length(LAttachment.ContentTransfer) = 0 then begin LAttachment.ContentTransfer := 'base64'; {do not localize} end; if Length(LAttachment.ContentDisposition) = 0 then begin LAttachment.ContentDisposition := 'attachment'; {do not localize} end; if (LAttachment.ContentTransfer = 'base64') {do not localize} and (Length(LAttachment.ContentType) = 0) then begin LAttachment.ContentType := 'application/octet-stream'; {do not localize} end; WriteLn('Content-Type: ' + LAttachment.ContentType + ';'); {do not localize} WriteLn(' name="' + ExtractFileName(LAttachment.FileName) + '"'); {do not localize} WriteLn('Content-Transfer-Encoding: ' + LAttachment.ContentTransfer); {do not localize} WriteLn('Content-Disposition: ' + LAttachment.ContentDisposition +';'); {do not localize} WriteLn(' filename="' + ExtractFileName(LAttachment.FileName) + '"'); {do not localize} WriteStrings(LAttachment.ExtraHeaders); WriteLn(''); end; LDestStream := TIdTCPStream.Create(Self); try TIdAttachment(AMsg.MessageParts[i]).Encode(LDestStream); finally FreeAndNil(LDestStream); end; WriteLn(''); end; end; if LMIMEAttachments then begin WriteLn('--' + LBoundary + '--'); end; end else if AMsg.MessageParts.TextPartCount > 1 then begin WriteLn('This is a multi-part message in MIME format'); {do not localize} WriteLn(''); for i := 0 to AMsg.MessageParts.Count - 1 do begin if AMsg.MessageParts.Items[i] is TIdText then begin WriteLn('--' + IndyMIMEBoundary); DoStatus(hsStatusText, [RSMsgClientEncodingText]); WriteTextPart(AMsg.MessageParts.Items[i] as TIdText); end; end; WriteLn('--' + IndyMIMEBoundary + '--'); end else begin DoStatus(hsStatusText, [RSMsgClientEncodingText]); // Write out Body //TODO: Why just iso2022jp? Why not someting generic for all MBCS? Or is iso2022jp special? if TransferEncoding = iso2022jp then begin for i := 0 to AMsg.Body.Count - 1 do begin if Copy(AMsg.Body[i], 1, 1) = '.' then begin WriteLn('.' + Encode2022JP(AMsg.Body[i])); end else begin WriteLn(Encode2022JP(AMsg.Body[i])); end; end; end else begin WriteBodyText(AMsg); end; end; finally EndWork(wmWrite); end; end; { 2001-Oct-29 Don Siders procedure TIdMessageClient.SendMsg(AMsg: TIdMessage); begin SendHeader(AMsg); WriteLn(''); SendBody(AMsg); end; } // 2001-Oct-29 Don Siders Added AHeadersOnly parameter // TODO: Override TIdMessageClient.SendMsg to provide socket, stream, and file // versions like TIdMessageClient.ProcessMessage? procedure TIdMessageClient.SendMsg(AMsg: TIdMessage; const AHeadersOnly: Boolean = False); begin if AMsg.NoEncode then begin WriteStringS(AMsg.Headers); WriteLn(''); if not AHeadersOnly then begin WriteStrings(AMsg.Body); end; end else begin SendHeader(AMsg); WriteLn(''); if (not AHeadersOnly) then SendBody(AMsg); end; end; function TIdMessageClient.ReceiveHeader(AMsg: TIdMessage; const AAltTerm: string = ''): string; begin BeginWork(wmRead); try repeat Result := ReadLn; // Exchange Bug: Exchange sometimes returns . when getting a message instead of // '' then a . - That is there is no seperation between the header and the message for an // empty message. if ((Length(AAltTerm) = 0) and (Result = '.')) or ({APR: why? (Length(AAltTerm) > 0) and }(Result = AAltTerm)) then begin Break; end else if Result <> '' then begin AMsg.Headers.Append(Result); end; until False; AMsg.ProcessHeaders; finally EndWork(wmRead); end; end; procedure TIdMessageclient.ProcessMessage(AMsg: TIdMessage; AHeaderOnly: Boolean = False); begin if IOHandler <> nil then begin ReceiveHeader(AMsg); if (not AHeaderOnly) then begin ReceiveBody(AMsg); end; end; end; procedure TIdMessageClient.ProcessMessage(AMsg: TIdMessage; const AStream: TStream; AHeaderOnly: Boolean = False); var LVoidStream: TMemoryStream; begin LVoidStream := TMemoryStream.Create; try IOHandler := TIdIOHandlerStream.Create(nil); try TIdIOHandlerStream(IOHandler).ReadStream := AStream; TIdIOHandlerStream(IOHandler).WriteStream := LVoidStream; ReceiveHeader(AMsg); if not AHeaderOnly then begin ReceiveBody(AMsg); end; finally IOHandler.Free; IOHandler := nil; end; finally FreeAndNil(LVoidStream); end; end; procedure TIdMessageClient.ProcessMessage(AMsg: TIdMessage; const AFilename: string; AHeaderOnly: Boolean = False); var LStream: TFileStream; begin LStream := TFileStream.Create(AFileName, fmOpenRead); try ProcessMessage(AMsg, LStream, AHeaderOnly); finally FreeAndNil(LStream); end; end; procedure TIdMessageClient.WriteBodyText(AMsg: TIdMessage); var i: integer; begin for i := 0 to AMsg.Body.Count - 1 do begin if Copy(AMsg.Body[i], 1, 1) = '.' then begin WriteLn('.' + AMsg.Body[i]); end else begin WriteLn(AMsg.Body[i]); end; end; end; end.
unit IWTreeview; {PUBDIST} interface uses {$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF} {$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF} {$IFDEF Linux}QForms,{$ELSE}Forms,{$ENDIF} Classes, SysUtils, IWControl, IWHTMLTag, IWFileReference; Type TIWTreeViewItems = class; IIWTreeViewDesigner = interface procedure RefreshItems; end; TIWTreeViewItem = class(TCollectionItem) protected FCaption: String; FExpanded: Boolean; FItems: TIWTreeViewItems; FName: String; FOnClick: TNotifyEvent; // procedure DefineProperties(AFiler: TFiler); override; function GetDisplayName: string; override; procedure ReadData(AReader: TReader); procedure SetDisplayName(const AValue: string); override; procedure SetItems(const Value: TIWTreeViewItems); procedure SetCaption(const Value: string); procedure WriteData(AWriter: TWriter); public property SubItems: TIWTreeViewItems read FItems write SetItems; // procedure AssignTo(ADest: TPersistent); override; constructor Create(ACollection: TCollection); override; function GetNamePath: string; override; destructor Destroy; override; procedure DoClick; published property Caption: string read FCaption write SetCaption; property Expanded: Boolean read FExpanded write FExpanded; property Name: string read FName write FName; property OnClick: TNotifyEvent read FOnClick write FOnClick; end; TIWTreeViewItems = class(TOwnedCollection) protected FDesigner: IIWTreeViewDesigner; function GetItem(AIndex: Integer): TIWTreeViewItem; procedure SetItem(AIndex: Integer; const AValue: TIWTreeViewItem); public function Add: TIWTreeViewItem; constructor Create(AOwner: TPersistent); destructor Destroy; override; procedure SetDesigner(ADesigner: IIWTreeViewDesigner); // property Items[AIndex: Integer]: TIWTreeViewItem read GetItem write SetItem; default; end; TIWTreeViewImages = class(TPersistent) protected FClosedFolderImage: TIWFileReference; FOpenFolderImage: TIWFileReference; FDocumentImage: TIWFileReference; FPlusImage: TIWFileReference; FMinusImage: TIWFileReference; // procedure SetClosedFolderImage(const Value: TIWFileReference); procedure SetDocumentImage(const Value: TIWFileReference); procedure SetMinusImage(const Value: TIWFileReference); procedure SetOpenFolderImage(const Value: TIWFileReference); procedure SetPlusImage(const Value: TIWFileReference); public constructor Create; destructor Destroy; override; published property OpenFolderImage: TIWFileReference read FOpenFolderImage write SetOpenFolderImage; property ClosedFolderImage: TIWFileReference read FClosedFolderImage write SetClosedFolderImage; property DocumentImage: TIWFileReference read FDocumentImage write SetDocumentImage; property PlusImage: TIWFileReference read FPlusImage write SetPlusImage; property MinusImage: TIWFileReference read FMinusImage write SetMinusImage; end; //@@ TIWTreeView implements a tree control in your application that allows for consolidation //of hierarchical data. Nodes can be assigned OnClick events. // //Note: TIWTreeView does work in Netscape 4 however when it is used in Netscape 4 and templates //are used there are some special considerations. Netscape 4 does not support DHTML on inline //HTML sections. It only supports DHTML on absolutely positioned sections. Because of this //the TIWTreeView will be output in a DIV aligned to the coordinates on the form even when //in a template. The name of the div will be the treeview name + Div. You can use javascript //or other methods to modify the DIV in your HTML. // //This only applies to Netscape 4. For other browsers the treeview is renderd in an inline SPAN //tag which other HTML will properly flow around when used with a template. You may wish to use //a different template or Netscape 4 by using the browser specific template features of //TIWTemplateProcessorHTML. TIWTreeView = class(TIWControl) protected FTreeViewItems: TIWTreeViewItems; FTreeViewImages: TIWTreeViewImages; FVertScrollBarVisible: Boolean; FHorScrollBarVisible: Boolean; // procedure SetTreeViewItems(const AValue: TIWTreeViewItems); procedure Submit(const AValue: string); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function RenderHTML: TIWHTMLTag; override; published property Font; property Items: TIWTreeViewItems read FTreeViewItems write SetTreeViewItems; property TreeViewImages: TIWTreeViewImages read FTreeViewImages write FTreeViewImages; property VertScrollBarVisible: Boolean read FVertScrollBarVisible write FVertScrollBarVisible; property HorScrollBarVisible: Boolean read FHorScrollBarVisible write FHorScrollBarVisible; end; implementation uses IWApplication, IWAppForm, IWTypes, IWForm, IWServer, SWSystem; { TIWTreeView } constructor TIWTreeView.Create(AOwner: TComponent); begin inherited Create(AOwner); FSupportsSubmit := True; FClip := True; Width := 200; Height := 200; FTreeViewItems := TIWTreeViewItems.Create(self); FTreeViewImages := TIWTreeViewImages.Create; FRenderSize := true; FVertScrollBarVisible := false; FHorScrollBarVisible := false; if not FDesignMode then begin GIWServer.AddInternalFile('IW_JS_IWTreeView'); end; end; destructor TIWTreeView.Destroy; begin FreeAndNil(FTreeViewItems); FreeAndNil(FTreeViewImages); inherited Destroy; end; function TIWTreeView.RenderHTML: TIWHTMLTag; var LScript: string; function BuildAddition(AItems: TIWTreeViewItems; AIdent : Integer = 1): String; var i: Integer; LItem: TIWTreeViewItem; begin result := ''; for i := 0 to AItems.Count - 1 do begin LItem := AItems.Items[i]; Result := Result + StringOfChar(' ', AIdent - 1) + 'new AddTVItem(' + HTMLName + 'IWCL' + ', "' + LItem.Caption + '"' + ', ' + iif(Assigned(LItem.OnClick), IntToStr(Integer(LItem)), '0') + ', "' + LItem.Name + '"' + ', ' + iif(LItem.Expanded, 'true', 'false') + ', '; if AItems.Items[i].SubItems.Count > 0 then begin result := result + EOL + BuildAddition(AItems.Items[i].SubItems, AIdent + 1) + ', '; end else begin result := result + 'null, '; end; if i = AItems.Count - 1 then begin result := result + 'null'; end else begin result := result + EOL; end; end; Result := Result + StringOfChar(')', AItems.Count); end; Var LOpenImg, LCloseImg, LDocImg, LPlusImg, LMinusImg: String; LStyle: String; begin if Items.Count = 0 then begin Result := nil; end else begin AddScriptFile('/js/IWTreeView.js'); LOpenImg := iif(FTreeViewImages.OpenFolderImage.Location(WebApplication.URLBase), FTreeViewImages.OpenFolderImage.Location(WebApplication.URLBase), WebApplication.URLBase + '/gfx/TIWTreeview_open.gif'); LCloseImg := iif(FTreeViewImages.ClosedFolderImage.Location(WebApplication.URLBase), FTreeViewImages.ClosedFolderImage.Location(WebApplication.URLBase), WebApplication.URLBase + '/gfx/TIWTreeview_closed.gif'); LDocImg := iif(FTreeViewImages.DocumentImage.Location(WebApplication.URLBase), FTreeViewImages.DocumentImage.Location(WebApplication.URLBase), WebApplication.URLBase + '/gfx/TIWTreeview_document.gif'); LPlusImg := iif(FTreeViewImages.PlusImage.Location(WebApplication.URLBase), FTreeViewImages.PlusImage.Location(WebApplication.URLBase), WebApplication.URLBase + '/gfx/TIWTreeview_plus.gif'); LMinusImg := iif(FTreeViewImages.MinusImage.Location(WebApplication.URLBase), FTreeViewImages.MinusImage.Location(WebApplication.URLBase), WebApplication.URLBase + '/gfx/TIWTreeview_minus.gif'); LScript := HTMLName + 'IWCL.ImgOpen = "'+ LOpenImg + '";' + EOL + HTMLName + 'IWCL.ImgClosed = "' + LCloseImg + '";' + EOL + HTMLName + 'IWCL.ImgDocument = "' + LDocImg + '";' + EOL + HTMLName + 'IWCL.ImgPlus = "' + LPlusImg + '";' + EOL + HTMLName + 'IWCL.ImgMinus = "' + LMinusImg + '";' + EOL + HTMLName + 'IWCL.ImgBlank = "' + WebApplication.URLBase + '/gfx/Tp.gif";' + EOL + HTMLName + 'IWCL.Items = ' + EOL + BuildAddition(FTreeViewItems) + ';' + EOL + 'showTreeView(' + HTMLName + 'IWCL);' + EOL; with TIWAppForm(Form) do begin CacheImage(Self.HTMLName + '_Open', LOpenImg); CacheImage(Self.HTMLName + '_Closed', LCloseImg); CacheImage(Self.HTMLName + '_Document', LDocImg); CacheImage(Self.HTMLName + '_Plus', LPlusImg); CacheImage(Self.HTMLName + '_Minus', LMinusImg); CacheImage(Self.HTMLName + '_Blank', WebApplication.URLBase + '/gfx/Tp.gif'); end; AddToInitProc(LScript); Result := TIWHTMLTag.CreateTag('DIV'); try Result.Contents.AddText('&nbsp;'); LStyle := ''; if VertScrollBarVisible then begin LStyle := LStyle + 'overflow-y:scroll;'; end; if HorScrollBarVisible then begin LStyle := LStyle + 'overflow-x:scroll;'; end; if LStyle <> '' then begin Result.AddStringParam('STYLE', LStyle); end; except FreeAndNil(Result); raise; end; end; end; procedure TIWTreeView.SetTreeViewItems(const AValue: TIWTreeViewItems); begin FTreeViewItems.Assign(AValue); end; procedure TIWTreeView.Submit(const AValue: string); begin TIWTreeViewItem(StrToInt(AValue)).DoClick; end; { TIWTreeViewItem } procedure TIWTreeViewItem.AssignTo(ADest: TPersistent); begin if ADest is TIWTreeViewItem then begin with TIWTreeViewItem(ADest) do begin Caption := Self.Caption; Expanded := Self.Expanded; SubItems := Self.SubItems; Name := Self.Name; OnClick := Self.OnClick; end; end else begin inherited; end; end; constructor TIWTreeViewItem.Create(ACollection: TCollection); var i: Integer; LItem: TIWTreeViewItem; LName: string; LTree: TIWTreeView; LOwner: TPersistent; function NameIsUsed(const AName: string; AItems: TIWTreeViewItems): Boolean; var i: Integer; begin Result := False; for i := 0 to AItems.Count - 1 do begin Result := AnsiSameText(AName, AItems.Items[i].Name) or NameIsUsed(AName, AItems.Items[i].SubItems); if Result then begin Break; end; end; end; begin inherited Create(ACollection); // Must be before Find Name as it uses Items FItems := TIWTreeViewItems.Create(self); // Find a unique name // // Travel up to find the tree itself LTree := nil; LItem := Self; while LTree = nil do begin LOwner := LItem.GetOwner; if LOwner is TIWTreeView then begin LTree := TIWTreeView(LOwner); end else begin LItem := TIWTreeViewItem(LOwner); end; end; // Find a unique name for i := 0 to MaxInt do begin // Dont assign to FName otherwise NameIsUsed will find this item and return true every time. LName := LTree.Name + 'Item' + IntToStr(i); if not NameIsUsed(LName, LTree.Items) then begin Break; end; end; // FName := LName; // Remove the below since at run-time it renames the caption back to the default if FCaption = '' then begin FCaption := LName; end; FExpanded := True; end; procedure TIWTreeViewItem.DefineProperties(AFiler: TFiler); begin inherited; AFiler.DefineProperty('SubItems', ReadData, WriteData, True); end; destructor TIWTreeViewItem.Destroy; begin FreeAndNil(FItems); inherited Destroy; end; procedure TIWTreeViewItem.DoClick; begin if Assigned(FOnClick) then begin FOnClick(self); end; end; function TIWTreeViewItem.GetDisplayName: string; begin Result := FName; end; function TIWTreeViewItem.GetNamePath: string; begin if Collection <> nil then begin Result := TIWTreeViewItems(Collection).GetOwner.GetNamePath + '.' + GetDisplayName; end else begin Result := inherited GetNamePath; end; end; procedure TIWTreeViewItem.ReadData(AReader: TReader); begin AReader.CheckValue(vaCollection); AReader.ReadCollection(SubItems); end; procedure TIWTreeViewItem.SetCaption(const Value: string); Var LDesigner: IDesignerNotify; LCollection: TCollection; begin FCaption := Value; LDesigner := FindRootDesigner(self); if LDesigner <> nil then begin LDesigner.Modified; end; LCollection := TCollection(GetOwner); if (LCollection <> nil) and (LCollection is TIWTreeViewItems) then begin if TIWTreeViewItems(LCollection).FDesigner <> nil then begin TIWTreeViewItems(LCollection).FDesigner.RefreshItems; end; end; end; procedure TIWTreeViewItem.SetDisplayName(const AValue: string); begin FName := AValue; inherited SetDisplayName(AValue); end; procedure TIWTreeViewItem.SetItems(const Value: TIWTreeViewItems); begin FItems.Assign(Value); end; procedure TIWTreeViewItem.WriteData(AWriter: TWriter); begin AWriter.WriteCollection(SubItems); end; { TIWTreeViewItems } constructor TIWTreeViewItems.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIWTreeViewItem); end; function TIWTreeViewItems.Add: TIWTreeViewItem; begin result := TIWTreeViewItem(inherited Add); end; function TIWTreeViewItems.GetItem(AIndex: Integer): TIWTreeViewItem; begin result := TIWTreeViewItem(inherited Items[AIndex]); end; procedure TIWTreeViewItems.SetItem(AIndex: Integer; const AValue: TIWTreeViewItem); begin TIWTreeViewItem(inherited Items[AIndex]).Assign(AValue); end; procedure TIWTreeViewItems.SetDesigner(ADesigner: IIWTreeViewDesigner); Var i: Integer; begin FDesigner := ADesigner; for i := 0 to Count -1 do begin Items[i].SubItems.SetDesigner(ADesigner); end; end; destructor TIWTreeViewItems.Destroy; begin FDesigner := nil; inherited Destroy; end; { TIWTreeViewImages } constructor TIWTreeViewImages.Create; begin inherited Create; FClosedFolderImage := TIWFileReference.Create; FOpenFolderImage := TIWFileReference.Create; FDocumentImage := TIWFileReference.Create; FPlusImage := TIWFileReference.Create; FMinusImage := TIWFileReference.Create; end; destructor TIWTreeViewImages.Destroy; begin FreeAndNil(FClosedFolderImage); FreeAndNil(FOpenFolderImage); FreeAndNil(FDocumentImage); FreeAndNil(FPlusImage); FreeAndNil(FMinusImage); inherited Destroy; end; procedure TIWTreeViewImages.SetClosedFolderImage( const Value: TIWFileReference); begin FClosedFolderImage.Assign(Value); end; procedure TIWTreeViewImages.SetDocumentImage( const Value: TIWFileReference); begin FDocumentImage.Assign(Value); end; procedure TIWTreeViewImages.SetMinusImage(const Value: TIWFileReference); begin FMinusImage.Assign(Value); end; procedure TIWTreeViewImages.SetOpenFolderImage( const Value: TIWFileReference); begin FOpenFolderImage.Assign(Value); end; procedure TIWTreeViewImages.SetPlusImage(const Value: TIWFileReference); begin FPlusImage.Assign(Value); end; end.
unit ccHash; interface const SHA256_SIZE = 32; function SHA256(pData: Pointer; iData: Integer; pKey: Pointer; iKey: Integer): Pointer; implementation uses Windows, WinApi_BCrypt; function SHA256(pData: Pointer; iData: Integer; pKey: Pointer; iKey: Integer): Pointer; var status: NTSTATUS; hAlg: BCRYPT_ALG_HANDLE; hHash: BCRYPT_HASH_HANDLE; dwFlags: Cardinal; cbData: Cardinal; cbHashObject: Cardinal; pbHashObject: Pointer; cbHash: Cardinal; pbHash: Pointer; begin Result := nil; hAlg := nil; hHash := nil; pbHashObject := nil; try // use HMAC if we got a key dwFlags := 0; if Assigned(pKey) then dwFlags := BCRYPT_ALG_HANDLE_HMAC_FLAG; //open an algorithm handle status := BCryptOpenAlgorithmProvider(hAlg, BCRYPT_SHA256_ALGORITHM, nil, dwFlags); if status <> 0 then exit; //calculate the size of the buffer to hold the hash object status := BCryptGetProperty(hAlg, BCRYPT_OBJECT_LENGTH, @cbHashObject, sizeof(Integer), cbData, 0); if status <> 0 then exit; //allocate the hash object on the heap GetMem(pbHashObject, cbHashObject); //calculate the length of the hash status := BCryptGetProperty(hAlg, BCRYPT_HASH_LENGTH, @cbHash, sizeof(Integer), cbData, 0); if status <> 0 then exit; //allocate the hash buffer on the heap GetMem(pbHash, cbHash); //create a hash status := BCryptCreateHash(hAlg, hHash, pbHashObject, cbHashObject, pKey, iKey, 0); if status <> 0 then exit; //hash some data status := BCryptHashData(hHash, pData, iData, 0); if status <> 0 then exit; //close the hash status := BCryptFinishHash(hHash, pbHash, cbHash, 0); if status <> 0 then exit; Result := pbHash; finally BCryptCloseAlgorithmProvider(hAlg, 0); BCryptDestroyHash(hHash); FreeMem(pbHashObject); //FreeMem(pbHash); // caller frees end; end; end.
unit TBCEditorDemo.Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, BCCommon.Forms.Base, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, BCEditor.Editor, BCEditor.Highlighter, BCEditor.Editor.Base, BCCommon.Frames.Search, Vcl.Buttons, Vcl.AppEvnts, System.Actions, Vcl.ActnList, BCEditor.Print, BCCommon.Images, BCComponents.SkinProvider, BCComponents.SkinManager, BCControls.Panel, BCControls.StatusBar, BCComponents.TitleBar, Vcl.Menus, ToolCtrlsEh, DBGridEhToolCtrls, EhLibVCL, DBAxisGridsEh, ObjectInspectorEh, BCControls.Splitter, GridsEh, BCCommon.Frames.Base, sPanel, BCComponents.MultiStringHolder, sSkinManager, sStatusBar, sSplitter, acTitleBar, sSkinProvider, System.Win.TaskbarCore, Vcl.Taskbar, sDialogs, Vcl.StdCtrls, sButton, BCControls.Button, System.Diagnostics; const BCEDITORDEMO_CAPTION = 'TBCEditor Control Demo v1.0b'; type TMainForm = class(TBCBaseForm) ActionFileOpen: TAction; ActionPreview: TAction; ActionSearch: TAction; Editor: TBCEditor; MenuItemExit: TMenuItem; MenuItemFileOpen: TMenuItem; MenuItemPrintPreview: TMenuItem; MenuItemSeparator1: TMenuItem; MenuItemSeparator2: TMenuItem; MultiStringHolderFileTypes: TBCMultiStringHolder; ObjectInspectorEh: TObjectInspectorEh; PanelLeft: TBCPanel; PanelProperty: TBCPanel; PopupMenuColors: TPopupMenu; PopupMenuFile: TPopupMenu; PopupMenuHighlighters: TPopupMenu; Splitter: TBCSplitter; OpenDialog: TsOpenDialog; SearchFrame: TBCSearchFrame; MenuItemSkins: TMenuItem; ActionSkins: TAction; procedure ActionFileOpenExecute(Sender: TObject); procedure ActionPreviewExecute(Sender: TObject); procedure ActionSearchExecute(Sender: TObject); procedure ActionSelectHighlighterColorExecute(Sender: TObject); procedure ActionSelectHighlighterExecute(Sender: TObject); procedure ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure SkinManagerGetMenuExtraLineData(FirstItem: TMenuItem; var SkinSection, Caption: string; var Glyph: TBitmap; var LineVisible: Boolean); procedure EditorCaretChanged(Sender: TObject; X, Y: Integer); procedure ActionSkinsExecute(Sender: TObject); private FStopWatch: TStopWatch; procedure InitializeEditorPrint(EditorPrint: TBCEditorPrint); procedure PrintPreview; procedure SetHighlighterColors; procedure SetHighlighters; end; var MainForm: TMainForm; implementation {$R *.dfm} uses BCCommon.Language.Strings, BCCommon.Forms.Print.Preview, BCEditor.Print.Types, BCCommon.StringUtils, BCCommon.Dialogs.SkinSelect; procedure TMainForm.ActionSelectHighlighterExecute(Sender: TObject); begin with Editor do begin Highlighter.LoadFromFile(Format('%s.json', [TAction(Sender).Caption])); Lines.Text := Highlighter.Info.General.Sample; CaretZero; SetFocus; end; StatusBar.Panels[3].Text := ''; TitleBar.Items[2].Caption := TAction(Sender).Caption; Caption := BCEDITORDEMO_CAPTION; SearchFrame.ClearText; end; procedure TMainForm.ActionSkinsExecute(Sender: TObject); begin inherited; TSkinSelectDialog.ClassShowModal(SkinManager); end; procedure TMainForm.ActionSelectHighlighterColorExecute(Sender: TObject); begin Editor.Highlighter.Colors.LoadFromFile(Format('%s.json', [TAction(Sender).Caption])); TitleBar.Items[4].Caption := TAction(Sender).Caption; Editor.SetFocus; end; procedure TMainForm.ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); var InfoText: string; KeyState: TKeyboardState; begin SearchFrame.Visible := Editor.Search.Enabled; if SearchFrame.Visible then Editor.Margins.Bottom := 0 else Editor.Margins.Bottom := 5; if Editor.Modified then InfoText := LanguageDataModule.GetConstant('Modified') else InfoText := ''; if StatusBar.Panels[2].Text <> InfoText then StatusBar.Panels[2].Text := InfoText; GetKeyboardState(KeyState); if KeyState[VK_INSERT] = 0 then if StatusBar.Panels[1].Text <> LanguageDataModule.GetConstant('Insert') then StatusBar.Panels[1].Text := LanguageDataModule.GetConstant('Insert'); if KeyState[VK_INSERT] = 1 then if StatusBar.Panels[1].Text <> LanguageDataModule.GetConstant('Overwrite') then StatusBar.Panels[1].Text := LanguageDataModule.GetConstant('Overwrite'); end; procedure TMainForm.EditorCaretChanged(Sender: TObject; X, Y: Integer); var InfoText: string; begin inherited; InfoText := Format('%d: %d', [Y, X]); if StatusBar.Panels[0].Text <> InfoText then StatusBar.Panels[0].Text := InfoText; end; procedure TMainForm.InitializeEditorPrint(EditorPrint: TBCEditorPrint); var Alignment: TAlignment; procedure SetHeaderFooter(Option: Integer; Value: string); begin case Option of 0, 1: with EditorPrint.Footer do begin case Option of 0: Alignment := taLeftJustify; 1: Alignment := taRightJustify; end; Add(Value, nil, Alignment, 1); end; 2, 3: with EditorPrint.Header do begin case Option of 2: Alignment := taLeftJustify; 3: Alignment := taRightJustify; end; Add(Value, nil, Alignment, 1); end; end; end; begin EditorPrint.Header.Clear; EditorPrint.Footer.Clear; SetHeaderFooter(0, Format(LanguageDataModule.GetConstant('PrintedBy'), [Application.Title])); SetHeaderFooter(1, LanguageDataModule.GetConstant('PreviewDocumentPage')); SetHeaderFooter(2, Editor.DocumentName); SetHeaderFooter(3, '$DATE$ $TIME$'); EditorPrint.Header.FrameTypes := [ftLine]; EditorPrint.Footer.FrameTypes := [ftLine]; EditorPrint.LineNumbersInMargin := True; EditorPrint.LineNumbers := True; EditorPrint.Wrap := False; EditorPrint.Colors := True; EditorPrint.Editor := Editor; EditorPrint.Title := Editor.DocumentName; end; procedure TMainForm.ActionPreviewExecute(Sender: TObject); begin PrintPreview end; procedure TMainForm.PrintPreview; begin with PrintPreviewDialog do begin InitializeEditorPrint(PrintPreview.EditorPrint); ShowModal; end; end; procedure TMainForm.ActionFileOpenExecute(Sender: TObject); var i: Integer; FileName, Ext, ItemString, Token: string; begin OpenDialog.Title := 'Open'; if OpenDialog.Execute(Handle) then begin FStopWatch.Reset; FStopWatch.Start; FileName := OpenDialog.Files[0]; Ext := LowerCase(ExtractFileExt(FileName)); for i := 0 to MultiStringHolderFileTypes.MultipleStrings.Count - 1 do begin ItemString := MultiStringHolderFileTypes.MultipleStrings.Items[i].Strings.Text; while ItemString <> '' do begin Token := GetNextToken(';', ItemString); ItemString := RemoveTokenFromStart(';', ItemString); if Ext = Token then begin PopupMenuHighlighters.Items.Find(MultiStringHolderFileTypes.MultipleStrings.Items[i].Name).Action.Execute; Break; end; end; end; TitleBar.Items[1].Caption := Format('%s - %s', [BCEDITORDEMO_CAPTION, FileName]); Editor.LoadFromFile(FileName); FStopWatch.Stop; StatusBar.Panels[3].Text := 'Load: ' + FormatDateTime('s.zzz "s"', FStopWatch.ElapsedMilliseconds / MSecsPerDay); end; end; procedure TMainForm.FormCreate(Sender: TObject); begin inherited; { IDE can lose these properties } SearchFrame.SpeedButtonFindPrevious.Images := ImagesDataModule.ImageListSmall; SearchFrame.SpeedButtonFindNext.Images := ImagesDataModule.ImageListSmall; SearchFrame.SpeedButtonOptions.Images := ImagesDataModule.ImageListSmall; PopupMenuFile.Images := ImagesDataModule.ImageList; TitleBar.Images := ImagesDataModule.ImageListSmall; end; procedure TMainForm.FormShow(Sender: TObject); begin ObjectInspectorEh.Component := Editor; ObjectInspectorEh.LabelColWidth := 145; SearchFrame.Editor := Editor; SetHighlighters; SetHighlighterColors; end; procedure TMainForm.SetHighlighters; var FindFileHandle: THandle; Win32FindData: TWin32FindData; FileName: string; LMenuItem: TMenuItem; LAction: TAction; begin PopupMenuHighlighters.Items.Clear; {$WARNINGS OFF} FindFileHandle := FindFirstFile(PChar(IncludeTrailingBackSlash(ExtractFilePath(Application.ExeName)) + 'Highlighters\*.json'), Win32FindData); {$WARNINGS ON} if FindFileHandle <> INVALID_HANDLE_VALUE then try // i := 1; repeat FileName := ExtractFileName(StrPas(Win32FindData.cFileName)); FileName := Copy(FileName, 1, Pos('.', FileName) - 1); LAction := TAction.Create(Self); LAction.Caption := FileName; LAction.OnExecute := ActionSelectHighlighterExecute; LMenuItem := TMenuItem.Create(PopupMenuHighlighters); LMenuItem.Action := LAction; LMenuItem.RadioItem := True; LMenuItem.AutoCheck := True; PopupMenuHighlighters.Items.Add(LMenuItem); if LAction.Caption = 'Object Pascal' then begin LAction.Checked := True; LAction.Execute; end; until not FindNextFile(FindFileHandle, Win32FindData); finally Winapi.Windows.FindClose(FindFileHandle); end; end; procedure TMainForm.SetHighlighterColors; var FindFileHandle: THandle; Win32FindData: TWin32FindData; FileName: string; LMenuItem: TMenuItem; LAction: TAction; begin PopupMenuColors.Items.Clear; {$WARNINGS OFF} FindFileHandle := FindFirstFile(PChar(IncludeTrailingBackSlash(ExtractFilePath(Application.ExeName)) + 'Colors\*.json'), Win32FindData); {$WARNINGS ON} if FindFileHandle <> INVALID_HANDLE_VALUE then try repeat FileName := ExtractFileName(StrPas(Win32FindData.cFileName)); FileName := Copy(FileName, 1, Pos('.', FileName) - 1); LAction := TAction.Create(Self); LAction.Caption := FileName; LAction.OnExecute := ActionSelectHighlighterColorExecute; LMenuItem := TMenuItem.Create(PopupMenuColors); LMenuItem.Action := LAction; LMenuItem.RadioItem := True; LMenuItem.AutoCheck := True; PopupMenuColors.Items.Add(LMenuItem); if LAction.Caption = 'Default' then begin LAction.Checked := True; LAction.Execute; end; until not FindNextFile(FindFileHandle, Win32FindData); finally Winapi.Windows.FindClose(FindFileHandle); end; end; procedure TMainForm.SkinManagerGetMenuExtraLineData(FirstItem: TMenuItem; var SkinSection, Caption: string; var Glyph: TBitmap; var LineVisible: Boolean); begin inherited; if FirstItem = PopupMenuHighlighters.Items[0] then begin LineVisible := True; Caption := 'Highlighter'; end else if FirstItem = PopupMenuColors.Items[0] then begin LineVisible := True; Caption := 'Color'; end else LineVisible := False; end; procedure TMainForm.ActionSearchExecute(Sender: TObject); begin Editor.Search.Enabled := True; Application.ProcessMessages; { search frame visible } SearchFrame.ComboBoxSearchText.SetFocus; end; end.
unit Params_3; interface implementation procedure P1(var A, B, C: Int32); begin A := A + 1; B := B + 2; C := A + B; end; var GA, GB, GC: Int32; procedure Test; begin GA, GB := 0; P1(GA, GB, GC); end; initialization Test(); finalization Assert(GA = 1); Assert(GB = 2); Assert(GC = 3); end.
unit ScalingUtils; interface uses {$IFDEF FPC} Forms {$ELSE} Vcl.Forms {$ENDIF}; type TDzFormScaling = class private FScaled: Boolean; FDesignerPPI: Integer; FMonitorPPI: Integer; public property Scaled: Boolean read FScaled; property DesignerPPI: Integer read FDesignerPPI; property MonitorPPI: Integer read FMonitorPPI; procedure Update(F: TCustomForm; xDesignerDPI: Integer); function Calc(Value: Integer): Integer; end; function RetrieveDesignerPPI(F: TCustomForm): Integer; function RetrieveMonitorPPI(F: TCustomForm): Integer; implementation uses {$IFDEF FPC} SysUtils, Windows {$ELSE} System.SysUtils, Winapi.Windows, Winapi.MultiMon {$ENDIF}; type TMonitorDpiType = ( MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI ); {$WARN SYMBOL_PLATFORM OFF} function GetDpiForMonitor( hmonitor: HMONITOR; dpiType: TMonitorDpiType; out dpiX: UINT; out dpiY: UINT ): HRESULT; stdcall; external 'Shcore.dll' {$IFDEF DCC}delayed{$ENDIF}; {$WARN SYMBOL_PLATFORM ON} function RetrieveMonitorPPI(F: TCustomForm): Integer; var Ydpi: Cardinal; Xdpi: Cardinal; DC: HDC; begin if CheckWin32Version(6,3) then begin if GetDpiForMonitor(F.Monitor.Handle, TMonitorDpiType.MDT_EFFECTIVE_DPI, Ydpi, Xdpi) = S_OK then Result := Ydpi else Result := 0; end else begin DC := GetDC(0); Result := GetDeviceCaps(DC, LOGPIXELSY); ReleaseDC(0, DC); end; end; // type TFormScaleHack = class(TCustomForm); function RetrieveDesignerPPI(F: TCustomForm): Integer; begin Result := {$IFDEF FPC} F.PixelsPerInch {$ELSE} {$IF CompilerVersion >= 31} //D10.1 Berlin TFormScaleHack(F).GetDesignDpi {$ELSE} TFormScaleHack(F).PixelsPerInch {$ENDIF} {$ENDIF}; end; procedure TDzFormScaling.Update(F: TCustomForm; xDesignerDPI: Integer); begin if F<>nil then begin FScaled := TFormScaleHack(F).Scaled; FDesignerPPI := xDesignerDPI; //Delphi 11 is not storing original design DPI (it changes by current monitor PPI) FMonitorPPI := RetrieveMonitorPPI(F); end else begin FScaled := False; FDesignerPPI := 0; FMonitorPPI := 0; end; end; function TDzFormScaling.Calc(Value: Integer): Integer; begin if FScaled then Result := MulDiv(Value, FMonitorPPI, FDesignerPPI) //{$IFDEF FPC}ScaleDesignToForm(Value){$ELSE}ScaleValue(Value){$ENDIF} - only supported in Delphi 10.4 (Monitor.PixelsPerInch supported too) else Result := Value; end; end.
{ ****************************************************************************** } { Fast KDTree SmallInt 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 FastKDTreeI16; {$INCLUDE zDefine.inc} interface uses CoreClasses, PascalStrings, UnicodeMixedLib, KM; const // SmallInt KDTree KDT1DI16_Axis = 1; KDT2DI16_Axis = 2; KDT3DI16_Axis = 3; KDT4DI16_Axis = 4; KDT5DI16_Axis = 5; KDT6DI16_Axis = 6; KDT7DI16_Axis = 7; KDT8DI16_Axis = 8; KDT9DI16_Axis = 9; KDT10DI16_Axis = 10; KDT11DI16_Axis = 11; KDT12DI16_Axis = 12; KDT13DI16_Axis = 13; KDT14DI16_Axis = 14; KDT15DI16_Axis = 15; KDT16DI16_Axis = 16; KDT17DI16_Axis = 17; KDT18DI16_Axis = 18; KDT19DI16_Axis = 19; KDT20DI16_Axis = 20; KDT21DI16_Axis = 21; KDT22DI16_Axis = 22; KDT23DI16_Axis = 23; KDT24DI16_Axis = 24; KDT48DI16_Axis = 48; KDT52DI16_Axis = 52; KDT64DI16_Axis = 64; KDT96DI16_Axis = 96; KDT128DI16_Axis = 128; KDT156DI16_Axis = 156; KDT192DI16_Axis = 192; KDT256DI16_Axis = 256; KDT384DI16_Axis = 384; KDT512DI16_Axis = 512; KDT800DI16_Axis = 800; KDT1024DI16_Axis = 1024; type // SmallInt: KDTree TKDT1DI16 = class; TKDT1DI16_VecType = KM.TKMFloat; // 1D TKDT2DI16 = class; TKDT2DI16_VecType = KM.TKMFloat; // 2D TKDT3DI16 = class; TKDT3DI16_VecType = KM.TKMFloat; // 3D TKDT4DI16 = class; TKDT4DI16_VecType = KM.TKMFloat; // 4D TKDT5DI16 = class; TKDT5DI16_VecType = KM.TKMFloat; // 5D TKDT6DI16 = class; TKDT6DI16_VecType = KM.TKMFloat; // 6D TKDT7DI16 = class; TKDT7DI16_VecType = KM.TKMFloat; // 7D TKDT8DI16 = class; TKDT8DI16_VecType = KM.TKMFloat; // 8D TKDT9DI16 = class; TKDT9DI16_VecType = KM.TKMFloat; // 9D TKDT10DI16 = class; TKDT10DI16_VecType = KM.TKMFloat; // 10D TKDT11DI16 = class; TKDT11DI16_VecType = KM.TKMFloat; // 11D TKDT12DI16 = class; TKDT12DI16_VecType = KM.TKMFloat; // 12D TKDT13DI16 = class; TKDT13DI16_VecType = KM.TKMFloat; // 13D TKDT14DI16 = class; TKDT14DI16_VecType = KM.TKMFloat; // 14D TKDT15DI16 = class; TKDT15DI16_VecType = KM.TKMFloat; // 15D TKDT16DI16 = class; TKDT16DI16_VecType = KM.TKMFloat; // 16D TKDT17DI16 = class; TKDT17DI16_VecType = KM.TKMFloat; // 17D TKDT18DI16 = class; TKDT18DI16_VecType = KM.TKMFloat; // 18D TKDT19DI16 = class; TKDT19DI16_VecType = KM.TKMFloat; // 19D TKDT20DI16 = class; TKDT20DI16_VecType = KM.TKMFloat; // 20D TKDT21DI16 = class; TKDT21DI16_VecType = KM.TKMFloat; // 21D TKDT22DI16 = class; TKDT22DI16_VecType = KM.TKMFloat; // 22D TKDT23DI16 = class; TKDT23DI16_VecType = KM.TKMFloat; // 23D TKDT24DI16 = class; TKDT24DI16_VecType = KM.TKMFloat; // 24D TKDT48DI16 = class; TKDT48DI16_VecType = KM.TKMFloat; // 48D TKDT52DI16 = class; TKDT52DI16_VecType = KM.TKMFloat; // 52D TKDT64DI16 = class; TKDT64DI16_VecType = KM.TKMFloat; // 64D TKDT96DI16 = class; TKDT96DI16_VecType = KM.TKMFloat; // 96D TKDT128DI16 = class; TKDT128DI16_VecType = KM.TKMFloat; // 128D TKDT156DI16 = class; TKDT156DI16_VecType = KM.TKMFloat; // 156D TKDT192DI16 = class; TKDT192DI16_VecType = KM.TKMFloat; // 192D TKDT256DI16 = class; TKDT256DI16_VecType = KM.TKMFloat; // 256D TKDT384DI16 = class; TKDT384DI16_VecType = KM.TKMFloat; // 384D TKDT512DI16 = class; TKDT512DI16_VecType = KM.TKMFloat; // 512D TKDT800DI16 = class; TKDT800DI16_VecType = KM.TKMFloat; // 800D TKDT1024DI16 = class; TKDT1024DI16_VecType = KM.TKMFloat; // 1024D // SmallInt KDTree TKDT1DI16 = class(TCoreClassObject) public type // code split TKDT1DI16_Vec = array [0 .. KDT1DI16_Axis - 1] of TKDT1DI16_VecType; PKDT1DI16_Vec = ^TKDT1DI16_Vec; TKDT1DI16_DynamicVecBuffer = array of TKDT1DI16_Vec; PKDT1DI16_DynamicVecBuffer = ^TKDT1DI16_DynamicVecBuffer; TKDT1DI16_Source = record buff: TKDT1DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT1DI16_Source = ^TKDT1DI16_Source; TKDT1DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1DI16_Source) - 1] of PKDT1DI16_Source; PKDT1DI16_SourceBuffer = ^TKDT1DI16_SourceBuffer; TKDT1DI16_DyanmicSourceBuffer = array of PKDT1DI16_Source; PKDT1DI16_DyanmicSourceBuffer = ^TKDT1DI16_DyanmicSourceBuffer; TKDT1DI16_DyanmicStoreBuffer = array of TKDT1DI16_Source; PKDT1DI16_DyanmicStoreBuffer = ^TKDT1DI16_DyanmicStoreBuffer; PKDT1DI16_Node = ^TKDT1DI16_Node; TKDT1DI16_Node = record Parent, Right, Left: PKDT1DI16_Node; Vec: PKDT1DI16_Source; end; TKDT1DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer); TKDT1DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT1DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT1DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT1DI16_DyanmicStoreBuffer; KDBuff: TKDT1DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT1DI16_Node; TestBuff: TKDT1DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DI16_Node; function GetData(const Index: NativeInt): PKDT1DI16_Source; public RootNode: PKDT1DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT1DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT1DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT1DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT1DI16_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: TKDT1DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildProc); overload; { search } function Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DI16_Node; overload; function Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DI16_Node; overload; function Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double): PKDT1DI16_Node; overload; function Search(const buff: TKDT1DI16_Vec): PKDT1DI16_Node; overload; function SearchToken(const buff: TKDT1DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT1DI16_DynamicVecBuffer; var OutBuff: TKDT1DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT1DI16_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: PKDT1DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT1DI16_Vec; overload; class function Vec(const v: TKDT1DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT1DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer); class procedure Test; end; TKDT2DI16 = class(TCoreClassObject) public type // code split TKDT2DI16_Vec = array [0 .. KDT2DI16_Axis - 1] of TKDT2DI16_VecType; PKDT2DI16_Vec = ^TKDT2DI16_Vec; TKDT2DI16_DynamicVecBuffer = array of TKDT2DI16_Vec; PKDT2DI16_DynamicVecBuffer = ^TKDT2DI16_DynamicVecBuffer; TKDT2DI16_Source = record buff: TKDT2DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT2DI16_Source = ^TKDT2DI16_Source; TKDT2DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT2DI16_Source) - 1] of PKDT2DI16_Source; PKDT2DI16_SourceBuffer = ^TKDT2DI16_SourceBuffer; TKDT2DI16_DyanmicSourceBuffer = array of PKDT2DI16_Source; PKDT2DI16_DyanmicSourceBuffer = ^TKDT2DI16_DyanmicSourceBuffer; TKDT2DI16_DyanmicStoreBuffer = array of TKDT2DI16_Source; PKDT2DI16_DyanmicStoreBuffer = ^TKDT2DI16_DyanmicStoreBuffer; PKDT2DI16_Node = ^TKDT2DI16_Node; TKDT2DI16_Node = record Parent, Right, Left: PKDT2DI16_Node; Vec: PKDT2DI16_Source; end; TKDT2DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer); TKDT2DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT2DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT2DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT2DI16_DyanmicStoreBuffer; KDBuff: TKDT2DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT2DI16_Node; TestBuff: TKDT2DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DI16_Node; function GetData(const Index: NativeInt): PKDT2DI16_Source; public RootNode: PKDT2DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT2DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT2DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT2DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT2DI16_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: TKDT2DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildProc); overload; { search } function Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DI16_Node; overload; function Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DI16_Node; overload; function Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double): PKDT2DI16_Node; overload; function Search(const buff: TKDT2DI16_Vec): PKDT2DI16_Node; overload; function SearchToken(const buff: TKDT2DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT2DI16_DynamicVecBuffer; var OutBuff: TKDT2DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT2DI16_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: PKDT2DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT2DI16_Vec; overload; class function Vec(const v: TKDT2DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT2DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer); class procedure Test; end; TKDT3DI16 = class(TCoreClassObject) public type // code split TKDT3DI16_Vec = array [0 .. KDT3DI16_Axis - 1] of TKDT3DI16_VecType; PKDT3DI16_Vec = ^TKDT3DI16_Vec; TKDT3DI16_DynamicVecBuffer = array of TKDT3DI16_Vec; PKDT3DI16_DynamicVecBuffer = ^TKDT3DI16_DynamicVecBuffer; TKDT3DI16_Source = record buff: TKDT3DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT3DI16_Source = ^TKDT3DI16_Source; TKDT3DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT3DI16_Source) - 1] of PKDT3DI16_Source; PKDT3DI16_SourceBuffer = ^TKDT3DI16_SourceBuffer; TKDT3DI16_DyanmicSourceBuffer = array of PKDT3DI16_Source; PKDT3DI16_DyanmicSourceBuffer = ^TKDT3DI16_DyanmicSourceBuffer; TKDT3DI16_DyanmicStoreBuffer = array of TKDT3DI16_Source; PKDT3DI16_DyanmicStoreBuffer = ^TKDT3DI16_DyanmicStoreBuffer; PKDT3DI16_Node = ^TKDT3DI16_Node; TKDT3DI16_Node = record Parent, Right, Left: PKDT3DI16_Node; Vec: PKDT3DI16_Source; end; TKDT3DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer); TKDT3DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT3DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT3DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT3DI16_DyanmicStoreBuffer; KDBuff: TKDT3DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT3DI16_Node; TestBuff: TKDT3DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DI16_Node; function GetData(const Index: NativeInt): PKDT3DI16_Source; public RootNode: PKDT3DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT3DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT3DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT3DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT3DI16_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: TKDT3DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildProc); overload; { search } function Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DI16_Node; overload; function Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DI16_Node; overload; function Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double): PKDT3DI16_Node; overload; function Search(const buff: TKDT3DI16_Vec): PKDT3DI16_Node; overload; function SearchToken(const buff: TKDT3DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT3DI16_DynamicVecBuffer; var OutBuff: TKDT3DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT3DI16_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: PKDT3DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT3DI16_Vec; overload; class function Vec(const v: TKDT3DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT3DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer); class procedure Test; end; TKDT4DI16 = class(TCoreClassObject) public type // code split TKDT4DI16_Vec = array [0 .. KDT4DI16_Axis - 1] of TKDT4DI16_VecType; PKDT4DI16_Vec = ^TKDT4DI16_Vec; TKDT4DI16_DynamicVecBuffer = array of TKDT4DI16_Vec; PKDT4DI16_DynamicVecBuffer = ^TKDT4DI16_DynamicVecBuffer; TKDT4DI16_Source = record buff: TKDT4DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT4DI16_Source = ^TKDT4DI16_Source; TKDT4DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT4DI16_Source) - 1] of PKDT4DI16_Source; PKDT4DI16_SourceBuffer = ^TKDT4DI16_SourceBuffer; TKDT4DI16_DyanmicSourceBuffer = array of PKDT4DI16_Source; PKDT4DI16_DyanmicSourceBuffer = ^TKDT4DI16_DyanmicSourceBuffer; TKDT4DI16_DyanmicStoreBuffer = array of TKDT4DI16_Source; PKDT4DI16_DyanmicStoreBuffer = ^TKDT4DI16_DyanmicStoreBuffer; PKDT4DI16_Node = ^TKDT4DI16_Node; TKDT4DI16_Node = record Parent, Right, Left: PKDT4DI16_Node; Vec: PKDT4DI16_Source; end; TKDT4DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer); TKDT4DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT4DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT4DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT4DI16_DyanmicStoreBuffer; KDBuff: TKDT4DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT4DI16_Node; TestBuff: TKDT4DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DI16_Node; function GetData(const Index: NativeInt): PKDT4DI16_Source; public RootNode: PKDT4DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT4DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT4DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT4DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT4DI16_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: TKDT4DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildProc); overload; { search } function Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DI16_Node; overload; function Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DI16_Node; overload; function Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double): PKDT4DI16_Node; overload; function Search(const buff: TKDT4DI16_Vec): PKDT4DI16_Node; overload; function SearchToken(const buff: TKDT4DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT4DI16_DynamicVecBuffer; var OutBuff: TKDT4DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT4DI16_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: PKDT4DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT4DI16_Vec; overload; class function Vec(const v: TKDT4DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT4DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer); class procedure Test; end; TKDT5DI16 = class(TCoreClassObject) public type // code split TKDT5DI16_Vec = array [0 .. KDT5DI16_Axis - 1] of TKDT5DI16_VecType; PKDT5DI16_Vec = ^TKDT5DI16_Vec; TKDT5DI16_DynamicVecBuffer = array of TKDT5DI16_Vec; PKDT5DI16_DynamicVecBuffer = ^TKDT5DI16_DynamicVecBuffer; TKDT5DI16_Source = record buff: TKDT5DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT5DI16_Source = ^TKDT5DI16_Source; TKDT5DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT5DI16_Source) - 1] of PKDT5DI16_Source; PKDT5DI16_SourceBuffer = ^TKDT5DI16_SourceBuffer; TKDT5DI16_DyanmicSourceBuffer = array of PKDT5DI16_Source; PKDT5DI16_DyanmicSourceBuffer = ^TKDT5DI16_DyanmicSourceBuffer; TKDT5DI16_DyanmicStoreBuffer = array of TKDT5DI16_Source; PKDT5DI16_DyanmicStoreBuffer = ^TKDT5DI16_DyanmicStoreBuffer; PKDT5DI16_Node = ^TKDT5DI16_Node; TKDT5DI16_Node = record Parent, Right, Left: PKDT5DI16_Node; Vec: PKDT5DI16_Source; end; TKDT5DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer); TKDT5DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT5DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT5DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT5DI16_DyanmicStoreBuffer; KDBuff: TKDT5DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT5DI16_Node; TestBuff: TKDT5DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DI16_Node; function GetData(const Index: NativeInt): PKDT5DI16_Source; public RootNode: PKDT5DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT5DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT5DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT5DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT5DI16_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: TKDT5DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildProc); overload; { search } function Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DI16_Node; overload; function Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DI16_Node; overload; function Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double): PKDT5DI16_Node; overload; function Search(const buff: TKDT5DI16_Vec): PKDT5DI16_Node; overload; function SearchToken(const buff: TKDT5DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT5DI16_DynamicVecBuffer; var OutBuff: TKDT5DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT5DI16_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: PKDT5DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT5DI16_Vec; overload; class function Vec(const v: TKDT5DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT5DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer); class procedure Test; end; TKDT6DI16 = class(TCoreClassObject) public type // code split TKDT6DI16_Vec = array [0 .. KDT6DI16_Axis - 1] of TKDT6DI16_VecType; PKDT6DI16_Vec = ^TKDT6DI16_Vec; TKDT6DI16_DynamicVecBuffer = array of TKDT6DI16_Vec; PKDT6DI16_DynamicVecBuffer = ^TKDT6DI16_DynamicVecBuffer; TKDT6DI16_Source = record buff: TKDT6DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT6DI16_Source = ^TKDT6DI16_Source; TKDT6DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT6DI16_Source) - 1] of PKDT6DI16_Source; PKDT6DI16_SourceBuffer = ^TKDT6DI16_SourceBuffer; TKDT6DI16_DyanmicSourceBuffer = array of PKDT6DI16_Source; PKDT6DI16_DyanmicSourceBuffer = ^TKDT6DI16_DyanmicSourceBuffer; TKDT6DI16_DyanmicStoreBuffer = array of TKDT6DI16_Source; PKDT6DI16_DyanmicStoreBuffer = ^TKDT6DI16_DyanmicStoreBuffer; PKDT6DI16_Node = ^TKDT6DI16_Node; TKDT6DI16_Node = record Parent, Right, Left: PKDT6DI16_Node; Vec: PKDT6DI16_Source; end; TKDT6DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer); TKDT6DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT6DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT6DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT6DI16_DyanmicStoreBuffer; KDBuff: TKDT6DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT6DI16_Node; TestBuff: TKDT6DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DI16_Node; function GetData(const Index: NativeInt): PKDT6DI16_Source; public RootNode: PKDT6DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT6DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT6DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT6DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT6DI16_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: TKDT6DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildProc); overload; { search } function Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DI16_Node; overload; function Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DI16_Node; overload; function Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double): PKDT6DI16_Node; overload; function Search(const buff: TKDT6DI16_Vec): PKDT6DI16_Node; overload; function SearchToken(const buff: TKDT6DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT6DI16_DynamicVecBuffer; var OutBuff: TKDT6DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT6DI16_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: PKDT6DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT6DI16_Vec; overload; class function Vec(const v: TKDT6DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT6DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer); class procedure Test; end; TKDT7DI16 = class(TCoreClassObject) public type // code split TKDT7DI16_Vec = array [0 .. KDT7DI16_Axis - 1] of TKDT7DI16_VecType; PKDT7DI16_Vec = ^TKDT7DI16_Vec; TKDT7DI16_DynamicVecBuffer = array of TKDT7DI16_Vec; PKDT7DI16_DynamicVecBuffer = ^TKDT7DI16_DynamicVecBuffer; TKDT7DI16_Source = record buff: TKDT7DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT7DI16_Source = ^TKDT7DI16_Source; TKDT7DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT7DI16_Source) - 1] of PKDT7DI16_Source; PKDT7DI16_SourceBuffer = ^TKDT7DI16_SourceBuffer; TKDT7DI16_DyanmicSourceBuffer = array of PKDT7DI16_Source; PKDT7DI16_DyanmicSourceBuffer = ^TKDT7DI16_DyanmicSourceBuffer; TKDT7DI16_DyanmicStoreBuffer = array of TKDT7DI16_Source; PKDT7DI16_DyanmicStoreBuffer = ^TKDT7DI16_DyanmicStoreBuffer; PKDT7DI16_Node = ^TKDT7DI16_Node; TKDT7DI16_Node = record Parent, Right, Left: PKDT7DI16_Node; Vec: PKDT7DI16_Source; end; TKDT7DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer); TKDT7DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT7DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT7DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT7DI16_DyanmicStoreBuffer; KDBuff: TKDT7DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT7DI16_Node; TestBuff: TKDT7DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DI16_Node; function GetData(const Index: NativeInt): PKDT7DI16_Source; public RootNode: PKDT7DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT7DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT7DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT7DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT7DI16_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: TKDT7DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildProc); overload; { search } function Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DI16_Node; overload; function Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DI16_Node; overload; function Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double): PKDT7DI16_Node; overload; function Search(const buff: TKDT7DI16_Vec): PKDT7DI16_Node; overload; function SearchToken(const buff: TKDT7DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT7DI16_DynamicVecBuffer; var OutBuff: TKDT7DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT7DI16_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: PKDT7DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT7DI16_Vec; overload; class function Vec(const v: TKDT7DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT7DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer); class procedure Test; end; TKDT8DI16 = class(TCoreClassObject) public type // code split TKDT8DI16_Vec = array [0 .. KDT8DI16_Axis - 1] of TKDT8DI16_VecType; PKDT8DI16_Vec = ^TKDT8DI16_Vec; TKDT8DI16_DynamicVecBuffer = array of TKDT8DI16_Vec; PKDT8DI16_DynamicVecBuffer = ^TKDT8DI16_DynamicVecBuffer; TKDT8DI16_Source = record buff: TKDT8DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT8DI16_Source = ^TKDT8DI16_Source; TKDT8DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT8DI16_Source) - 1] of PKDT8DI16_Source; PKDT8DI16_SourceBuffer = ^TKDT8DI16_SourceBuffer; TKDT8DI16_DyanmicSourceBuffer = array of PKDT8DI16_Source; PKDT8DI16_DyanmicSourceBuffer = ^TKDT8DI16_DyanmicSourceBuffer; TKDT8DI16_DyanmicStoreBuffer = array of TKDT8DI16_Source; PKDT8DI16_DyanmicStoreBuffer = ^TKDT8DI16_DyanmicStoreBuffer; PKDT8DI16_Node = ^TKDT8DI16_Node; TKDT8DI16_Node = record Parent, Right, Left: PKDT8DI16_Node; Vec: PKDT8DI16_Source; end; TKDT8DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer); TKDT8DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT8DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT8DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT8DI16_DyanmicStoreBuffer; KDBuff: TKDT8DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT8DI16_Node; TestBuff: TKDT8DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DI16_Node; function GetData(const Index: NativeInt): PKDT8DI16_Source; public RootNode: PKDT8DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT8DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT8DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT8DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT8DI16_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: TKDT8DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildProc); overload; { search } function Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DI16_Node; overload; function Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DI16_Node; overload; function Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double): PKDT8DI16_Node; overload; function Search(const buff: TKDT8DI16_Vec): PKDT8DI16_Node; overload; function SearchToken(const buff: TKDT8DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT8DI16_DynamicVecBuffer; var OutBuff: TKDT8DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT8DI16_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: PKDT8DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT8DI16_Vec; overload; class function Vec(const v: TKDT8DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT8DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer); class procedure Test; end; TKDT9DI16 = class(TCoreClassObject) public type // code split TKDT9DI16_Vec = array [0 .. KDT9DI16_Axis - 1] of TKDT9DI16_VecType; PKDT9DI16_Vec = ^TKDT9DI16_Vec; TKDT9DI16_DynamicVecBuffer = array of TKDT9DI16_Vec; PKDT9DI16_DynamicVecBuffer = ^TKDT9DI16_DynamicVecBuffer; TKDT9DI16_Source = record buff: TKDT9DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT9DI16_Source = ^TKDT9DI16_Source; TKDT9DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT9DI16_Source) - 1] of PKDT9DI16_Source; PKDT9DI16_SourceBuffer = ^TKDT9DI16_SourceBuffer; TKDT9DI16_DyanmicSourceBuffer = array of PKDT9DI16_Source; PKDT9DI16_DyanmicSourceBuffer = ^TKDT9DI16_DyanmicSourceBuffer; TKDT9DI16_DyanmicStoreBuffer = array of TKDT9DI16_Source; PKDT9DI16_DyanmicStoreBuffer = ^TKDT9DI16_DyanmicStoreBuffer; PKDT9DI16_Node = ^TKDT9DI16_Node; TKDT9DI16_Node = record Parent, Right, Left: PKDT9DI16_Node; Vec: PKDT9DI16_Source; end; TKDT9DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer); TKDT9DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT9DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT9DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT9DI16_DyanmicStoreBuffer; KDBuff: TKDT9DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT9DI16_Node; TestBuff: TKDT9DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DI16_Node; function GetData(const Index: NativeInt): PKDT9DI16_Source; public RootNode: PKDT9DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT9DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT9DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT9DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT9DI16_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: TKDT9DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildProc); overload; { search } function Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DI16_Node; overload; function Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DI16_Node; overload; function Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double): PKDT9DI16_Node; overload; function Search(const buff: TKDT9DI16_Vec): PKDT9DI16_Node; overload; function SearchToken(const buff: TKDT9DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT9DI16_DynamicVecBuffer; var OutBuff: TKDT9DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT9DI16_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: PKDT9DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT9DI16_Vec; overload; class function Vec(const v: TKDT9DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT9DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer); class procedure Test; end; TKDT10DI16 = class(TCoreClassObject) public type // code split TKDT10DI16_Vec = array [0 .. KDT10DI16_Axis - 1] of TKDT10DI16_VecType; PKDT10DI16_Vec = ^TKDT10DI16_Vec; TKDT10DI16_DynamicVecBuffer = array of TKDT10DI16_Vec; PKDT10DI16_DynamicVecBuffer = ^TKDT10DI16_DynamicVecBuffer; TKDT10DI16_Source = record buff: TKDT10DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT10DI16_Source = ^TKDT10DI16_Source; TKDT10DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT10DI16_Source) - 1] of PKDT10DI16_Source; PKDT10DI16_SourceBuffer = ^TKDT10DI16_SourceBuffer; TKDT10DI16_DyanmicSourceBuffer = array of PKDT10DI16_Source; PKDT10DI16_DyanmicSourceBuffer = ^TKDT10DI16_DyanmicSourceBuffer; TKDT10DI16_DyanmicStoreBuffer = array of TKDT10DI16_Source; PKDT10DI16_DyanmicStoreBuffer = ^TKDT10DI16_DyanmicStoreBuffer; PKDT10DI16_Node = ^TKDT10DI16_Node; TKDT10DI16_Node = record Parent, Right, Left: PKDT10DI16_Node; Vec: PKDT10DI16_Source; end; TKDT10DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer); TKDT10DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT10DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT10DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT10DI16_DyanmicStoreBuffer; KDBuff: TKDT10DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT10DI16_Node; TestBuff: TKDT10DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DI16_Node; function GetData(const Index: NativeInt): PKDT10DI16_Source; public RootNode: PKDT10DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT10DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT10DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT10DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT10DI16_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: TKDT10DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildProc); overload; { search } function Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DI16_Node; overload; function Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DI16_Node; overload; function Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double): PKDT10DI16_Node; overload; function Search(const buff: TKDT10DI16_Vec): PKDT10DI16_Node; overload; function SearchToken(const buff: TKDT10DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT10DI16_DynamicVecBuffer; var OutBuff: TKDT10DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT10DI16_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: PKDT10DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT10DI16_Vec; overload; class function Vec(const v: TKDT10DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT10DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer); class procedure Test; end; TKDT11DI16 = class(TCoreClassObject) public type // code split TKDT11DI16_Vec = array [0 .. KDT11DI16_Axis - 1] of TKDT11DI16_VecType; PKDT11DI16_Vec = ^TKDT11DI16_Vec; TKDT11DI16_DynamicVecBuffer = array of TKDT11DI16_Vec; PKDT11DI16_DynamicVecBuffer = ^TKDT11DI16_DynamicVecBuffer; TKDT11DI16_Source = record buff: TKDT11DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT11DI16_Source = ^TKDT11DI16_Source; TKDT11DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT11DI16_Source) - 1] of PKDT11DI16_Source; PKDT11DI16_SourceBuffer = ^TKDT11DI16_SourceBuffer; TKDT11DI16_DyanmicSourceBuffer = array of PKDT11DI16_Source; PKDT11DI16_DyanmicSourceBuffer = ^TKDT11DI16_DyanmicSourceBuffer; TKDT11DI16_DyanmicStoreBuffer = array of TKDT11DI16_Source; PKDT11DI16_DyanmicStoreBuffer = ^TKDT11DI16_DyanmicStoreBuffer; PKDT11DI16_Node = ^TKDT11DI16_Node; TKDT11DI16_Node = record Parent, Right, Left: PKDT11DI16_Node; Vec: PKDT11DI16_Source; end; TKDT11DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer); TKDT11DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT11DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT11DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT11DI16_DyanmicStoreBuffer; KDBuff: TKDT11DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT11DI16_Node; TestBuff: TKDT11DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DI16_Node; function GetData(const Index: NativeInt): PKDT11DI16_Source; public RootNode: PKDT11DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT11DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT11DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT11DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT11DI16_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: TKDT11DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildProc); overload; { search } function Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DI16_Node; overload; function Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DI16_Node; overload; function Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double): PKDT11DI16_Node; overload; function Search(const buff: TKDT11DI16_Vec): PKDT11DI16_Node; overload; function SearchToken(const buff: TKDT11DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT11DI16_DynamicVecBuffer; var OutBuff: TKDT11DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT11DI16_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: PKDT11DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT11DI16_Vec; overload; class function Vec(const v: TKDT11DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT11DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer); class procedure Test; end; TKDT12DI16 = class(TCoreClassObject) public type // code split TKDT12DI16_Vec = array [0 .. KDT12DI16_Axis - 1] of TKDT12DI16_VecType; PKDT12DI16_Vec = ^TKDT12DI16_Vec; TKDT12DI16_DynamicVecBuffer = array of TKDT12DI16_Vec; PKDT12DI16_DynamicVecBuffer = ^TKDT12DI16_DynamicVecBuffer; TKDT12DI16_Source = record buff: TKDT12DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT12DI16_Source = ^TKDT12DI16_Source; TKDT12DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT12DI16_Source) - 1] of PKDT12DI16_Source; PKDT12DI16_SourceBuffer = ^TKDT12DI16_SourceBuffer; TKDT12DI16_DyanmicSourceBuffer = array of PKDT12DI16_Source; PKDT12DI16_DyanmicSourceBuffer = ^TKDT12DI16_DyanmicSourceBuffer; TKDT12DI16_DyanmicStoreBuffer = array of TKDT12DI16_Source; PKDT12DI16_DyanmicStoreBuffer = ^TKDT12DI16_DyanmicStoreBuffer; PKDT12DI16_Node = ^TKDT12DI16_Node; TKDT12DI16_Node = record Parent, Right, Left: PKDT12DI16_Node; Vec: PKDT12DI16_Source; end; TKDT12DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer); TKDT12DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT12DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT12DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT12DI16_DyanmicStoreBuffer; KDBuff: TKDT12DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT12DI16_Node; TestBuff: TKDT12DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DI16_Node; function GetData(const Index: NativeInt): PKDT12DI16_Source; public RootNode: PKDT12DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT12DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT12DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT12DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT12DI16_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: TKDT12DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildProc); overload; { search } function Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DI16_Node; overload; function Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DI16_Node; overload; function Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double): PKDT12DI16_Node; overload; function Search(const buff: TKDT12DI16_Vec): PKDT12DI16_Node; overload; function SearchToken(const buff: TKDT12DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT12DI16_DynamicVecBuffer; var OutBuff: TKDT12DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT12DI16_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: PKDT12DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT12DI16_Vec; overload; class function Vec(const v: TKDT12DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT12DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer); class procedure Test; end; TKDT13DI16 = class(TCoreClassObject) public type // code split TKDT13DI16_Vec = array [0 .. KDT13DI16_Axis - 1] of TKDT13DI16_VecType; PKDT13DI16_Vec = ^TKDT13DI16_Vec; TKDT13DI16_DynamicVecBuffer = array of TKDT13DI16_Vec; PKDT13DI16_DynamicVecBuffer = ^TKDT13DI16_DynamicVecBuffer; TKDT13DI16_Source = record buff: TKDT13DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT13DI16_Source = ^TKDT13DI16_Source; TKDT13DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT13DI16_Source) - 1] of PKDT13DI16_Source; PKDT13DI16_SourceBuffer = ^TKDT13DI16_SourceBuffer; TKDT13DI16_DyanmicSourceBuffer = array of PKDT13DI16_Source; PKDT13DI16_DyanmicSourceBuffer = ^TKDT13DI16_DyanmicSourceBuffer; TKDT13DI16_DyanmicStoreBuffer = array of TKDT13DI16_Source; PKDT13DI16_DyanmicStoreBuffer = ^TKDT13DI16_DyanmicStoreBuffer; PKDT13DI16_Node = ^TKDT13DI16_Node; TKDT13DI16_Node = record Parent, Right, Left: PKDT13DI16_Node; Vec: PKDT13DI16_Source; end; TKDT13DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer); TKDT13DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT13DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT13DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT13DI16_DyanmicStoreBuffer; KDBuff: TKDT13DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT13DI16_Node; TestBuff: TKDT13DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DI16_Node; function GetData(const Index: NativeInt): PKDT13DI16_Source; public RootNode: PKDT13DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT13DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT13DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT13DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT13DI16_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: TKDT13DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildProc); overload; { search } function Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DI16_Node; overload; function Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DI16_Node; overload; function Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double): PKDT13DI16_Node; overload; function Search(const buff: TKDT13DI16_Vec): PKDT13DI16_Node; overload; function SearchToken(const buff: TKDT13DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT13DI16_DynamicVecBuffer; var OutBuff: TKDT13DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT13DI16_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: PKDT13DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT13DI16_Vec; overload; class function Vec(const v: TKDT13DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT13DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer); class procedure Test; end; TKDT14DI16 = class(TCoreClassObject) public type // code split TKDT14DI16_Vec = array [0 .. KDT14DI16_Axis - 1] of TKDT14DI16_VecType; PKDT14DI16_Vec = ^TKDT14DI16_Vec; TKDT14DI16_DynamicVecBuffer = array of TKDT14DI16_Vec; PKDT14DI16_DynamicVecBuffer = ^TKDT14DI16_DynamicVecBuffer; TKDT14DI16_Source = record buff: TKDT14DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT14DI16_Source = ^TKDT14DI16_Source; TKDT14DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT14DI16_Source) - 1] of PKDT14DI16_Source; PKDT14DI16_SourceBuffer = ^TKDT14DI16_SourceBuffer; TKDT14DI16_DyanmicSourceBuffer = array of PKDT14DI16_Source; PKDT14DI16_DyanmicSourceBuffer = ^TKDT14DI16_DyanmicSourceBuffer; TKDT14DI16_DyanmicStoreBuffer = array of TKDT14DI16_Source; PKDT14DI16_DyanmicStoreBuffer = ^TKDT14DI16_DyanmicStoreBuffer; PKDT14DI16_Node = ^TKDT14DI16_Node; TKDT14DI16_Node = record Parent, Right, Left: PKDT14DI16_Node; Vec: PKDT14DI16_Source; end; TKDT14DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer); TKDT14DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT14DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT14DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT14DI16_DyanmicStoreBuffer; KDBuff: TKDT14DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT14DI16_Node; TestBuff: TKDT14DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DI16_Node; function GetData(const Index: NativeInt): PKDT14DI16_Source; public RootNode: PKDT14DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT14DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT14DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT14DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT14DI16_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: TKDT14DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildProc); overload; { search } function Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DI16_Node; overload; function Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DI16_Node; overload; function Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double): PKDT14DI16_Node; overload; function Search(const buff: TKDT14DI16_Vec): PKDT14DI16_Node; overload; function SearchToken(const buff: TKDT14DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT14DI16_DynamicVecBuffer; var OutBuff: TKDT14DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT14DI16_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: PKDT14DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT14DI16_Vec; overload; class function Vec(const v: TKDT14DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT14DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer); class procedure Test; end; TKDT15DI16 = class(TCoreClassObject) public type // code split TKDT15DI16_Vec = array [0 .. KDT15DI16_Axis - 1] of TKDT15DI16_VecType; PKDT15DI16_Vec = ^TKDT15DI16_Vec; TKDT15DI16_DynamicVecBuffer = array of TKDT15DI16_Vec; PKDT15DI16_DynamicVecBuffer = ^TKDT15DI16_DynamicVecBuffer; TKDT15DI16_Source = record buff: TKDT15DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT15DI16_Source = ^TKDT15DI16_Source; TKDT15DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT15DI16_Source) - 1] of PKDT15DI16_Source; PKDT15DI16_SourceBuffer = ^TKDT15DI16_SourceBuffer; TKDT15DI16_DyanmicSourceBuffer = array of PKDT15DI16_Source; PKDT15DI16_DyanmicSourceBuffer = ^TKDT15DI16_DyanmicSourceBuffer; TKDT15DI16_DyanmicStoreBuffer = array of TKDT15DI16_Source; PKDT15DI16_DyanmicStoreBuffer = ^TKDT15DI16_DyanmicStoreBuffer; PKDT15DI16_Node = ^TKDT15DI16_Node; TKDT15DI16_Node = record Parent, Right, Left: PKDT15DI16_Node; Vec: PKDT15DI16_Source; end; TKDT15DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer); TKDT15DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT15DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT15DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT15DI16_DyanmicStoreBuffer; KDBuff: TKDT15DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT15DI16_Node; TestBuff: TKDT15DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DI16_Node; function GetData(const Index: NativeInt): PKDT15DI16_Source; public RootNode: PKDT15DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT15DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT15DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT15DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT15DI16_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: TKDT15DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildProc); overload; { search } function Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DI16_Node; overload; function Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DI16_Node; overload; function Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double): PKDT15DI16_Node; overload; function Search(const buff: TKDT15DI16_Vec): PKDT15DI16_Node; overload; function SearchToken(const buff: TKDT15DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT15DI16_DynamicVecBuffer; var OutBuff: TKDT15DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT15DI16_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: PKDT15DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT15DI16_Vec; overload; class function Vec(const v: TKDT15DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT15DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer); class procedure Test; end; TKDT16DI16 = class(TCoreClassObject) public type // code split TKDT16DI16_Vec = array [0 .. KDT16DI16_Axis - 1] of TKDT16DI16_VecType; PKDT16DI16_Vec = ^TKDT16DI16_Vec; TKDT16DI16_DynamicVecBuffer = array of TKDT16DI16_Vec; PKDT16DI16_DynamicVecBuffer = ^TKDT16DI16_DynamicVecBuffer; TKDT16DI16_Source = record buff: TKDT16DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT16DI16_Source = ^TKDT16DI16_Source; TKDT16DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT16DI16_Source) - 1] of PKDT16DI16_Source; PKDT16DI16_SourceBuffer = ^TKDT16DI16_SourceBuffer; TKDT16DI16_DyanmicSourceBuffer = array of PKDT16DI16_Source; PKDT16DI16_DyanmicSourceBuffer = ^TKDT16DI16_DyanmicSourceBuffer; TKDT16DI16_DyanmicStoreBuffer = array of TKDT16DI16_Source; PKDT16DI16_DyanmicStoreBuffer = ^TKDT16DI16_DyanmicStoreBuffer; PKDT16DI16_Node = ^TKDT16DI16_Node; TKDT16DI16_Node = record Parent, Right, Left: PKDT16DI16_Node; Vec: PKDT16DI16_Source; end; TKDT16DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer); TKDT16DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT16DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT16DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT16DI16_DyanmicStoreBuffer; KDBuff: TKDT16DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT16DI16_Node; TestBuff: TKDT16DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DI16_Node; function GetData(const Index: NativeInt): PKDT16DI16_Source; public RootNode: PKDT16DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT16DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT16DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT16DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT16DI16_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: TKDT16DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildProc); overload; { search } function Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DI16_Node; overload; function Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DI16_Node; overload; function Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double): PKDT16DI16_Node; overload; function Search(const buff: TKDT16DI16_Vec): PKDT16DI16_Node; overload; function SearchToken(const buff: TKDT16DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT16DI16_DynamicVecBuffer; var OutBuff: TKDT16DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT16DI16_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: PKDT16DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT16DI16_Vec; overload; class function Vec(const v: TKDT16DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT16DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer); class procedure Test; end; TKDT17DI16 = class(TCoreClassObject) public type // code split TKDT17DI16_Vec = array [0 .. KDT17DI16_Axis - 1] of TKDT17DI16_VecType; PKDT17DI16_Vec = ^TKDT17DI16_Vec; TKDT17DI16_DynamicVecBuffer = array of TKDT17DI16_Vec; PKDT17DI16_DynamicVecBuffer = ^TKDT17DI16_DynamicVecBuffer; TKDT17DI16_Source = record buff: TKDT17DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT17DI16_Source = ^TKDT17DI16_Source; TKDT17DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT17DI16_Source) - 1] of PKDT17DI16_Source; PKDT17DI16_SourceBuffer = ^TKDT17DI16_SourceBuffer; TKDT17DI16_DyanmicSourceBuffer = array of PKDT17DI16_Source; PKDT17DI16_DyanmicSourceBuffer = ^TKDT17DI16_DyanmicSourceBuffer; TKDT17DI16_DyanmicStoreBuffer = array of TKDT17DI16_Source; PKDT17DI16_DyanmicStoreBuffer = ^TKDT17DI16_DyanmicStoreBuffer; PKDT17DI16_Node = ^TKDT17DI16_Node; TKDT17DI16_Node = record Parent, Right, Left: PKDT17DI16_Node; Vec: PKDT17DI16_Source; end; TKDT17DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer); TKDT17DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT17DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT17DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT17DI16_DyanmicStoreBuffer; KDBuff: TKDT17DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT17DI16_Node; TestBuff: TKDT17DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DI16_Node; function GetData(const Index: NativeInt): PKDT17DI16_Source; public RootNode: PKDT17DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT17DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT17DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT17DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT17DI16_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: TKDT17DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildProc); overload; { search } function Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DI16_Node; overload; function Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DI16_Node; overload; function Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double): PKDT17DI16_Node; overload; function Search(const buff: TKDT17DI16_Vec): PKDT17DI16_Node; overload; function SearchToken(const buff: TKDT17DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT17DI16_DynamicVecBuffer; var OutBuff: TKDT17DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT17DI16_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: PKDT17DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT17DI16_Vec; overload; class function Vec(const v: TKDT17DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT17DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer); class procedure Test; end; TKDT18DI16 = class(TCoreClassObject) public type // code split TKDT18DI16_Vec = array [0 .. KDT18DI16_Axis - 1] of TKDT18DI16_VecType; PKDT18DI16_Vec = ^TKDT18DI16_Vec; TKDT18DI16_DynamicVecBuffer = array of TKDT18DI16_Vec; PKDT18DI16_DynamicVecBuffer = ^TKDT18DI16_DynamicVecBuffer; TKDT18DI16_Source = record buff: TKDT18DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT18DI16_Source = ^TKDT18DI16_Source; TKDT18DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT18DI16_Source) - 1] of PKDT18DI16_Source; PKDT18DI16_SourceBuffer = ^TKDT18DI16_SourceBuffer; TKDT18DI16_DyanmicSourceBuffer = array of PKDT18DI16_Source; PKDT18DI16_DyanmicSourceBuffer = ^TKDT18DI16_DyanmicSourceBuffer; TKDT18DI16_DyanmicStoreBuffer = array of TKDT18DI16_Source; PKDT18DI16_DyanmicStoreBuffer = ^TKDT18DI16_DyanmicStoreBuffer; PKDT18DI16_Node = ^TKDT18DI16_Node; TKDT18DI16_Node = record Parent, Right, Left: PKDT18DI16_Node; Vec: PKDT18DI16_Source; end; TKDT18DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer); TKDT18DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT18DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT18DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT18DI16_DyanmicStoreBuffer; KDBuff: TKDT18DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT18DI16_Node; TestBuff: TKDT18DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DI16_Node; function GetData(const Index: NativeInt): PKDT18DI16_Source; public RootNode: PKDT18DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT18DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT18DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT18DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT18DI16_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: TKDT18DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildProc); overload; { search } function Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DI16_Node; overload; function Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DI16_Node; overload; function Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double): PKDT18DI16_Node; overload; function Search(const buff: TKDT18DI16_Vec): PKDT18DI16_Node; overload; function SearchToken(const buff: TKDT18DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT18DI16_DynamicVecBuffer; var OutBuff: TKDT18DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT18DI16_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: PKDT18DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT18DI16_Vec; overload; class function Vec(const v: TKDT18DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT18DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer); class procedure Test; end; TKDT19DI16 = class(TCoreClassObject) public type // code split TKDT19DI16_Vec = array [0 .. KDT19DI16_Axis - 1] of TKDT19DI16_VecType; PKDT19DI16_Vec = ^TKDT19DI16_Vec; TKDT19DI16_DynamicVecBuffer = array of TKDT19DI16_Vec; PKDT19DI16_DynamicVecBuffer = ^TKDT19DI16_DynamicVecBuffer; TKDT19DI16_Source = record buff: TKDT19DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT19DI16_Source = ^TKDT19DI16_Source; TKDT19DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT19DI16_Source) - 1] of PKDT19DI16_Source; PKDT19DI16_SourceBuffer = ^TKDT19DI16_SourceBuffer; TKDT19DI16_DyanmicSourceBuffer = array of PKDT19DI16_Source; PKDT19DI16_DyanmicSourceBuffer = ^TKDT19DI16_DyanmicSourceBuffer; TKDT19DI16_DyanmicStoreBuffer = array of TKDT19DI16_Source; PKDT19DI16_DyanmicStoreBuffer = ^TKDT19DI16_DyanmicStoreBuffer; PKDT19DI16_Node = ^TKDT19DI16_Node; TKDT19DI16_Node = record Parent, Right, Left: PKDT19DI16_Node; Vec: PKDT19DI16_Source; end; TKDT19DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer); TKDT19DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT19DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT19DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT19DI16_DyanmicStoreBuffer; KDBuff: TKDT19DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT19DI16_Node; TestBuff: TKDT19DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DI16_Node; function GetData(const Index: NativeInt): PKDT19DI16_Source; public RootNode: PKDT19DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT19DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT19DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT19DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT19DI16_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: TKDT19DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildProc); overload; { search } function Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DI16_Node; overload; function Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DI16_Node; overload; function Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double): PKDT19DI16_Node; overload; function Search(const buff: TKDT19DI16_Vec): PKDT19DI16_Node; overload; function SearchToken(const buff: TKDT19DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT19DI16_DynamicVecBuffer; var OutBuff: TKDT19DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT19DI16_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: PKDT19DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT19DI16_Vec; overload; class function Vec(const v: TKDT19DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT19DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer); class procedure Test; end; TKDT20DI16 = class(TCoreClassObject) public type // code split TKDT20DI16_Vec = array [0 .. KDT20DI16_Axis - 1] of TKDT20DI16_VecType; PKDT20DI16_Vec = ^TKDT20DI16_Vec; TKDT20DI16_DynamicVecBuffer = array of TKDT20DI16_Vec; PKDT20DI16_DynamicVecBuffer = ^TKDT20DI16_DynamicVecBuffer; TKDT20DI16_Source = record buff: TKDT20DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT20DI16_Source = ^TKDT20DI16_Source; TKDT20DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT20DI16_Source) - 1] of PKDT20DI16_Source; PKDT20DI16_SourceBuffer = ^TKDT20DI16_SourceBuffer; TKDT20DI16_DyanmicSourceBuffer = array of PKDT20DI16_Source; PKDT20DI16_DyanmicSourceBuffer = ^TKDT20DI16_DyanmicSourceBuffer; TKDT20DI16_DyanmicStoreBuffer = array of TKDT20DI16_Source; PKDT20DI16_DyanmicStoreBuffer = ^TKDT20DI16_DyanmicStoreBuffer; PKDT20DI16_Node = ^TKDT20DI16_Node; TKDT20DI16_Node = record Parent, Right, Left: PKDT20DI16_Node; Vec: PKDT20DI16_Source; end; TKDT20DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer); TKDT20DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT20DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT20DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT20DI16_DyanmicStoreBuffer; KDBuff: TKDT20DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT20DI16_Node; TestBuff: TKDT20DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DI16_Node; function GetData(const Index: NativeInt): PKDT20DI16_Source; public RootNode: PKDT20DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT20DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT20DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT20DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT20DI16_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: TKDT20DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildProc); overload; { search } function Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DI16_Node; overload; function Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DI16_Node; overload; function Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double): PKDT20DI16_Node; overload; function Search(const buff: TKDT20DI16_Vec): PKDT20DI16_Node; overload; function SearchToken(const buff: TKDT20DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT20DI16_DynamicVecBuffer; var OutBuff: TKDT20DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT20DI16_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: PKDT20DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT20DI16_Vec; overload; class function Vec(const v: TKDT20DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT20DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer); class procedure Test; end; TKDT21DI16 = class(TCoreClassObject) public type // code split TKDT21DI16_Vec = array [0 .. KDT21DI16_Axis - 1] of TKDT21DI16_VecType; PKDT21DI16_Vec = ^TKDT21DI16_Vec; TKDT21DI16_DynamicVecBuffer = array of TKDT21DI16_Vec; PKDT21DI16_DynamicVecBuffer = ^TKDT21DI16_DynamicVecBuffer; TKDT21DI16_Source = record buff: TKDT21DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT21DI16_Source = ^TKDT21DI16_Source; TKDT21DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT21DI16_Source) - 1] of PKDT21DI16_Source; PKDT21DI16_SourceBuffer = ^TKDT21DI16_SourceBuffer; TKDT21DI16_DyanmicSourceBuffer = array of PKDT21DI16_Source; PKDT21DI16_DyanmicSourceBuffer = ^TKDT21DI16_DyanmicSourceBuffer; TKDT21DI16_DyanmicStoreBuffer = array of TKDT21DI16_Source; PKDT21DI16_DyanmicStoreBuffer = ^TKDT21DI16_DyanmicStoreBuffer; PKDT21DI16_Node = ^TKDT21DI16_Node; TKDT21DI16_Node = record Parent, Right, Left: PKDT21DI16_Node; Vec: PKDT21DI16_Source; end; TKDT21DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer); TKDT21DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT21DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT21DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT21DI16_DyanmicStoreBuffer; KDBuff: TKDT21DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT21DI16_Node; TestBuff: TKDT21DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DI16_Node; function GetData(const Index: NativeInt): PKDT21DI16_Source; public RootNode: PKDT21DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT21DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT21DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT21DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT21DI16_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: TKDT21DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildProc); overload; { search } function Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DI16_Node; overload; function Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DI16_Node; overload; function Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double): PKDT21DI16_Node; overload; function Search(const buff: TKDT21DI16_Vec): PKDT21DI16_Node; overload; function SearchToken(const buff: TKDT21DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT21DI16_DynamicVecBuffer; var OutBuff: TKDT21DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT21DI16_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: PKDT21DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT21DI16_Vec; overload; class function Vec(const v: TKDT21DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT21DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer); class procedure Test; end; TKDT22DI16 = class(TCoreClassObject) public type // code split TKDT22DI16_Vec = array [0 .. KDT22DI16_Axis - 1] of TKDT22DI16_VecType; PKDT22DI16_Vec = ^TKDT22DI16_Vec; TKDT22DI16_DynamicVecBuffer = array of TKDT22DI16_Vec; PKDT22DI16_DynamicVecBuffer = ^TKDT22DI16_DynamicVecBuffer; TKDT22DI16_Source = record buff: TKDT22DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT22DI16_Source = ^TKDT22DI16_Source; TKDT22DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT22DI16_Source) - 1] of PKDT22DI16_Source; PKDT22DI16_SourceBuffer = ^TKDT22DI16_SourceBuffer; TKDT22DI16_DyanmicSourceBuffer = array of PKDT22DI16_Source; PKDT22DI16_DyanmicSourceBuffer = ^TKDT22DI16_DyanmicSourceBuffer; TKDT22DI16_DyanmicStoreBuffer = array of TKDT22DI16_Source; PKDT22DI16_DyanmicStoreBuffer = ^TKDT22DI16_DyanmicStoreBuffer; PKDT22DI16_Node = ^TKDT22DI16_Node; TKDT22DI16_Node = record Parent, Right, Left: PKDT22DI16_Node; Vec: PKDT22DI16_Source; end; TKDT22DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer); TKDT22DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT22DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT22DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT22DI16_DyanmicStoreBuffer; KDBuff: TKDT22DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT22DI16_Node; TestBuff: TKDT22DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DI16_Node; function GetData(const Index: NativeInt): PKDT22DI16_Source; public RootNode: PKDT22DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT22DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT22DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT22DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT22DI16_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: TKDT22DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildProc); overload; { search } function Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DI16_Node; overload; function Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DI16_Node; overload; function Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double): PKDT22DI16_Node; overload; function Search(const buff: TKDT22DI16_Vec): PKDT22DI16_Node; overload; function SearchToken(const buff: TKDT22DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT22DI16_DynamicVecBuffer; var OutBuff: TKDT22DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT22DI16_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: PKDT22DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT22DI16_Vec; overload; class function Vec(const v: TKDT22DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT22DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer); class procedure Test; end; TKDT23DI16 = class(TCoreClassObject) public type // code split TKDT23DI16_Vec = array [0 .. KDT23DI16_Axis - 1] of TKDT23DI16_VecType; PKDT23DI16_Vec = ^TKDT23DI16_Vec; TKDT23DI16_DynamicVecBuffer = array of TKDT23DI16_Vec; PKDT23DI16_DynamicVecBuffer = ^TKDT23DI16_DynamicVecBuffer; TKDT23DI16_Source = record buff: TKDT23DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT23DI16_Source = ^TKDT23DI16_Source; TKDT23DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT23DI16_Source) - 1] of PKDT23DI16_Source; PKDT23DI16_SourceBuffer = ^TKDT23DI16_SourceBuffer; TKDT23DI16_DyanmicSourceBuffer = array of PKDT23DI16_Source; PKDT23DI16_DyanmicSourceBuffer = ^TKDT23DI16_DyanmicSourceBuffer; TKDT23DI16_DyanmicStoreBuffer = array of TKDT23DI16_Source; PKDT23DI16_DyanmicStoreBuffer = ^TKDT23DI16_DyanmicStoreBuffer; PKDT23DI16_Node = ^TKDT23DI16_Node; TKDT23DI16_Node = record Parent, Right, Left: PKDT23DI16_Node; Vec: PKDT23DI16_Source; end; TKDT23DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer); TKDT23DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT23DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT23DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT23DI16_DyanmicStoreBuffer; KDBuff: TKDT23DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT23DI16_Node; TestBuff: TKDT23DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DI16_Node; function GetData(const Index: NativeInt): PKDT23DI16_Source; public RootNode: PKDT23DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT23DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT23DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT23DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT23DI16_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: TKDT23DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildProc); overload; { search } function Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DI16_Node; overload; function Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DI16_Node; overload; function Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double): PKDT23DI16_Node; overload; function Search(const buff: TKDT23DI16_Vec): PKDT23DI16_Node; overload; function SearchToken(const buff: TKDT23DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT23DI16_DynamicVecBuffer; var OutBuff: TKDT23DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT23DI16_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: PKDT23DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT23DI16_Vec; overload; class function Vec(const v: TKDT23DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT23DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer); class procedure Test; end; TKDT24DI16 = class(TCoreClassObject) public type // code split TKDT24DI16_Vec = array [0 .. KDT24DI16_Axis - 1] of TKDT24DI16_VecType; PKDT24DI16_Vec = ^TKDT24DI16_Vec; TKDT24DI16_DynamicVecBuffer = array of TKDT24DI16_Vec; PKDT24DI16_DynamicVecBuffer = ^TKDT24DI16_DynamicVecBuffer; TKDT24DI16_Source = record buff: TKDT24DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT24DI16_Source = ^TKDT24DI16_Source; TKDT24DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT24DI16_Source) - 1] of PKDT24DI16_Source; PKDT24DI16_SourceBuffer = ^TKDT24DI16_SourceBuffer; TKDT24DI16_DyanmicSourceBuffer = array of PKDT24DI16_Source; PKDT24DI16_DyanmicSourceBuffer = ^TKDT24DI16_DyanmicSourceBuffer; TKDT24DI16_DyanmicStoreBuffer = array of TKDT24DI16_Source; PKDT24DI16_DyanmicStoreBuffer = ^TKDT24DI16_DyanmicStoreBuffer; PKDT24DI16_Node = ^TKDT24DI16_Node; TKDT24DI16_Node = record Parent, Right, Left: PKDT24DI16_Node; Vec: PKDT24DI16_Source; end; TKDT24DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer); TKDT24DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT24DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT24DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT24DI16_DyanmicStoreBuffer; KDBuff: TKDT24DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT24DI16_Node; TestBuff: TKDT24DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DI16_Node; function GetData(const Index: NativeInt): PKDT24DI16_Source; public RootNode: PKDT24DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT24DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT24DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT24DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT24DI16_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: TKDT24DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildProc); overload; { search } function Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DI16_Node; overload; function Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DI16_Node; overload; function Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double): PKDT24DI16_Node; overload; function Search(const buff: TKDT24DI16_Vec): PKDT24DI16_Node; overload; function SearchToken(const buff: TKDT24DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT24DI16_DynamicVecBuffer; var OutBuff: TKDT24DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT24DI16_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: PKDT24DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT24DI16_Vec; overload; class function Vec(const v: TKDT24DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT24DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer); class procedure Test; end; TKDT48DI16 = class(TCoreClassObject) public type // code split TKDT48DI16_Vec = array [0 .. KDT48DI16_Axis - 1] of TKDT48DI16_VecType; PKDT48DI16_Vec = ^TKDT48DI16_Vec; TKDT48DI16_DynamicVecBuffer = array of TKDT48DI16_Vec; PKDT48DI16_DynamicVecBuffer = ^TKDT48DI16_DynamicVecBuffer; TKDT48DI16_Source = record buff: TKDT48DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT48DI16_Source = ^TKDT48DI16_Source; TKDT48DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT48DI16_Source) - 1] of PKDT48DI16_Source; PKDT48DI16_SourceBuffer = ^TKDT48DI16_SourceBuffer; TKDT48DI16_DyanmicSourceBuffer = array of PKDT48DI16_Source; PKDT48DI16_DyanmicSourceBuffer = ^TKDT48DI16_DyanmicSourceBuffer; TKDT48DI16_DyanmicStoreBuffer = array of TKDT48DI16_Source; PKDT48DI16_DyanmicStoreBuffer = ^TKDT48DI16_DyanmicStoreBuffer; PKDT48DI16_Node = ^TKDT48DI16_Node; TKDT48DI16_Node = record Parent, Right, Left: PKDT48DI16_Node; Vec: PKDT48DI16_Source; end; TKDT48DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer); TKDT48DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT48DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT48DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT48DI16_DyanmicStoreBuffer; KDBuff: TKDT48DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT48DI16_Node; TestBuff: TKDT48DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DI16_Node; function GetData(const Index: NativeInt): PKDT48DI16_Source; public RootNode: PKDT48DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT48DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT48DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT48DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT48DI16_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: TKDT48DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildProc); overload; { search } function Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DI16_Node; overload; function Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DI16_Node; overload; function Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double): PKDT48DI16_Node; overload; function Search(const buff: TKDT48DI16_Vec): PKDT48DI16_Node; overload; function SearchToken(const buff: TKDT48DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT48DI16_DynamicVecBuffer; var OutBuff: TKDT48DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT48DI16_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: PKDT48DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT48DI16_Vec; overload; class function Vec(const v: TKDT48DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT48DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer); class procedure Test; end; TKDT52DI16 = class(TCoreClassObject) public type // code split TKDT52DI16_Vec = array [0 .. KDT52DI16_Axis - 1] of TKDT52DI16_VecType; PKDT52DI16_Vec = ^TKDT52DI16_Vec; TKDT52DI16_DynamicVecBuffer = array of TKDT52DI16_Vec; PKDT52DI16_DynamicVecBuffer = ^TKDT52DI16_DynamicVecBuffer; TKDT52DI16_Source = record buff: TKDT52DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT52DI16_Source = ^TKDT52DI16_Source; TKDT52DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT52DI16_Source) - 1] of PKDT52DI16_Source; PKDT52DI16_SourceBuffer = ^TKDT52DI16_SourceBuffer; TKDT52DI16_DyanmicSourceBuffer = array of PKDT52DI16_Source; PKDT52DI16_DyanmicSourceBuffer = ^TKDT52DI16_DyanmicSourceBuffer; TKDT52DI16_DyanmicStoreBuffer = array of TKDT52DI16_Source; PKDT52DI16_DyanmicStoreBuffer = ^TKDT52DI16_DyanmicStoreBuffer; PKDT52DI16_Node = ^TKDT52DI16_Node; TKDT52DI16_Node = record Parent, Right, Left: PKDT52DI16_Node; Vec: PKDT52DI16_Source; end; TKDT52DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer); TKDT52DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT52DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT52DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT52DI16_DyanmicStoreBuffer; KDBuff: TKDT52DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT52DI16_Node; TestBuff: TKDT52DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DI16_Node; function GetData(const Index: NativeInt): PKDT52DI16_Source; public RootNode: PKDT52DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT52DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT52DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT52DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT52DI16_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: TKDT52DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildProc); overload; { search } function Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DI16_Node; overload; function Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DI16_Node; overload; function Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double): PKDT52DI16_Node; overload; function Search(const buff: TKDT52DI16_Vec): PKDT52DI16_Node; overload; function SearchToken(const buff: TKDT52DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT52DI16_DynamicVecBuffer; var OutBuff: TKDT52DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT52DI16_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: PKDT52DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT52DI16_Vec; overload; class function Vec(const v: TKDT52DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT52DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer); class procedure Test; end; TKDT64DI16 = class(TCoreClassObject) public type // code split TKDT64DI16_Vec = array [0 .. KDT64DI16_Axis - 1] of TKDT64DI16_VecType; PKDT64DI16_Vec = ^TKDT64DI16_Vec; TKDT64DI16_DynamicVecBuffer = array of TKDT64DI16_Vec; PKDT64DI16_DynamicVecBuffer = ^TKDT64DI16_DynamicVecBuffer; TKDT64DI16_Source = record buff: TKDT64DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT64DI16_Source = ^TKDT64DI16_Source; TKDT64DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT64DI16_Source) - 1] of PKDT64DI16_Source; PKDT64DI16_SourceBuffer = ^TKDT64DI16_SourceBuffer; TKDT64DI16_DyanmicSourceBuffer = array of PKDT64DI16_Source; PKDT64DI16_DyanmicSourceBuffer = ^TKDT64DI16_DyanmicSourceBuffer; TKDT64DI16_DyanmicStoreBuffer = array of TKDT64DI16_Source; PKDT64DI16_DyanmicStoreBuffer = ^TKDT64DI16_DyanmicStoreBuffer; PKDT64DI16_Node = ^TKDT64DI16_Node; TKDT64DI16_Node = record Parent, Right, Left: PKDT64DI16_Node; Vec: PKDT64DI16_Source; end; TKDT64DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer); TKDT64DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT64DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT64DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT64DI16_DyanmicStoreBuffer; KDBuff: TKDT64DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT64DI16_Node; TestBuff: TKDT64DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DI16_Node; function GetData(const Index: NativeInt): PKDT64DI16_Source; public RootNode: PKDT64DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT64DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT64DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT64DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT64DI16_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: TKDT64DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildProc); overload; { search } function Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DI16_Node; overload; function Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DI16_Node; overload; function Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double): PKDT64DI16_Node; overload; function Search(const buff: TKDT64DI16_Vec): PKDT64DI16_Node; overload; function SearchToken(const buff: TKDT64DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT64DI16_DynamicVecBuffer; var OutBuff: TKDT64DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT64DI16_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: PKDT64DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT64DI16_Vec; overload; class function Vec(const v: TKDT64DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT64DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer); class procedure Test; end; TKDT96DI16 = class(TCoreClassObject) public type // code split TKDT96DI16_Vec = array [0 .. KDT96DI16_Axis - 1] of TKDT96DI16_VecType; PKDT96DI16_Vec = ^TKDT96DI16_Vec; TKDT96DI16_DynamicVecBuffer = array of TKDT96DI16_Vec; PKDT96DI16_DynamicVecBuffer = ^TKDT96DI16_DynamicVecBuffer; TKDT96DI16_Source = record buff: TKDT96DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT96DI16_Source = ^TKDT96DI16_Source; TKDT96DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT96DI16_Source) - 1] of PKDT96DI16_Source; PKDT96DI16_SourceBuffer = ^TKDT96DI16_SourceBuffer; TKDT96DI16_DyanmicSourceBuffer = array of PKDT96DI16_Source; PKDT96DI16_DyanmicSourceBuffer = ^TKDT96DI16_DyanmicSourceBuffer; TKDT96DI16_DyanmicStoreBuffer = array of TKDT96DI16_Source; PKDT96DI16_DyanmicStoreBuffer = ^TKDT96DI16_DyanmicStoreBuffer; PKDT96DI16_Node = ^TKDT96DI16_Node; TKDT96DI16_Node = record Parent, Right, Left: PKDT96DI16_Node; Vec: PKDT96DI16_Source; end; TKDT96DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer); TKDT96DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT96DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT96DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT96DI16_DyanmicStoreBuffer; KDBuff: TKDT96DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT96DI16_Node; TestBuff: TKDT96DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DI16_Node; function GetData(const Index: NativeInt): PKDT96DI16_Source; public RootNode: PKDT96DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT96DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT96DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT96DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT96DI16_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: TKDT96DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildProc); overload; { search } function Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DI16_Node; overload; function Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DI16_Node; overload; function Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double): PKDT96DI16_Node; overload; function Search(const buff: TKDT96DI16_Vec): PKDT96DI16_Node; overload; function SearchToken(const buff: TKDT96DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT96DI16_DynamicVecBuffer; var OutBuff: TKDT96DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT96DI16_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: PKDT96DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT96DI16_Vec; overload; class function Vec(const v: TKDT96DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT96DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer); class procedure Test; end; TKDT128DI16 = class(TCoreClassObject) public type // code split TKDT128DI16_Vec = array [0 .. KDT128DI16_Axis - 1] of TKDT128DI16_VecType; PKDT128DI16_Vec = ^TKDT128DI16_Vec; TKDT128DI16_DynamicVecBuffer = array of TKDT128DI16_Vec; PKDT128DI16_DynamicVecBuffer = ^TKDT128DI16_DynamicVecBuffer; TKDT128DI16_Source = record buff: TKDT128DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT128DI16_Source = ^TKDT128DI16_Source; TKDT128DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT128DI16_Source) - 1] of PKDT128DI16_Source; PKDT128DI16_SourceBuffer = ^TKDT128DI16_SourceBuffer; TKDT128DI16_DyanmicSourceBuffer = array of PKDT128DI16_Source; PKDT128DI16_DyanmicSourceBuffer = ^TKDT128DI16_DyanmicSourceBuffer; TKDT128DI16_DyanmicStoreBuffer = array of TKDT128DI16_Source; PKDT128DI16_DyanmicStoreBuffer = ^TKDT128DI16_DyanmicStoreBuffer; PKDT128DI16_Node = ^TKDT128DI16_Node; TKDT128DI16_Node = record Parent, Right, Left: PKDT128DI16_Node; Vec: PKDT128DI16_Source; end; TKDT128DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer); TKDT128DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT128DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT128DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT128DI16_DyanmicStoreBuffer; KDBuff: TKDT128DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT128DI16_Node; TestBuff: TKDT128DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DI16_Node; function GetData(const Index: NativeInt): PKDT128DI16_Source; public RootNode: PKDT128DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT128DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT128DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT128DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT128DI16_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: TKDT128DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildProc); overload; { search } function Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DI16_Node; overload; function Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DI16_Node; overload; function Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double): PKDT128DI16_Node; overload; function Search(const buff: TKDT128DI16_Vec): PKDT128DI16_Node; overload; function SearchToken(const buff: TKDT128DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT128DI16_DynamicVecBuffer; var OutBuff: TKDT128DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT128DI16_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: PKDT128DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT128DI16_Vec; overload; class function Vec(const v: TKDT128DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT128DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer); class procedure Test; end; TKDT156DI16 = class(TCoreClassObject) public type // code split TKDT156DI16_Vec = array [0 .. KDT156DI16_Axis - 1] of TKDT156DI16_VecType; PKDT156DI16_Vec = ^TKDT156DI16_Vec; TKDT156DI16_DynamicVecBuffer = array of TKDT156DI16_Vec; PKDT156DI16_DynamicVecBuffer = ^TKDT156DI16_DynamicVecBuffer; TKDT156DI16_Source = record buff: TKDT156DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT156DI16_Source = ^TKDT156DI16_Source; TKDT156DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT156DI16_Source) - 1] of PKDT156DI16_Source; PKDT156DI16_SourceBuffer = ^TKDT156DI16_SourceBuffer; TKDT156DI16_DyanmicSourceBuffer = array of PKDT156DI16_Source; PKDT156DI16_DyanmicSourceBuffer = ^TKDT156DI16_DyanmicSourceBuffer; TKDT156DI16_DyanmicStoreBuffer = array of TKDT156DI16_Source; PKDT156DI16_DyanmicStoreBuffer = ^TKDT156DI16_DyanmicStoreBuffer; PKDT156DI16_Node = ^TKDT156DI16_Node; TKDT156DI16_Node = record Parent, Right, Left: PKDT156DI16_Node; Vec: PKDT156DI16_Source; end; TKDT156DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer); TKDT156DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT156DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT156DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT156DI16_DyanmicStoreBuffer; KDBuff: TKDT156DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT156DI16_Node; TestBuff: TKDT156DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DI16_Node; function GetData(const Index: NativeInt): PKDT156DI16_Source; public RootNode: PKDT156DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT156DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT156DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT156DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT156DI16_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: TKDT156DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildProc); overload; { search } function Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DI16_Node; overload; function Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DI16_Node; overload; function Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double): PKDT156DI16_Node; overload; function Search(const buff: TKDT156DI16_Vec): PKDT156DI16_Node; overload; function SearchToken(const buff: TKDT156DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT156DI16_DynamicVecBuffer; var OutBuff: TKDT156DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT156DI16_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: PKDT156DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT156DI16_Vec; overload; class function Vec(const v: TKDT156DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT156DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer); class procedure Test; end; TKDT192DI16 = class(TCoreClassObject) public type // code split TKDT192DI16_Vec = array [0 .. KDT192DI16_Axis - 1] of TKDT192DI16_VecType; PKDT192DI16_Vec = ^TKDT192DI16_Vec; TKDT192DI16_DynamicVecBuffer = array of TKDT192DI16_Vec; PKDT192DI16_DynamicVecBuffer = ^TKDT192DI16_DynamicVecBuffer; TKDT192DI16_Source = record buff: TKDT192DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT192DI16_Source = ^TKDT192DI16_Source; TKDT192DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT192DI16_Source) - 1] of PKDT192DI16_Source; PKDT192DI16_SourceBuffer = ^TKDT192DI16_SourceBuffer; TKDT192DI16_DyanmicSourceBuffer = array of PKDT192DI16_Source; PKDT192DI16_DyanmicSourceBuffer = ^TKDT192DI16_DyanmicSourceBuffer; TKDT192DI16_DyanmicStoreBuffer = array of TKDT192DI16_Source; PKDT192DI16_DyanmicStoreBuffer = ^TKDT192DI16_DyanmicStoreBuffer; PKDT192DI16_Node = ^TKDT192DI16_Node; TKDT192DI16_Node = record Parent, Right, Left: PKDT192DI16_Node; Vec: PKDT192DI16_Source; end; TKDT192DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer); TKDT192DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT192DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT192DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT192DI16_DyanmicStoreBuffer; KDBuff: TKDT192DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT192DI16_Node; TestBuff: TKDT192DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DI16_Node; function GetData(const Index: NativeInt): PKDT192DI16_Source; public RootNode: PKDT192DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT192DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT192DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT192DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT192DI16_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: TKDT192DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildProc); overload; { search } function Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DI16_Node; overload; function Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DI16_Node; overload; function Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double): PKDT192DI16_Node; overload; function Search(const buff: TKDT192DI16_Vec): PKDT192DI16_Node; overload; function SearchToken(const buff: TKDT192DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT192DI16_DynamicVecBuffer; var OutBuff: TKDT192DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT192DI16_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: PKDT192DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT192DI16_Vec; overload; class function Vec(const v: TKDT192DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT192DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer); class procedure Test; end; TKDT256DI16 = class(TCoreClassObject) public type // code split TKDT256DI16_Vec = array [0 .. KDT256DI16_Axis - 1] of TKDT256DI16_VecType; PKDT256DI16_Vec = ^TKDT256DI16_Vec; TKDT256DI16_DynamicVecBuffer = array of TKDT256DI16_Vec; PKDT256DI16_DynamicVecBuffer = ^TKDT256DI16_DynamicVecBuffer; TKDT256DI16_Source = record buff: TKDT256DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT256DI16_Source = ^TKDT256DI16_Source; TKDT256DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT256DI16_Source) - 1] of PKDT256DI16_Source; PKDT256DI16_SourceBuffer = ^TKDT256DI16_SourceBuffer; TKDT256DI16_DyanmicSourceBuffer = array of PKDT256DI16_Source; PKDT256DI16_DyanmicSourceBuffer = ^TKDT256DI16_DyanmicSourceBuffer; TKDT256DI16_DyanmicStoreBuffer = array of TKDT256DI16_Source; PKDT256DI16_DyanmicStoreBuffer = ^TKDT256DI16_DyanmicStoreBuffer; PKDT256DI16_Node = ^TKDT256DI16_Node; TKDT256DI16_Node = record Parent, Right, Left: PKDT256DI16_Node; Vec: PKDT256DI16_Source; end; TKDT256DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer); TKDT256DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT256DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT256DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT256DI16_DyanmicStoreBuffer; KDBuff: TKDT256DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT256DI16_Node; TestBuff: TKDT256DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DI16_Node; function GetData(const Index: NativeInt): PKDT256DI16_Source; public RootNode: PKDT256DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT256DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT256DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT256DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT256DI16_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: TKDT256DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildProc); overload; { search } function Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DI16_Node; overload; function Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DI16_Node; overload; function Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double): PKDT256DI16_Node; overload; function Search(const buff: TKDT256DI16_Vec): PKDT256DI16_Node; overload; function SearchToken(const buff: TKDT256DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT256DI16_DynamicVecBuffer; var OutBuff: TKDT256DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT256DI16_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: PKDT256DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT256DI16_Vec; overload; class function Vec(const v: TKDT256DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT256DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer); class procedure Test; end; TKDT384DI16 = class(TCoreClassObject) public type // code split TKDT384DI16_Vec = array [0 .. KDT384DI16_Axis - 1] of TKDT384DI16_VecType; PKDT384DI16_Vec = ^TKDT384DI16_Vec; TKDT384DI16_DynamicVecBuffer = array of TKDT384DI16_Vec; PKDT384DI16_DynamicVecBuffer = ^TKDT384DI16_DynamicVecBuffer; TKDT384DI16_Source = record buff: TKDT384DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT384DI16_Source = ^TKDT384DI16_Source; TKDT384DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT384DI16_Source) - 1] of PKDT384DI16_Source; PKDT384DI16_SourceBuffer = ^TKDT384DI16_SourceBuffer; TKDT384DI16_DyanmicSourceBuffer = array of PKDT384DI16_Source; PKDT384DI16_DyanmicSourceBuffer = ^TKDT384DI16_DyanmicSourceBuffer; TKDT384DI16_DyanmicStoreBuffer = array of TKDT384DI16_Source; PKDT384DI16_DyanmicStoreBuffer = ^TKDT384DI16_DyanmicStoreBuffer; PKDT384DI16_Node = ^TKDT384DI16_Node; TKDT384DI16_Node = record Parent, Right, Left: PKDT384DI16_Node; Vec: PKDT384DI16_Source; end; TKDT384DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer); TKDT384DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT384DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT384DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT384DI16_DyanmicStoreBuffer; KDBuff: TKDT384DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT384DI16_Node; TestBuff: TKDT384DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DI16_Node; function GetData(const Index: NativeInt): PKDT384DI16_Source; public RootNode: PKDT384DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT384DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT384DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT384DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT384DI16_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: TKDT384DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildProc); overload; { search } function Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DI16_Node; overload; function Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DI16_Node; overload; function Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double): PKDT384DI16_Node; overload; function Search(const buff: TKDT384DI16_Vec): PKDT384DI16_Node; overload; function SearchToken(const buff: TKDT384DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT384DI16_DynamicVecBuffer; var OutBuff: TKDT384DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT384DI16_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: PKDT384DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT384DI16_Vec; overload; class function Vec(const v: TKDT384DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT384DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer); class procedure Test; end; TKDT512DI16 = class(TCoreClassObject) public type // code split TKDT512DI16_Vec = array [0 .. KDT512DI16_Axis - 1] of TKDT512DI16_VecType; PKDT512DI16_Vec = ^TKDT512DI16_Vec; TKDT512DI16_DynamicVecBuffer = array of TKDT512DI16_Vec; PKDT512DI16_DynamicVecBuffer = ^TKDT512DI16_DynamicVecBuffer; TKDT512DI16_Source = record buff: TKDT512DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT512DI16_Source = ^TKDT512DI16_Source; TKDT512DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT512DI16_Source) - 1] of PKDT512DI16_Source; PKDT512DI16_SourceBuffer = ^TKDT512DI16_SourceBuffer; TKDT512DI16_DyanmicSourceBuffer = array of PKDT512DI16_Source; PKDT512DI16_DyanmicSourceBuffer = ^TKDT512DI16_DyanmicSourceBuffer; TKDT512DI16_DyanmicStoreBuffer = array of TKDT512DI16_Source; PKDT512DI16_DyanmicStoreBuffer = ^TKDT512DI16_DyanmicStoreBuffer; PKDT512DI16_Node = ^TKDT512DI16_Node; TKDT512DI16_Node = record Parent, Right, Left: PKDT512DI16_Node; Vec: PKDT512DI16_Source; end; TKDT512DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer); TKDT512DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT512DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT512DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT512DI16_DyanmicStoreBuffer; KDBuff: TKDT512DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT512DI16_Node; TestBuff: TKDT512DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DI16_Node; function GetData(const Index: NativeInt): PKDT512DI16_Source; public RootNode: PKDT512DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT512DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT512DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT512DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT512DI16_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: TKDT512DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildProc); overload; { search } function Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DI16_Node; overload; function Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DI16_Node; overload; function Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double): PKDT512DI16_Node; overload; function Search(const buff: TKDT512DI16_Vec): PKDT512DI16_Node; overload; function SearchToken(const buff: TKDT512DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT512DI16_DynamicVecBuffer; var OutBuff: TKDT512DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT512DI16_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: PKDT512DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT512DI16_Vec; overload; class function Vec(const v: TKDT512DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT512DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer); class procedure Test; end; TKDT800DI16 = class(TCoreClassObject) public type // code split TKDT800DI16_Vec = array [0 .. KDT800DI16_Axis - 1] of TKDT800DI16_VecType; PKDT800DI16_Vec = ^TKDT800DI16_Vec; TKDT800DI16_DynamicVecBuffer = array of TKDT800DI16_Vec; PKDT800DI16_DynamicVecBuffer = ^TKDT800DI16_DynamicVecBuffer; TKDT800DI16_Source = record buff: TKDT800DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT800DI16_Source = ^TKDT800DI16_Source; TKDT800DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT800DI16_Source) - 1] of PKDT800DI16_Source; PKDT800DI16_SourceBuffer = ^TKDT800DI16_SourceBuffer; TKDT800DI16_DyanmicSourceBuffer = array of PKDT800DI16_Source; PKDT800DI16_DyanmicSourceBuffer = ^TKDT800DI16_DyanmicSourceBuffer; TKDT800DI16_DyanmicStoreBuffer = array of TKDT800DI16_Source; PKDT800DI16_DyanmicStoreBuffer = ^TKDT800DI16_DyanmicStoreBuffer; PKDT800DI16_Node = ^TKDT800DI16_Node; TKDT800DI16_Node = record Parent, Right, Left: PKDT800DI16_Node; Vec: PKDT800DI16_Source; end; TKDT800DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer); TKDT800DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT800DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT800DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT800DI16_DyanmicStoreBuffer; KDBuff: TKDT800DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT800DI16_Node; TestBuff: TKDT800DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DI16_Node; function GetData(const Index: NativeInt): PKDT800DI16_Source; public RootNode: PKDT800DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT800DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT800DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT800DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT800DI16_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: TKDT800DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildProc); overload; { search } function Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DI16_Node; overload; function Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DI16_Node; overload; function Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double): PKDT800DI16_Node; overload; function Search(const buff: TKDT800DI16_Vec): PKDT800DI16_Node; overload; function SearchToken(const buff: TKDT800DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT800DI16_DynamicVecBuffer; var OutBuff: TKDT800DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT800DI16_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: PKDT800DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT800DI16_Vec; overload; class function Vec(const v: TKDT800DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT800DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer); class procedure Test; end; TKDT1024DI16 = class(TCoreClassObject) public type // code split TKDT1024DI16_Vec = array [0 .. KDT1024DI16_Axis - 1] of TKDT1024DI16_VecType; PKDT1024DI16_Vec = ^TKDT1024DI16_Vec; TKDT1024DI16_DynamicVecBuffer = array of TKDT1024DI16_Vec; PKDT1024DI16_DynamicVecBuffer = ^TKDT1024DI16_DynamicVecBuffer; TKDT1024DI16_Source = record buff: TKDT1024DI16_Vec; Index: Int64; Token: TPascalString; end; PKDT1024DI16_Source = ^TKDT1024DI16_Source; TKDT1024DI16_SourceBuffer = array [0 .. MaxInt div SizeOf(PKDT1024DI16_Source) - 1] of PKDT1024DI16_Source; PKDT1024DI16_SourceBuffer = ^TKDT1024DI16_SourceBuffer; TKDT1024DI16_DyanmicSourceBuffer = array of PKDT1024DI16_Source; PKDT1024DI16_DyanmicSourceBuffer = ^TKDT1024DI16_DyanmicSourceBuffer; TKDT1024DI16_DyanmicStoreBuffer = array of TKDT1024DI16_Source; PKDT1024DI16_DyanmicStoreBuffer = ^TKDT1024DI16_DyanmicStoreBuffer; PKDT1024DI16_Node = ^TKDT1024DI16_Node; TKDT1024DI16_Node = record Parent, Right, Left: PKDT1024DI16_Node; Vec: PKDT1024DI16_Source; end; TKDT1024DI16_BuildCall = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer); TKDT1024DI16_BuildMethod = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer) of object; {$IFDEF FPC} TKDT1024DI16_BuildProc = procedure(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer) is nested; {$ELSE FPC} TKDT1024DI16_BuildProc = reference to procedure(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer); {$ENDIF FPC} private KDStoreBuff: TKDT1024DI16_DyanmicStoreBuffer; KDBuff: TKDT1024DI16_DyanmicSourceBuffer; NodeCounter: NativeInt; KDNodes: array of PKDT1024DI16_Node; TestBuff: TKDT1024DI16_DynamicVecBuffer; function InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DI16_Node; function GetData(const Index: NativeInt): PKDT1024DI16_Source; public RootNode: PKDT1024DI16_Node; constructor Create; destructor Destroy; override; procedure Clear; property Count: NativeInt read NodeCounter; function StoreBuffPtr: PKDT1024DI16_DyanmicStoreBuffer; property SourceP[const Index: NativeInt]: PKDT1024DI16_Source read GetData; default; { bakcall build } procedure BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildCall); procedure BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildMethod); procedure BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildProc); { fill k-means++ clusterization } procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); overload; procedure BuildKDTreeWithCluster(const inBuff: TKDT1024DI16_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: TKDT1024DI16_BuildCall); overload; procedure BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildMethod); overload; procedure BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildProc); overload; { search } function Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DI16_Node; overload; function Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DI16_Node; overload; function Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double): PKDT1024DI16_Node; overload; function Search(const buff: TKDT1024DI16_Vec): PKDT1024DI16_Node; overload; function SearchToken(const buff: TKDT1024DI16_Vec): TPascalString; { parallel search } procedure Search(const inBuff: TKDT1024DI16_DynamicVecBuffer; var OutBuff: TKDT1024DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); overload; procedure Search(const inBuff: TKDT1024DI16_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: PKDT1024DI16_Node); procedure PrintBuffer; class function Vec(const s: SystemString): TKDT1024DI16_Vec; overload; class function Vec(const v: TKDT1024DI16_Vec): SystemString; overload; class function Distance(const v1, v2: TKDT1024DI16_Vec): Double; // debug time procedure Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer); class procedure Test; end; procedure Test_All; implementation uses TextParsing, MemoryStream64, DoStatusIO; const SaveToken = $77; function TKDT1DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1DI16_Node; function SortCompare(const p1, p2: PKDT1DI16_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: PKDT1DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT1DI16_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: PKDT1DI16_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 KDT1DI16_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 TKDT1DI16.GetData(const Index: NativeInt): PKDT1DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT1DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT1DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT1DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT1DI16_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 TKDT1DI16.StoreBuffPtr: PKDT1DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT1DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT1DI16.BuildKDTreeWithCluster(const inBuff: TKDT1DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT1DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT1DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT1DI16_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 KDT1DI16_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 TKDT1DI16.BuildKDTreeWithCluster(const inBuff: TKDT1DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT1DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildCall); var TempStoreBuff: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI16_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 KDT1DI16_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 TKDT1DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildMethod); var TempStoreBuff: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI16_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 KDT1DI16_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 TKDT1DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1DI16_BuildProc); var TempStoreBuff: TKDT1DI16_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(TKDT1DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1DI16_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 KDT1DI16_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 TKDT1DI16.Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1DI16_Node; var NearestNeighbour: PKDT1DI16_Node; function FindParentNode(const buffPtr: PKDT1DI16_Vec; NodePtr: PKDT1DI16_Node): PKDT1DI16_Node; var Next: PKDT1DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT1DI16_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: PKDT1DI16_Node; const buffPtr: PKDT1DI16_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 KDT1DI16_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: PKDT1DI16_Vec; const p1, p2: PKDT1DI16_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: PKDT1DI16_Vec); var i, j: NativeInt; p, t: PKDT1DI16_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: PKDT1DI16_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 := PKDT1DI16_Node(NearestNodes[0]); end; end; function TKDT1DI16.Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT1DI16.Search(const buff: TKDT1DI16_Vec; var SearchedDistanceMin: Double): PKDT1DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1DI16.Search(const buff: TKDT1DI16_Vec): PKDT1DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1DI16.SearchToken(const buff: TKDT1DI16_Vec): TPascalString; var p: PKDT1DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT1DI16.Search(const inBuff: TKDT1DI16_DynamicVecBuffer; var OutBuff: TKDT1DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1DI16_DynamicVecBuffer; outBuffPtr: PKDT1DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1DI16_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: PKDT1DI16_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: PKDT1DI16_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 TKDT1DI16.Search(const inBuff: TKDT1DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1DI16_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: PKDT1DI16_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: PKDT1DI16_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 TKDT1DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT1DI16_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(TKDT1DI16_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 TKDT1DI16.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 <> KDT1DI16_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(TKDT1DI16_Vec)) <> SizeOf(TKDT1DI16_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 TKDT1DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1DI16.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 TKDT1DI16.PrintNodeTree(const NodePtr: PKDT1DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT1DI16_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 TKDT1DI16.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 TKDT1DI16.Vec(const s: SystemString): TKDT1DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT1DI16_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 >= KDT1DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT1DI16.Vec(const v: TKDT1DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT1DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT1DI16.Distance(const v1, v2: TKDT1DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT1DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT1DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT1DI16.Test; var TKDT1DI16_Test: TKDT1DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT1DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT1DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT1DI16_Test := TKDT1DI16.Create; n.Append('...'); SetLength(TKDT1DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT1DI16_Test.TestBuff) - 1 do for j := 0 to KDT1DI16_Axis - 1 do TKDT1DI16_Test.TestBuff[i][j] := i * KDT1DI16_Axis + j; {$IFDEF FPC} TKDT1DI16_Test.BuildKDTreeM(length(TKDT1DI16_Test.TestBuff), nil, @TKDT1DI16_Test.Test_BuildM); {$ELSE FPC} TKDT1DI16_Test.BuildKDTreeM(length(TKDT1DI16_Test.TestBuff), nil, TKDT1DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT1DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT1DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT1DI16_Test.TestBuff) - 1 do begin p := TKDT1DI16_Test.Search(TKDT1DI16_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(TKDT1DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT1DI16_Test.TestBuff)); TKDT1DI16_Test.Search(TKDT1DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT1DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT1DI16_Test.Clear; { kMean test } TKDT1DI16_Test.BuildKDTreeWithCluster(TKDT1DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT1DI16_Test.Search(TKDT1DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT1DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT1DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT1DI16_Test); DoStatus(n); n := ''; end; function TKDT2DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT2DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT2DI16_Node; function SortCompare(const p1, p2: PKDT2DI16_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: PKDT2DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT2DI16_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: PKDT2DI16_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 KDT2DI16_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 TKDT2DI16.GetData(const Index: NativeInt): PKDT2DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT2DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT2DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT2DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT2DI16_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 TKDT2DI16.StoreBuffPtr: PKDT2DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT2DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT2DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT2DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT2DI16.BuildKDTreeWithCluster(const inBuff: TKDT2DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT2DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT2DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT2DI16_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 KDT2DI16_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 TKDT2DI16.BuildKDTreeWithCluster(const inBuff: TKDT2DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT2DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildCall); var TempStoreBuff: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI16_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 KDT2DI16_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 TKDT2DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildMethod); var TempStoreBuff: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI16_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 KDT2DI16_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 TKDT2DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT2DI16_BuildProc); var TempStoreBuff: TKDT2DI16_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(TKDT2DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT2DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT2DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT2DI16_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 KDT2DI16_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 TKDT2DI16.Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT2DI16_Node; var NearestNeighbour: PKDT2DI16_Node; function FindParentNode(const buffPtr: PKDT2DI16_Vec; NodePtr: PKDT2DI16_Node): PKDT2DI16_Node; var Next: PKDT2DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT2DI16_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: PKDT2DI16_Node; const buffPtr: PKDT2DI16_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 KDT2DI16_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: PKDT2DI16_Vec; const p1, p2: PKDT2DI16_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: PKDT2DI16_Vec); var i, j: NativeInt; p, t: PKDT2DI16_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: PKDT2DI16_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 := PKDT2DI16_Node(NearestNodes[0]); end; end; function TKDT2DI16.Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT2DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT2DI16.Search(const buff: TKDT2DI16_Vec; var SearchedDistanceMin: Double): PKDT2DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT2DI16.Search(const buff: TKDT2DI16_Vec): PKDT2DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT2DI16.SearchToken(const buff: TKDT2DI16_Vec): TPascalString; var p: PKDT2DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT2DI16.Search(const inBuff: TKDT2DI16_DynamicVecBuffer; var OutBuff: TKDT2DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT2DI16_DynamicVecBuffer; outBuffPtr: PKDT2DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT2DI16_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: PKDT2DI16_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: PKDT2DI16_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 TKDT2DI16.Search(const inBuff: TKDT2DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT2DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT2DI16_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: PKDT2DI16_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: PKDT2DI16_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 TKDT2DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT2DI16_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(TKDT2DI16_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 TKDT2DI16.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 <> KDT2DI16_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(TKDT2DI16_Vec)) <> SizeOf(TKDT2DI16_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 TKDT2DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT2DI16.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 TKDT2DI16.PrintNodeTree(const NodePtr: PKDT2DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT2DI16_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 TKDT2DI16.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 TKDT2DI16.Vec(const s: SystemString): TKDT2DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT2DI16_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 >= KDT2DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT2DI16.Vec(const v: TKDT2DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT2DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT2DI16.Distance(const v1, v2: TKDT2DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT2DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT2DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT2DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT2DI16.Test; var TKDT2DI16_Test: TKDT2DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT2DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT2DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT2DI16_Test := TKDT2DI16.Create; n.Append('...'); SetLength(TKDT2DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT2DI16_Test.TestBuff) - 1 do for j := 0 to KDT2DI16_Axis - 1 do TKDT2DI16_Test.TestBuff[i][j] := i * KDT2DI16_Axis + j; {$IFDEF FPC} TKDT2DI16_Test.BuildKDTreeM(length(TKDT2DI16_Test.TestBuff), nil, @TKDT2DI16_Test.Test_BuildM); {$ELSE FPC} TKDT2DI16_Test.BuildKDTreeM(length(TKDT2DI16_Test.TestBuff), nil, TKDT2DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT2DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT2DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT2DI16_Test.TestBuff) - 1 do begin p := TKDT2DI16_Test.Search(TKDT2DI16_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(TKDT2DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT2DI16_Test.TestBuff)); TKDT2DI16_Test.Search(TKDT2DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT2DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT2DI16_Test.Clear; { kMean test } TKDT2DI16_Test.BuildKDTreeWithCluster(TKDT2DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT2DI16_Test.Search(TKDT2DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT2DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT2DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT2DI16_Test); DoStatus(n); n := ''; end; function TKDT3DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT3DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT3DI16_Node; function SortCompare(const p1, p2: PKDT3DI16_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: PKDT3DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT3DI16_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: PKDT3DI16_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 KDT3DI16_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 TKDT3DI16.GetData(const Index: NativeInt): PKDT3DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT3DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT3DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT3DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT3DI16_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 TKDT3DI16.StoreBuffPtr: PKDT3DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT3DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT3DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT3DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT3DI16.BuildKDTreeWithCluster(const inBuff: TKDT3DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT3DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT3DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT3DI16_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 KDT3DI16_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 TKDT3DI16.BuildKDTreeWithCluster(const inBuff: TKDT3DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT3DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildCall); var TempStoreBuff: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI16_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 KDT3DI16_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 TKDT3DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildMethod); var TempStoreBuff: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI16_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 KDT3DI16_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 TKDT3DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT3DI16_BuildProc); var TempStoreBuff: TKDT3DI16_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(TKDT3DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT3DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT3DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT3DI16_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 KDT3DI16_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 TKDT3DI16.Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT3DI16_Node; var NearestNeighbour: PKDT3DI16_Node; function FindParentNode(const buffPtr: PKDT3DI16_Vec; NodePtr: PKDT3DI16_Node): PKDT3DI16_Node; var Next: PKDT3DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT3DI16_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: PKDT3DI16_Node; const buffPtr: PKDT3DI16_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 KDT3DI16_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: PKDT3DI16_Vec; const p1, p2: PKDT3DI16_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: PKDT3DI16_Vec); var i, j: NativeInt; p, t: PKDT3DI16_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: PKDT3DI16_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 := PKDT3DI16_Node(NearestNodes[0]); end; end; function TKDT3DI16.Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT3DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT3DI16.Search(const buff: TKDT3DI16_Vec; var SearchedDistanceMin: Double): PKDT3DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT3DI16.Search(const buff: TKDT3DI16_Vec): PKDT3DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT3DI16.SearchToken(const buff: TKDT3DI16_Vec): TPascalString; var p: PKDT3DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT3DI16.Search(const inBuff: TKDT3DI16_DynamicVecBuffer; var OutBuff: TKDT3DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT3DI16_DynamicVecBuffer; outBuffPtr: PKDT3DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT3DI16_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: PKDT3DI16_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: PKDT3DI16_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 TKDT3DI16.Search(const inBuff: TKDT3DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT3DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT3DI16_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: PKDT3DI16_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: PKDT3DI16_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 TKDT3DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT3DI16_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(TKDT3DI16_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 TKDT3DI16.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 <> KDT3DI16_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(TKDT3DI16_Vec)) <> SizeOf(TKDT3DI16_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 TKDT3DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT3DI16.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 TKDT3DI16.PrintNodeTree(const NodePtr: PKDT3DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT3DI16_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 TKDT3DI16.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 TKDT3DI16.Vec(const s: SystemString): TKDT3DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT3DI16_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 >= KDT3DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT3DI16.Vec(const v: TKDT3DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT3DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT3DI16.Distance(const v1, v2: TKDT3DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT3DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT3DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT3DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT3DI16.Test; var TKDT3DI16_Test: TKDT3DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT3DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT3DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT3DI16_Test := TKDT3DI16.Create; n.Append('...'); SetLength(TKDT3DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT3DI16_Test.TestBuff) - 1 do for j := 0 to KDT3DI16_Axis - 1 do TKDT3DI16_Test.TestBuff[i][j] := i * KDT3DI16_Axis + j; {$IFDEF FPC} TKDT3DI16_Test.BuildKDTreeM(length(TKDT3DI16_Test.TestBuff), nil, @TKDT3DI16_Test.Test_BuildM); {$ELSE FPC} TKDT3DI16_Test.BuildKDTreeM(length(TKDT3DI16_Test.TestBuff), nil, TKDT3DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT3DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT3DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT3DI16_Test.TestBuff) - 1 do begin p := TKDT3DI16_Test.Search(TKDT3DI16_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(TKDT3DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT3DI16_Test.TestBuff)); TKDT3DI16_Test.Search(TKDT3DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT3DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT3DI16_Test.Clear; { kMean test } TKDT3DI16_Test.BuildKDTreeWithCluster(TKDT3DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT3DI16_Test.Search(TKDT3DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT3DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT3DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT3DI16_Test); DoStatus(n); n := ''; end; function TKDT4DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT4DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT4DI16_Node; function SortCompare(const p1, p2: PKDT4DI16_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: PKDT4DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT4DI16_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: PKDT4DI16_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 KDT4DI16_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 TKDT4DI16.GetData(const Index: NativeInt): PKDT4DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT4DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT4DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT4DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT4DI16_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 TKDT4DI16.StoreBuffPtr: PKDT4DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT4DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT4DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT4DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT4DI16.BuildKDTreeWithCluster(const inBuff: TKDT4DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT4DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT4DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT4DI16_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 KDT4DI16_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 TKDT4DI16.BuildKDTreeWithCluster(const inBuff: TKDT4DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT4DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildCall); var TempStoreBuff: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI16_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 KDT4DI16_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 TKDT4DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildMethod); var TempStoreBuff: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI16_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 KDT4DI16_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 TKDT4DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT4DI16_BuildProc); var TempStoreBuff: TKDT4DI16_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(TKDT4DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT4DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT4DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT4DI16_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 KDT4DI16_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 TKDT4DI16.Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT4DI16_Node; var NearestNeighbour: PKDT4DI16_Node; function FindParentNode(const buffPtr: PKDT4DI16_Vec; NodePtr: PKDT4DI16_Node): PKDT4DI16_Node; var Next: PKDT4DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT4DI16_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: PKDT4DI16_Node; const buffPtr: PKDT4DI16_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 KDT4DI16_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: PKDT4DI16_Vec; const p1, p2: PKDT4DI16_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: PKDT4DI16_Vec); var i, j: NativeInt; p, t: PKDT4DI16_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: PKDT4DI16_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 := PKDT4DI16_Node(NearestNodes[0]); end; end; function TKDT4DI16.Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT4DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT4DI16.Search(const buff: TKDT4DI16_Vec; var SearchedDistanceMin: Double): PKDT4DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT4DI16.Search(const buff: TKDT4DI16_Vec): PKDT4DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT4DI16.SearchToken(const buff: TKDT4DI16_Vec): TPascalString; var p: PKDT4DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT4DI16.Search(const inBuff: TKDT4DI16_DynamicVecBuffer; var OutBuff: TKDT4DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT4DI16_DynamicVecBuffer; outBuffPtr: PKDT4DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT4DI16_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: PKDT4DI16_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: PKDT4DI16_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 TKDT4DI16.Search(const inBuff: TKDT4DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT4DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT4DI16_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: PKDT4DI16_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: PKDT4DI16_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 TKDT4DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT4DI16_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(TKDT4DI16_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 TKDT4DI16.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 <> KDT4DI16_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(TKDT4DI16_Vec)) <> SizeOf(TKDT4DI16_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 TKDT4DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT4DI16.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 TKDT4DI16.PrintNodeTree(const NodePtr: PKDT4DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT4DI16_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 TKDT4DI16.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 TKDT4DI16.Vec(const s: SystemString): TKDT4DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT4DI16_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 >= KDT4DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT4DI16.Vec(const v: TKDT4DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT4DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT4DI16.Distance(const v1, v2: TKDT4DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT4DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT4DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT4DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT4DI16.Test; var TKDT4DI16_Test: TKDT4DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT4DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT4DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT4DI16_Test := TKDT4DI16.Create; n.Append('...'); SetLength(TKDT4DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT4DI16_Test.TestBuff) - 1 do for j := 0 to KDT4DI16_Axis - 1 do TKDT4DI16_Test.TestBuff[i][j] := i * KDT4DI16_Axis + j; {$IFDEF FPC} TKDT4DI16_Test.BuildKDTreeM(length(TKDT4DI16_Test.TestBuff), nil, @TKDT4DI16_Test.Test_BuildM); {$ELSE FPC} TKDT4DI16_Test.BuildKDTreeM(length(TKDT4DI16_Test.TestBuff), nil, TKDT4DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT4DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT4DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT4DI16_Test.TestBuff) - 1 do begin p := TKDT4DI16_Test.Search(TKDT4DI16_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(TKDT4DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT4DI16_Test.TestBuff)); TKDT4DI16_Test.Search(TKDT4DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT4DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT4DI16_Test.Clear; { kMean test } TKDT4DI16_Test.BuildKDTreeWithCluster(TKDT4DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT4DI16_Test.Search(TKDT4DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT4DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT4DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT4DI16_Test); DoStatus(n); n := ''; end; function TKDT5DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT5DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT5DI16_Node; function SortCompare(const p1, p2: PKDT5DI16_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: PKDT5DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT5DI16_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: PKDT5DI16_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 KDT5DI16_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 TKDT5DI16.GetData(const Index: NativeInt): PKDT5DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT5DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT5DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT5DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT5DI16_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 TKDT5DI16.StoreBuffPtr: PKDT5DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT5DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT5DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT5DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT5DI16.BuildKDTreeWithCluster(const inBuff: TKDT5DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT5DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT5DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT5DI16_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 KDT5DI16_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 TKDT5DI16.BuildKDTreeWithCluster(const inBuff: TKDT5DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT5DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildCall); var TempStoreBuff: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI16_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 KDT5DI16_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 TKDT5DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildMethod); var TempStoreBuff: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI16_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 KDT5DI16_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 TKDT5DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT5DI16_BuildProc); var TempStoreBuff: TKDT5DI16_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(TKDT5DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT5DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT5DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT5DI16_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 KDT5DI16_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 TKDT5DI16.Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT5DI16_Node; var NearestNeighbour: PKDT5DI16_Node; function FindParentNode(const buffPtr: PKDT5DI16_Vec; NodePtr: PKDT5DI16_Node): PKDT5DI16_Node; var Next: PKDT5DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT5DI16_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: PKDT5DI16_Node; const buffPtr: PKDT5DI16_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 KDT5DI16_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: PKDT5DI16_Vec; const p1, p2: PKDT5DI16_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: PKDT5DI16_Vec); var i, j: NativeInt; p, t: PKDT5DI16_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: PKDT5DI16_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 := PKDT5DI16_Node(NearestNodes[0]); end; end; function TKDT5DI16.Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT5DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT5DI16.Search(const buff: TKDT5DI16_Vec; var SearchedDistanceMin: Double): PKDT5DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT5DI16.Search(const buff: TKDT5DI16_Vec): PKDT5DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT5DI16.SearchToken(const buff: TKDT5DI16_Vec): TPascalString; var p: PKDT5DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT5DI16.Search(const inBuff: TKDT5DI16_DynamicVecBuffer; var OutBuff: TKDT5DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT5DI16_DynamicVecBuffer; outBuffPtr: PKDT5DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT5DI16_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: PKDT5DI16_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: PKDT5DI16_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 TKDT5DI16.Search(const inBuff: TKDT5DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT5DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT5DI16_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: PKDT5DI16_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: PKDT5DI16_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 TKDT5DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT5DI16_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(TKDT5DI16_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 TKDT5DI16.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 <> KDT5DI16_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(TKDT5DI16_Vec)) <> SizeOf(TKDT5DI16_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 TKDT5DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT5DI16.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 TKDT5DI16.PrintNodeTree(const NodePtr: PKDT5DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT5DI16_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 TKDT5DI16.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 TKDT5DI16.Vec(const s: SystemString): TKDT5DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT5DI16_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 >= KDT5DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT5DI16.Vec(const v: TKDT5DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT5DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT5DI16.Distance(const v1, v2: TKDT5DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT5DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT5DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT5DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT5DI16.Test; var TKDT5DI16_Test: TKDT5DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT5DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT5DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT5DI16_Test := TKDT5DI16.Create; n.Append('...'); SetLength(TKDT5DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT5DI16_Test.TestBuff) - 1 do for j := 0 to KDT5DI16_Axis - 1 do TKDT5DI16_Test.TestBuff[i][j] := i * KDT5DI16_Axis + j; {$IFDEF FPC} TKDT5DI16_Test.BuildKDTreeM(length(TKDT5DI16_Test.TestBuff), nil, @TKDT5DI16_Test.Test_BuildM); {$ELSE FPC} TKDT5DI16_Test.BuildKDTreeM(length(TKDT5DI16_Test.TestBuff), nil, TKDT5DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT5DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT5DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT5DI16_Test.TestBuff) - 1 do begin p := TKDT5DI16_Test.Search(TKDT5DI16_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(TKDT5DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT5DI16_Test.TestBuff)); TKDT5DI16_Test.Search(TKDT5DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT5DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT5DI16_Test.Clear; { kMean test } TKDT5DI16_Test.BuildKDTreeWithCluster(TKDT5DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT5DI16_Test.Search(TKDT5DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT5DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT5DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT5DI16_Test); DoStatus(n); n := ''; end; function TKDT6DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT6DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT6DI16_Node; function SortCompare(const p1, p2: PKDT6DI16_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: PKDT6DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT6DI16_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: PKDT6DI16_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 KDT6DI16_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 TKDT6DI16.GetData(const Index: NativeInt): PKDT6DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT6DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT6DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT6DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT6DI16_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 TKDT6DI16.StoreBuffPtr: PKDT6DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT6DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT6DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT6DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT6DI16.BuildKDTreeWithCluster(const inBuff: TKDT6DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT6DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT6DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT6DI16_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 KDT6DI16_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 TKDT6DI16.BuildKDTreeWithCluster(const inBuff: TKDT6DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT6DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildCall); var TempStoreBuff: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI16_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 KDT6DI16_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 TKDT6DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildMethod); var TempStoreBuff: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI16_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 KDT6DI16_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 TKDT6DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT6DI16_BuildProc); var TempStoreBuff: TKDT6DI16_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(TKDT6DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT6DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT6DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT6DI16_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 KDT6DI16_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 TKDT6DI16.Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT6DI16_Node; var NearestNeighbour: PKDT6DI16_Node; function FindParentNode(const buffPtr: PKDT6DI16_Vec; NodePtr: PKDT6DI16_Node): PKDT6DI16_Node; var Next: PKDT6DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT6DI16_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: PKDT6DI16_Node; const buffPtr: PKDT6DI16_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 KDT6DI16_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: PKDT6DI16_Vec; const p1, p2: PKDT6DI16_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: PKDT6DI16_Vec); var i, j: NativeInt; p, t: PKDT6DI16_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: PKDT6DI16_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 := PKDT6DI16_Node(NearestNodes[0]); end; end; function TKDT6DI16.Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT6DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT6DI16.Search(const buff: TKDT6DI16_Vec; var SearchedDistanceMin: Double): PKDT6DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT6DI16.Search(const buff: TKDT6DI16_Vec): PKDT6DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT6DI16.SearchToken(const buff: TKDT6DI16_Vec): TPascalString; var p: PKDT6DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT6DI16.Search(const inBuff: TKDT6DI16_DynamicVecBuffer; var OutBuff: TKDT6DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT6DI16_DynamicVecBuffer; outBuffPtr: PKDT6DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT6DI16_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: PKDT6DI16_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: PKDT6DI16_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 TKDT6DI16.Search(const inBuff: TKDT6DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT6DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT6DI16_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: PKDT6DI16_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: PKDT6DI16_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 TKDT6DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT6DI16_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(TKDT6DI16_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 TKDT6DI16.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 <> KDT6DI16_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(TKDT6DI16_Vec)) <> SizeOf(TKDT6DI16_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 TKDT6DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT6DI16.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 TKDT6DI16.PrintNodeTree(const NodePtr: PKDT6DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT6DI16_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 TKDT6DI16.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 TKDT6DI16.Vec(const s: SystemString): TKDT6DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT6DI16_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 >= KDT6DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT6DI16.Vec(const v: TKDT6DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT6DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT6DI16.Distance(const v1, v2: TKDT6DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT6DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT6DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT6DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT6DI16.Test; var TKDT6DI16_Test: TKDT6DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT6DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT6DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT6DI16_Test := TKDT6DI16.Create; n.Append('...'); SetLength(TKDT6DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT6DI16_Test.TestBuff) - 1 do for j := 0 to KDT6DI16_Axis - 1 do TKDT6DI16_Test.TestBuff[i][j] := i * KDT6DI16_Axis + j; {$IFDEF FPC} TKDT6DI16_Test.BuildKDTreeM(length(TKDT6DI16_Test.TestBuff), nil, @TKDT6DI16_Test.Test_BuildM); {$ELSE FPC} TKDT6DI16_Test.BuildKDTreeM(length(TKDT6DI16_Test.TestBuff), nil, TKDT6DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT6DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT6DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT6DI16_Test.TestBuff) - 1 do begin p := TKDT6DI16_Test.Search(TKDT6DI16_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(TKDT6DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT6DI16_Test.TestBuff)); TKDT6DI16_Test.Search(TKDT6DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT6DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT6DI16_Test.Clear; { kMean test } TKDT6DI16_Test.BuildKDTreeWithCluster(TKDT6DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT6DI16_Test.Search(TKDT6DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT6DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT6DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT6DI16_Test); DoStatus(n); n := ''; end; function TKDT7DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT7DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT7DI16_Node; function SortCompare(const p1, p2: PKDT7DI16_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: PKDT7DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT7DI16_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: PKDT7DI16_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 KDT7DI16_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 TKDT7DI16.GetData(const Index: NativeInt): PKDT7DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT7DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT7DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT7DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT7DI16_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 TKDT7DI16.StoreBuffPtr: PKDT7DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT7DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT7DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT7DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT7DI16.BuildKDTreeWithCluster(const inBuff: TKDT7DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT7DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT7DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT7DI16_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 KDT7DI16_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 TKDT7DI16.BuildKDTreeWithCluster(const inBuff: TKDT7DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT7DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildCall); var TempStoreBuff: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI16_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 KDT7DI16_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 TKDT7DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildMethod); var TempStoreBuff: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI16_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 KDT7DI16_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 TKDT7DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT7DI16_BuildProc); var TempStoreBuff: TKDT7DI16_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(TKDT7DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT7DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT7DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT7DI16_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 KDT7DI16_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 TKDT7DI16.Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT7DI16_Node; var NearestNeighbour: PKDT7DI16_Node; function FindParentNode(const buffPtr: PKDT7DI16_Vec; NodePtr: PKDT7DI16_Node): PKDT7DI16_Node; var Next: PKDT7DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT7DI16_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: PKDT7DI16_Node; const buffPtr: PKDT7DI16_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 KDT7DI16_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: PKDT7DI16_Vec; const p1, p2: PKDT7DI16_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: PKDT7DI16_Vec); var i, j: NativeInt; p, t: PKDT7DI16_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: PKDT7DI16_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 := PKDT7DI16_Node(NearestNodes[0]); end; end; function TKDT7DI16.Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT7DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT7DI16.Search(const buff: TKDT7DI16_Vec; var SearchedDistanceMin: Double): PKDT7DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT7DI16.Search(const buff: TKDT7DI16_Vec): PKDT7DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT7DI16.SearchToken(const buff: TKDT7DI16_Vec): TPascalString; var p: PKDT7DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT7DI16.Search(const inBuff: TKDT7DI16_DynamicVecBuffer; var OutBuff: TKDT7DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT7DI16_DynamicVecBuffer; outBuffPtr: PKDT7DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT7DI16_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: PKDT7DI16_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: PKDT7DI16_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 TKDT7DI16.Search(const inBuff: TKDT7DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT7DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT7DI16_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: PKDT7DI16_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: PKDT7DI16_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 TKDT7DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT7DI16_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(TKDT7DI16_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 TKDT7DI16.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 <> KDT7DI16_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(TKDT7DI16_Vec)) <> SizeOf(TKDT7DI16_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 TKDT7DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT7DI16.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 TKDT7DI16.PrintNodeTree(const NodePtr: PKDT7DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT7DI16_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 TKDT7DI16.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 TKDT7DI16.Vec(const s: SystemString): TKDT7DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT7DI16_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 >= KDT7DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT7DI16.Vec(const v: TKDT7DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT7DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT7DI16.Distance(const v1, v2: TKDT7DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT7DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT7DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT7DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT7DI16.Test; var TKDT7DI16_Test: TKDT7DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT7DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT7DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT7DI16_Test := TKDT7DI16.Create; n.Append('...'); SetLength(TKDT7DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT7DI16_Test.TestBuff) - 1 do for j := 0 to KDT7DI16_Axis - 1 do TKDT7DI16_Test.TestBuff[i][j] := i * KDT7DI16_Axis + j; {$IFDEF FPC} TKDT7DI16_Test.BuildKDTreeM(length(TKDT7DI16_Test.TestBuff), nil, @TKDT7DI16_Test.Test_BuildM); {$ELSE FPC} TKDT7DI16_Test.BuildKDTreeM(length(TKDT7DI16_Test.TestBuff), nil, TKDT7DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT7DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT7DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT7DI16_Test.TestBuff) - 1 do begin p := TKDT7DI16_Test.Search(TKDT7DI16_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(TKDT7DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT7DI16_Test.TestBuff)); TKDT7DI16_Test.Search(TKDT7DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT7DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT7DI16_Test.Clear; { kMean test } TKDT7DI16_Test.BuildKDTreeWithCluster(TKDT7DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT7DI16_Test.Search(TKDT7DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT7DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT7DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT7DI16_Test); DoStatus(n); n := ''; end; function TKDT8DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT8DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT8DI16_Node; function SortCompare(const p1, p2: PKDT8DI16_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: PKDT8DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT8DI16_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: PKDT8DI16_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 KDT8DI16_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 TKDT8DI16.GetData(const Index: NativeInt): PKDT8DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT8DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT8DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT8DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT8DI16_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 TKDT8DI16.StoreBuffPtr: PKDT8DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT8DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT8DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT8DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT8DI16.BuildKDTreeWithCluster(const inBuff: TKDT8DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT8DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT8DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT8DI16_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 KDT8DI16_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 TKDT8DI16.BuildKDTreeWithCluster(const inBuff: TKDT8DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT8DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildCall); var TempStoreBuff: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI16_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 KDT8DI16_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 TKDT8DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildMethod); var TempStoreBuff: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI16_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 KDT8DI16_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 TKDT8DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT8DI16_BuildProc); var TempStoreBuff: TKDT8DI16_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(TKDT8DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT8DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT8DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT8DI16_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 KDT8DI16_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 TKDT8DI16.Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT8DI16_Node; var NearestNeighbour: PKDT8DI16_Node; function FindParentNode(const buffPtr: PKDT8DI16_Vec; NodePtr: PKDT8DI16_Node): PKDT8DI16_Node; var Next: PKDT8DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT8DI16_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: PKDT8DI16_Node; const buffPtr: PKDT8DI16_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 KDT8DI16_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: PKDT8DI16_Vec; const p1, p2: PKDT8DI16_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: PKDT8DI16_Vec); var i, j: NativeInt; p, t: PKDT8DI16_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: PKDT8DI16_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 := PKDT8DI16_Node(NearestNodes[0]); end; end; function TKDT8DI16.Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT8DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT8DI16.Search(const buff: TKDT8DI16_Vec; var SearchedDistanceMin: Double): PKDT8DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT8DI16.Search(const buff: TKDT8DI16_Vec): PKDT8DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT8DI16.SearchToken(const buff: TKDT8DI16_Vec): TPascalString; var p: PKDT8DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT8DI16.Search(const inBuff: TKDT8DI16_DynamicVecBuffer; var OutBuff: TKDT8DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT8DI16_DynamicVecBuffer; outBuffPtr: PKDT8DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT8DI16_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: PKDT8DI16_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: PKDT8DI16_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 TKDT8DI16.Search(const inBuff: TKDT8DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT8DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT8DI16_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: PKDT8DI16_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: PKDT8DI16_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 TKDT8DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT8DI16_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(TKDT8DI16_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 TKDT8DI16.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 <> KDT8DI16_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(TKDT8DI16_Vec)) <> SizeOf(TKDT8DI16_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 TKDT8DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT8DI16.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 TKDT8DI16.PrintNodeTree(const NodePtr: PKDT8DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT8DI16_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 TKDT8DI16.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 TKDT8DI16.Vec(const s: SystemString): TKDT8DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT8DI16_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 >= KDT8DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT8DI16.Vec(const v: TKDT8DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT8DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT8DI16.Distance(const v1, v2: TKDT8DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT8DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT8DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT8DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT8DI16.Test; var TKDT8DI16_Test: TKDT8DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT8DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT8DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT8DI16_Test := TKDT8DI16.Create; n.Append('...'); SetLength(TKDT8DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT8DI16_Test.TestBuff) - 1 do for j := 0 to KDT8DI16_Axis - 1 do TKDT8DI16_Test.TestBuff[i][j] := i * KDT8DI16_Axis + j; {$IFDEF FPC} TKDT8DI16_Test.BuildKDTreeM(length(TKDT8DI16_Test.TestBuff), nil, @TKDT8DI16_Test.Test_BuildM); {$ELSE FPC} TKDT8DI16_Test.BuildKDTreeM(length(TKDT8DI16_Test.TestBuff), nil, TKDT8DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT8DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT8DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT8DI16_Test.TestBuff) - 1 do begin p := TKDT8DI16_Test.Search(TKDT8DI16_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(TKDT8DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT8DI16_Test.TestBuff)); TKDT8DI16_Test.Search(TKDT8DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT8DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT8DI16_Test.Clear; { kMean test } TKDT8DI16_Test.BuildKDTreeWithCluster(TKDT8DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT8DI16_Test.Search(TKDT8DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT8DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT8DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT8DI16_Test); DoStatus(n); n := ''; end; function TKDT9DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT9DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT9DI16_Node; function SortCompare(const p1, p2: PKDT9DI16_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: PKDT9DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT9DI16_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: PKDT9DI16_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 KDT9DI16_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 TKDT9DI16.GetData(const Index: NativeInt): PKDT9DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT9DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT9DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT9DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT9DI16_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 TKDT9DI16.StoreBuffPtr: PKDT9DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT9DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT9DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT9DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT9DI16.BuildKDTreeWithCluster(const inBuff: TKDT9DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT9DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT9DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT9DI16_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 KDT9DI16_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 TKDT9DI16.BuildKDTreeWithCluster(const inBuff: TKDT9DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT9DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildCall); var TempStoreBuff: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI16_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 KDT9DI16_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 TKDT9DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildMethod); var TempStoreBuff: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI16_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 KDT9DI16_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 TKDT9DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT9DI16_BuildProc); var TempStoreBuff: TKDT9DI16_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(TKDT9DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT9DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT9DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT9DI16_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 KDT9DI16_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 TKDT9DI16.Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT9DI16_Node; var NearestNeighbour: PKDT9DI16_Node; function FindParentNode(const buffPtr: PKDT9DI16_Vec; NodePtr: PKDT9DI16_Node): PKDT9DI16_Node; var Next: PKDT9DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT9DI16_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: PKDT9DI16_Node; const buffPtr: PKDT9DI16_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 KDT9DI16_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: PKDT9DI16_Vec; const p1, p2: PKDT9DI16_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: PKDT9DI16_Vec); var i, j: NativeInt; p, t: PKDT9DI16_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: PKDT9DI16_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 := PKDT9DI16_Node(NearestNodes[0]); end; end; function TKDT9DI16.Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT9DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT9DI16.Search(const buff: TKDT9DI16_Vec; var SearchedDistanceMin: Double): PKDT9DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT9DI16.Search(const buff: TKDT9DI16_Vec): PKDT9DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT9DI16.SearchToken(const buff: TKDT9DI16_Vec): TPascalString; var p: PKDT9DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT9DI16.Search(const inBuff: TKDT9DI16_DynamicVecBuffer; var OutBuff: TKDT9DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT9DI16_DynamicVecBuffer; outBuffPtr: PKDT9DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT9DI16_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: PKDT9DI16_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: PKDT9DI16_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 TKDT9DI16.Search(const inBuff: TKDT9DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT9DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT9DI16_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: PKDT9DI16_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: PKDT9DI16_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 TKDT9DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT9DI16_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(TKDT9DI16_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 TKDT9DI16.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 <> KDT9DI16_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(TKDT9DI16_Vec)) <> SizeOf(TKDT9DI16_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 TKDT9DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT9DI16.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 TKDT9DI16.PrintNodeTree(const NodePtr: PKDT9DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT9DI16_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 TKDT9DI16.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 TKDT9DI16.Vec(const s: SystemString): TKDT9DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT9DI16_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 >= KDT9DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT9DI16.Vec(const v: TKDT9DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT9DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT9DI16.Distance(const v1, v2: TKDT9DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT9DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT9DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT9DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT9DI16.Test; var TKDT9DI16_Test: TKDT9DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT9DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT9DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT9DI16_Test := TKDT9DI16.Create; n.Append('...'); SetLength(TKDT9DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT9DI16_Test.TestBuff) - 1 do for j := 0 to KDT9DI16_Axis - 1 do TKDT9DI16_Test.TestBuff[i][j] := i * KDT9DI16_Axis + j; {$IFDEF FPC} TKDT9DI16_Test.BuildKDTreeM(length(TKDT9DI16_Test.TestBuff), nil, @TKDT9DI16_Test.Test_BuildM); {$ELSE FPC} TKDT9DI16_Test.BuildKDTreeM(length(TKDT9DI16_Test.TestBuff), nil, TKDT9DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT9DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT9DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT9DI16_Test.TestBuff) - 1 do begin p := TKDT9DI16_Test.Search(TKDT9DI16_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(TKDT9DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT9DI16_Test.TestBuff)); TKDT9DI16_Test.Search(TKDT9DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT9DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT9DI16_Test.Clear; { kMean test } TKDT9DI16_Test.BuildKDTreeWithCluster(TKDT9DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT9DI16_Test.Search(TKDT9DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT9DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT9DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT9DI16_Test); DoStatus(n); n := ''; end; function TKDT10DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT10DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT10DI16_Node; function SortCompare(const p1, p2: PKDT10DI16_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: PKDT10DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT10DI16_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: PKDT10DI16_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 KDT10DI16_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 TKDT10DI16.GetData(const Index: NativeInt): PKDT10DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT10DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT10DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT10DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT10DI16_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 TKDT10DI16.StoreBuffPtr: PKDT10DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT10DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT10DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT10DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT10DI16.BuildKDTreeWithCluster(const inBuff: TKDT10DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT10DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT10DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT10DI16_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 KDT10DI16_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 TKDT10DI16.BuildKDTreeWithCluster(const inBuff: TKDT10DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT10DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildCall); var TempStoreBuff: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI16_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 KDT10DI16_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 TKDT10DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildMethod); var TempStoreBuff: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI16_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 KDT10DI16_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 TKDT10DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT10DI16_BuildProc); var TempStoreBuff: TKDT10DI16_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(TKDT10DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT10DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT10DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT10DI16_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 KDT10DI16_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 TKDT10DI16.Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT10DI16_Node; var NearestNeighbour: PKDT10DI16_Node; function FindParentNode(const buffPtr: PKDT10DI16_Vec; NodePtr: PKDT10DI16_Node): PKDT10DI16_Node; var Next: PKDT10DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT10DI16_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: PKDT10DI16_Node; const buffPtr: PKDT10DI16_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 KDT10DI16_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: PKDT10DI16_Vec; const p1, p2: PKDT10DI16_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: PKDT10DI16_Vec); var i, j: NativeInt; p, t: PKDT10DI16_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: PKDT10DI16_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 := PKDT10DI16_Node(NearestNodes[0]); end; end; function TKDT10DI16.Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT10DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT10DI16.Search(const buff: TKDT10DI16_Vec; var SearchedDistanceMin: Double): PKDT10DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT10DI16.Search(const buff: TKDT10DI16_Vec): PKDT10DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT10DI16.SearchToken(const buff: TKDT10DI16_Vec): TPascalString; var p: PKDT10DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT10DI16.Search(const inBuff: TKDT10DI16_DynamicVecBuffer; var OutBuff: TKDT10DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT10DI16_DynamicVecBuffer; outBuffPtr: PKDT10DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT10DI16_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: PKDT10DI16_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: PKDT10DI16_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 TKDT10DI16.Search(const inBuff: TKDT10DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT10DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT10DI16_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: PKDT10DI16_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: PKDT10DI16_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 TKDT10DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT10DI16_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(TKDT10DI16_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 TKDT10DI16.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 <> KDT10DI16_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(TKDT10DI16_Vec)) <> SizeOf(TKDT10DI16_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 TKDT10DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT10DI16.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 TKDT10DI16.PrintNodeTree(const NodePtr: PKDT10DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT10DI16_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 TKDT10DI16.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 TKDT10DI16.Vec(const s: SystemString): TKDT10DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT10DI16_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 >= KDT10DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT10DI16.Vec(const v: TKDT10DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT10DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT10DI16.Distance(const v1, v2: TKDT10DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT10DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT10DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT10DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT10DI16.Test; var TKDT10DI16_Test: TKDT10DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT10DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT10DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT10DI16_Test := TKDT10DI16.Create; n.Append('...'); SetLength(TKDT10DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT10DI16_Test.TestBuff) - 1 do for j := 0 to KDT10DI16_Axis - 1 do TKDT10DI16_Test.TestBuff[i][j] := i * KDT10DI16_Axis + j; {$IFDEF FPC} TKDT10DI16_Test.BuildKDTreeM(length(TKDT10DI16_Test.TestBuff), nil, @TKDT10DI16_Test.Test_BuildM); {$ELSE FPC} TKDT10DI16_Test.BuildKDTreeM(length(TKDT10DI16_Test.TestBuff), nil, TKDT10DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT10DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT10DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT10DI16_Test.TestBuff) - 1 do begin p := TKDT10DI16_Test.Search(TKDT10DI16_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(TKDT10DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT10DI16_Test.TestBuff)); TKDT10DI16_Test.Search(TKDT10DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT10DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT10DI16_Test.Clear; { kMean test } TKDT10DI16_Test.BuildKDTreeWithCluster(TKDT10DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT10DI16_Test.Search(TKDT10DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT10DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT10DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT10DI16_Test); DoStatus(n); n := ''; end; function TKDT11DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT11DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT11DI16_Node; function SortCompare(const p1, p2: PKDT11DI16_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: PKDT11DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT11DI16_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: PKDT11DI16_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 KDT11DI16_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 TKDT11DI16.GetData(const Index: NativeInt): PKDT11DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT11DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT11DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT11DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT11DI16_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 TKDT11DI16.StoreBuffPtr: PKDT11DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT11DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT11DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT11DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT11DI16.BuildKDTreeWithCluster(const inBuff: TKDT11DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT11DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT11DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT11DI16_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 KDT11DI16_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 TKDT11DI16.BuildKDTreeWithCluster(const inBuff: TKDT11DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT11DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildCall); var TempStoreBuff: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI16_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 KDT11DI16_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 TKDT11DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildMethod); var TempStoreBuff: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI16_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 KDT11DI16_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 TKDT11DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT11DI16_BuildProc); var TempStoreBuff: TKDT11DI16_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(TKDT11DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT11DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT11DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT11DI16_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 KDT11DI16_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 TKDT11DI16.Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT11DI16_Node; var NearestNeighbour: PKDT11DI16_Node; function FindParentNode(const buffPtr: PKDT11DI16_Vec; NodePtr: PKDT11DI16_Node): PKDT11DI16_Node; var Next: PKDT11DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT11DI16_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: PKDT11DI16_Node; const buffPtr: PKDT11DI16_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 KDT11DI16_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: PKDT11DI16_Vec; const p1, p2: PKDT11DI16_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: PKDT11DI16_Vec); var i, j: NativeInt; p, t: PKDT11DI16_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: PKDT11DI16_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 := PKDT11DI16_Node(NearestNodes[0]); end; end; function TKDT11DI16.Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT11DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT11DI16.Search(const buff: TKDT11DI16_Vec; var SearchedDistanceMin: Double): PKDT11DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT11DI16.Search(const buff: TKDT11DI16_Vec): PKDT11DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT11DI16.SearchToken(const buff: TKDT11DI16_Vec): TPascalString; var p: PKDT11DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT11DI16.Search(const inBuff: TKDT11DI16_DynamicVecBuffer; var OutBuff: TKDT11DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT11DI16_DynamicVecBuffer; outBuffPtr: PKDT11DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT11DI16_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: PKDT11DI16_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: PKDT11DI16_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 TKDT11DI16.Search(const inBuff: TKDT11DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT11DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT11DI16_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: PKDT11DI16_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: PKDT11DI16_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 TKDT11DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT11DI16_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(TKDT11DI16_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 TKDT11DI16.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 <> KDT11DI16_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(TKDT11DI16_Vec)) <> SizeOf(TKDT11DI16_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 TKDT11DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT11DI16.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 TKDT11DI16.PrintNodeTree(const NodePtr: PKDT11DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT11DI16_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 TKDT11DI16.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 TKDT11DI16.Vec(const s: SystemString): TKDT11DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT11DI16_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 >= KDT11DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT11DI16.Vec(const v: TKDT11DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT11DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT11DI16.Distance(const v1, v2: TKDT11DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT11DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT11DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT11DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT11DI16.Test; var TKDT11DI16_Test: TKDT11DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT11DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT11DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT11DI16_Test := TKDT11DI16.Create; n.Append('...'); SetLength(TKDT11DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT11DI16_Test.TestBuff) - 1 do for j := 0 to KDT11DI16_Axis - 1 do TKDT11DI16_Test.TestBuff[i][j] := i * KDT11DI16_Axis + j; {$IFDEF FPC} TKDT11DI16_Test.BuildKDTreeM(length(TKDT11DI16_Test.TestBuff), nil, @TKDT11DI16_Test.Test_BuildM); {$ELSE FPC} TKDT11DI16_Test.BuildKDTreeM(length(TKDT11DI16_Test.TestBuff), nil, TKDT11DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT11DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT11DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT11DI16_Test.TestBuff) - 1 do begin p := TKDT11DI16_Test.Search(TKDT11DI16_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(TKDT11DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT11DI16_Test.TestBuff)); TKDT11DI16_Test.Search(TKDT11DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT11DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT11DI16_Test.Clear; { kMean test } TKDT11DI16_Test.BuildKDTreeWithCluster(TKDT11DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT11DI16_Test.Search(TKDT11DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT11DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT11DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT11DI16_Test); DoStatus(n); n := ''; end; function TKDT12DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT12DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT12DI16_Node; function SortCompare(const p1, p2: PKDT12DI16_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: PKDT12DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT12DI16_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: PKDT12DI16_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 KDT12DI16_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 TKDT12DI16.GetData(const Index: NativeInt): PKDT12DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT12DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT12DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT12DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT12DI16_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 TKDT12DI16.StoreBuffPtr: PKDT12DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT12DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT12DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT12DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT12DI16.BuildKDTreeWithCluster(const inBuff: TKDT12DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT12DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT12DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT12DI16_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 KDT12DI16_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 TKDT12DI16.BuildKDTreeWithCluster(const inBuff: TKDT12DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT12DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildCall); var TempStoreBuff: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI16_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 KDT12DI16_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 TKDT12DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildMethod); var TempStoreBuff: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI16_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 KDT12DI16_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 TKDT12DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT12DI16_BuildProc); var TempStoreBuff: TKDT12DI16_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(TKDT12DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT12DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT12DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT12DI16_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 KDT12DI16_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 TKDT12DI16.Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT12DI16_Node; var NearestNeighbour: PKDT12DI16_Node; function FindParentNode(const buffPtr: PKDT12DI16_Vec; NodePtr: PKDT12DI16_Node): PKDT12DI16_Node; var Next: PKDT12DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT12DI16_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: PKDT12DI16_Node; const buffPtr: PKDT12DI16_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 KDT12DI16_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: PKDT12DI16_Vec; const p1, p2: PKDT12DI16_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: PKDT12DI16_Vec); var i, j: NativeInt; p, t: PKDT12DI16_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: PKDT12DI16_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 := PKDT12DI16_Node(NearestNodes[0]); end; end; function TKDT12DI16.Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT12DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT12DI16.Search(const buff: TKDT12DI16_Vec; var SearchedDistanceMin: Double): PKDT12DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT12DI16.Search(const buff: TKDT12DI16_Vec): PKDT12DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT12DI16.SearchToken(const buff: TKDT12DI16_Vec): TPascalString; var p: PKDT12DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT12DI16.Search(const inBuff: TKDT12DI16_DynamicVecBuffer; var OutBuff: TKDT12DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT12DI16_DynamicVecBuffer; outBuffPtr: PKDT12DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT12DI16_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: PKDT12DI16_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: PKDT12DI16_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 TKDT12DI16.Search(const inBuff: TKDT12DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT12DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT12DI16_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: PKDT12DI16_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: PKDT12DI16_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 TKDT12DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT12DI16_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(TKDT12DI16_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 TKDT12DI16.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 <> KDT12DI16_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(TKDT12DI16_Vec)) <> SizeOf(TKDT12DI16_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 TKDT12DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT12DI16.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 TKDT12DI16.PrintNodeTree(const NodePtr: PKDT12DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT12DI16_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 TKDT12DI16.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 TKDT12DI16.Vec(const s: SystemString): TKDT12DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT12DI16_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 >= KDT12DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT12DI16.Vec(const v: TKDT12DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT12DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT12DI16.Distance(const v1, v2: TKDT12DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT12DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT12DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT12DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT12DI16.Test; var TKDT12DI16_Test: TKDT12DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT12DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT12DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT12DI16_Test := TKDT12DI16.Create; n.Append('...'); SetLength(TKDT12DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT12DI16_Test.TestBuff) - 1 do for j := 0 to KDT12DI16_Axis - 1 do TKDT12DI16_Test.TestBuff[i][j] := i * KDT12DI16_Axis + j; {$IFDEF FPC} TKDT12DI16_Test.BuildKDTreeM(length(TKDT12DI16_Test.TestBuff), nil, @TKDT12DI16_Test.Test_BuildM); {$ELSE FPC} TKDT12DI16_Test.BuildKDTreeM(length(TKDT12DI16_Test.TestBuff), nil, TKDT12DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT12DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT12DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT12DI16_Test.TestBuff) - 1 do begin p := TKDT12DI16_Test.Search(TKDT12DI16_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(TKDT12DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT12DI16_Test.TestBuff)); TKDT12DI16_Test.Search(TKDT12DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT12DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT12DI16_Test.Clear; { kMean test } TKDT12DI16_Test.BuildKDTreeWithCluster(TKDT12DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT12DI16_Test.Search(TKDT12DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT12DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT12DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT12DI16_Test); DoStatus(n); n := ''; end; function TKDT13DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT13DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT13DI16_Node; function SortCompare(const p1, p2: PKDT13DI16_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: PKDT13DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT13DI16_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: PKDT13DI16_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 KDT13DI16_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 TKDT13DI16.GetData(const Index: NativeInt): PKDT13DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT13DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT13DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT13DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT13DI16_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 TKDT13DI16.StoreBuffPtr: PKDT13DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT13DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT13DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT13DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT13DI16.BuildKDTreeWithCluster(const inBuff: TKDT13DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT13DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT13DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT13DI16_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 KDT13DI16_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 TKDT13DI16.BuildKDTreeWithCluster(const inBuff: TKDT13DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT13DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildCall); var TempStoreBuff: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI16_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 KDT13DI16_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 TKDT13DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildMethod); var TempStoreBuff: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI16_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 KDT13DI16_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 TKDT13DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT13DI16_BuildProc); var TempStoreBuff: TKDT13DI16_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(TKDT13DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT13DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT13DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT13DI16_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 KDT13DI16_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 TKDT13DI16.Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT13DI16_Node; var NearestNeighbour: PKDT13DI16_Node; function FindParentNode(const buffPtr: PKDT13DI16_Vec; NodePtr: PKDT13DI16_Node): PKDT13DI16_Node; var Next: PKDT13DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT13DI16_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: PKDT13DI16_Node; const buffPtr: PKDT13DI16_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 KDT13DI16_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: PKDT13DI16_Vec; const p1, p2: PKDT13DI16_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: PKDT13DI16_Vec); var i, j: NativeInt; p, t: PKDT13DI16_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: PKDT13DI16_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 := PKDT13DI16_Node(NearestNodes[0]); end; end; function TKDT13DI16.Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT13DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT13DI16.Search(const buff: TKDT13DI16_Vec; var SearchedDistanceMin: Double): PKDT13DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT13DI16.Search(const buff: TKDT13DI16_Vec): PKDT13DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT13DI16.SearchToken(const buff: TKDT13DI16_Vec): TPascalString; var p: PKDT13DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT13DI16.Search(const inBuff: TKDT13DI16_DynamicVecBuffer; var OutBuff: TKDT13DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT13DI16_DynamicVecBuffer; outBuffPtr: PKDT13DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT13DI16_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: PKDT13DI16_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: PKDT13DI16_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 TKDT13DI16.Search(const inBuff: TKDT13DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT13DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT13DI16_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: PKDT13DI16_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: PKDT13DI16_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 TKDT13DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT13DI16_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(TKDT13DI16_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 TKDT13DI16.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 <> KDT13DI16_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(TKDT13DI16_Vec)) <> SizeOf(TKDT13DI16_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 TKDT13DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT13DI16.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 TKDT13DI16.PrintNodeTree(const NodePtr: PKDT13DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT13DI16_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 TKDT13DI16.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 TKDT13DI16.Vec(const s: SystemString): TKDT13DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT13DI16_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 >= KDT13DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT13DI16.Vec(const v: TKDT13DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT13DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT13DI16.Distance(const v1, v2: TKDT13DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT13DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT13DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT13DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT13DI16.Test; var TKDT13DI16_Test: TKDT13DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT13DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT13DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT13DI16_Test := TKDT13DI16.Create; n.Append('...'); SetLength(TKDT13DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT13DI16_Test.TestBuff) - 1 do for j := 0 to KDT13DI16_Axis - 1 do TKDT13DI16_Test.TestBuff[i][j] := i * KDT13DI16_Axis + j; {$IFDEF FPC} TKDT13DI16_Test.BuildKDTreeM(length(TKDT13DI16_Test.TestBuff), nil, @TKDT13DI16_Test.Test_BuildM); {$ELSE FPC} TKDT13DI16_Test.BuildKDTreeM(length(TKDT13DI16_Test.TestBuff), nil, TKDT13DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT13DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT13DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT13DI16_Test.TestBuff) - 1 do begin p := TKDT13DI16_Test.Search(TKDT13DI16_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(TKDT13DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT13DI16_Test.TestBuff)); TKDT13DI16_Test.Search(TKDT13DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT13DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT13DI16_Test.Clear; { kMean test } TKDT13DI16_Test.BuildKDTreeWithCluster(TKDT13DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT13DI16_Test.Search(TKDT13DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT13DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT13DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT13DI16_Test); DoStatus(n); n := ''; end; function TKDT14DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT14DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT14DI16_Node; function SortCompare(const p1, p2: PKDT14DI16_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: PKDT14DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT14DI16_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: PKDT14DI16_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 KDT14DI16_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 TKDT14DI16.GetData(const Index: NativeInt): PKDT14DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT14DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT14DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT14DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT14DI16_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 TKDT14DI16.StoreBuffPtr: PKDT14DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT14DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT14DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT14DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT14DI16.BuildKDTreeWithCluster(const inBuff: TKDT14DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT14DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT14DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT14DI16_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 KDT14DI16_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 TKDT14DI16.BuildKDTreeWithCluster(const inBuff: TKDT14DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT14DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildCall); var TempStoreBuff: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI16_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 KDT14DI16_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 TKDT14DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildMethod); var TempStoreBuff: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI16_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 KDT14DI16_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 TKDT14DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT14DI16_BuildProc); var TempStoreBuff: TKDT14DI16_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(TKDT14DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT14DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT14DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT14DI16_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 KDT14DI16_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 TKDT14DI16.Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT14DI16_Node; var NearestNeighbour: PKDT14DI16_Node; function FindParentNode(const buffPtr: PKDT14DI16_Vec; NodePtr: PKDT14DI16_Node): PKDT14DI16_Node; var Next: PKDT14DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT14DI16_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: PKDT14DI16_Node; const buffPtr: PKDT14DI16_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 KDT14DI16_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: PKDT14DI16_Vec; const p1, p2: PKDT14DI16_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: PKDT14DI16_Vec); var i, j: NativeInt; p, t: PKDT14DI16_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: PKDT14DI16_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 := PKDT14DI16_Node(NearestNodes[0]); end; end; function TKDT14DI16.Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT14DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT14DI16.Search(const buff: TKDT14DI16_Vec; var SearchedDistanceMin: Double): PKDT14DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT14DI16.Search(const buff: TKDT14DI16_Vec): PKDT14DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT14DI16.SearchToken(const buff: TKDT14DI16_Vec): TPascalString; var p: PKDT14DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT14DI16.Search(const inBuff: TKDT14DI16_DynamicVecBuffer; var OutBuff: TKDT14DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT14DI16_DynamicVecBuffer; outBuffPtr: PKDT14DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT14DI16_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: PKDT14DI16_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: PKDT14DI16_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 TKDT14DI16.Search(const inBuff: TKDT14DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT14DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT14DI16_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: PKDT14DI16_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: PKDT14DI16_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 TKDT14DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT14DI16_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(TKDT14DI16_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 TKDT14DI16.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 <> KDT14DI16_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(TKDT14DI16_Vec)) <> SizeOf(TKDT14DI16_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 TKDT14DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT14DI16.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 TKDT14DI16.PrintNodeTree(const NodePtr: PKDT14DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT14DI16_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 TKDT14DI16.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 TKDT14DI16.Vec(const s: SystemString): TKDT14DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT14DI16_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 >= KDT14DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT14DI16.Vec(const v: TKDT14DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT14DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT14DI16.Distance(const v1, v2: TKDT14DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT14DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT14DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT14DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT14DI16.Test; var TKDT14DI16_Test: TKDT14DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT14DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT14DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT14DI16_Test := TKDT14DI16.Create; n.Append('...'); SetLength(TKDT14DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT14DI16_Test.TestBuff) - 1 do for j := 0 to KDT14DI16_Axis - 1 do TKDT14DI16_Test.TestBuff[i][j] := i * KDT14DI16_Axis + j; {$IFDEF FPC} TKDT14DI16_Test.BuildKDTreeM(length(TKDT14DI16_Test.TestBuff), nil, @TKDT14DI16_Test.Test_BuildM); {$ELSE FPC} TKDT14DI16_Test.BuildKDTreeM(length(TKDT14DI16_Test.TestBuff), nil, TKDT14DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT14DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT14DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT14DI16_Test.TestBuff) - 1 do begin p := TKDT14DI16_Test.Search(TKDT14DI16_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(TKDT14DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT14DI16_Test.TestBuff)); TKDT14DI16_Test.Search(TKDT14DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT14DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT14DI16_Test.Clear; { kMean test } TKDT14DI16_Test.BuildKDTreeWithCluster(TKDT14DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT14DI16_Test.Search(TKDT14DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT14DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT14DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT14DI16_Test); DoStatus(n); n := ''; end; function TKDT15DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT15DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT15DI16_Node; function SortCompare(const p1, p2: PKDT15DI16_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: PKDT15DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT15DI16_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: PKDT15DI16_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 KDT15DI16_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 TKDT15DI16.GetData(const Index: NativeInt): PKDT15DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT15DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT15DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT15DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT15DI16_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 TKDT15DI16.StoreBuffPtr: PKDT15DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT15DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT15DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT15DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT15DI16.BuildKDTreeWithCluster(const inBuff: TKDT15DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT15DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT15DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT15DI16_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 KDT15DI16_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 TKDT15DI16.BuildKDTreeWithCluster(const inBuff: TKDT15DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT15DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildCall); var TempStoreBuff: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI16_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 KDT15DI16_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 TKDT15DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildMethod); var TempStoreBuff: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI16_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 KDT15DI16_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 TKDT15DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT15DI16_BuildProc); var TempStoreBuff: TKDT15DI16_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(TKDT15DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT15DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT15DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT15DI16_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 KDT15DI16_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 TKDT15DI16.Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT15DI16_Node; var NearestNeighbour: PKDT15DI16_Node; function FindParentNode(const buffPtr: PKDT15DI16_Vec; NodePtr: PKDT15DI16_Node): PKDT15DI16_Node; var Next: PKDT15DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT15DI16_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: PKDT15DI16_Node; const buffPtr: PKDT15DI16_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 KDT15DI16_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: PKDT15DI16_Vec; const p1, p2: PKDT15DI16_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: PKDT15DI16_Vec); var i, j: NativeInt; p, t: PKDT15DI16_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: PKDT15DI16_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 := PKDT15DI16_Node(NearestNodes[0]); end; end; function TKDT15DI16.Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT15DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT15DI16.Search(const buff: TKDT15DI16_Vec; var SearchedDistanceMin: Double): PKDT15DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT15DI16.Search(const buff: TKDT15DI16_Vec): PKDT15DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT15DI16.SearchToken(const buff: TKDT15DI16_Vec): TPascalString; var p: PKDT15DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT15DI16.Search(const inBuff: TKDT15DI16_DynamicVecBuffer; var OutBuff: TKDT15DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT15DI16_DynamicVecBuffer; outBuffPtr: PKDT15DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT15DI16_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: PKDT15DI16_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: PKDT15DI16_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 TKDT15DI16.Search(const inBuff: TKDT15DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT15DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT15DI16_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: PKDT15DI16_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: PKDT15DI16_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 TKDT15DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT15DI16_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(TKDT15DI16_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 TKDT15DI16.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 <> KDT15DI16_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(TKDT15DI16_Vec)) <> SizeOf(TKDT15DI16_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 TKDT15DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT15DI16.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 TKDT15DI16.PrintNodeTree(const NodePtr: PKDT15DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT15DI16_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 TKDT15DI16.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 TKDT15DI16.Vec(const s: SystemString): TKDT15DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT15DI16_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 >= KDT15DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT15DI16.Vec(const v: TKDT15DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT15DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT15DI16.Distance(const v1, v2: TKDT15DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT15DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT15DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT15DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT15DI16.Test; var TKDT15DI16_Test: TKDT15DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT15DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT15DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT15DI16_Test := TKDT15DI16.Create; n.Append('...'); SetLength(TKDT15DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT15DI16_Test.TestBuff) - 1 do for j := 0 to KDT15DI16_Axis - 1 do TKDT15DI16_Test.TestBuff[i][j] := i * KDT15DI16_Axis + j; {$IFDEF FPC} TKDT15DI16_Test.BuildKDTreeM(length(TKDT15DI16_Test.TestBuff), nil, @TKDT15DI16_Test.Test_BuildM); {$ELSE FPC} TKDT15DI16_Test.BuildKDTreeM(length(TKDT15DI16_Test.TestBuff), nil, TKDT15DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT15DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT15DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT15DI16_Test.TestBuff) - 1 do begin p := TKDT15DI16_Test.Search(TKDT15DI16_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(TKDT15DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT15DI16_Test.TestBuff)); TKDT15DI16_Test.Search(TKDT15DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT15DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT15DI16_Test.Clear; { kMean test } TKDT15DI16_Test.BuildKDTreeWithCluster(TKDT15DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT15DI16_Test.Search(TKDT15DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT15DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT15DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT15DI16_Test); DoStatus(n); n := ''; end; function TKDT16DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT16DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT16DI16_Node; function SortCompare(const p1, p2: PKDT16DI16_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: PKDT16DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT16DI16_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: PKDT16DI16_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 KDT16DI16_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 TKDT16DI16.GetData(const Index: NativeInt): PKDT16DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT16DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT16DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT16DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT16DI16_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 TKDT16DI16.StoreBuffPtr: PKDT16DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT16DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT16DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT16DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT16DI16.BuildKDTreeWithCluster(const inBuff: TKDT16DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT16DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT16DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT16DI16_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 KDT16DI16_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 TKDT16DI16.BuildKDTreeWithCluster(const inBuff: TKDT16DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT16DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildCall); var TempStoreBuff: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI16_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 KDT16DI16_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 TKDT16DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildMethod); var TempStoreBuff: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI16_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 KDT16DI16_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 TKDT16DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT16DI16_BuildProc); var TempStoreBuff: TKDT16DI16_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(TKDT16DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT16DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT16DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT16DI16_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 KDT16DI16_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 TKDT16DI16.Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT16DI16_Node; var NearestNeighbour: PKDT16DI16_Node; function FindParentNode(const buffPtr: PKDT16DI16_Vec; NodePtr: PKDT16DI16_Node): PKDT16DI16_Node; var Next: PKDT16DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT16DI16_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: PKDT16DI16_Node; const buffPtr: PKDT16DI16_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 KDT16DI16_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: PKDT16DI16_Vec; const p1, p2: PKDT16DI16_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: PKDT16DI16_Vec); var i, j: NativeInt; p, t: PKDT16DI16_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: PKDT16DI16_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 := PKDT16DI16_Node(NearestNodes[0]); end; end; function TKDT16DI16.Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT16DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT16DI16.Search(const buff: TKDT16DI16_Vec; var SearchedDistanceMin: Double): PKDT16DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT16DI16.Search(const buff: TKDT16DI16_Vec): PKDT16DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT16DI16.SearchToken(const buff: TKDT16DI16_Vec): TPascalString; var p: PKDT16DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT16DI16.Search(const inBuff: TKDT16DI16_DynamicVecBuffer; var OutBuff: TKDT16DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT16DI16_DynamicVecBuffer; outBuffPtr: PKDT16DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT16DI16_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: PKDT16DI16_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: PKDT16DI16_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 TKDT16DI16.Search(const inBuff: TKDT16DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT16DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT16DI16_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: PKDT16DI16_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: PKDT16DI16_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 TKDT16DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT16DI16_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(TKDT16DI16_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 TKDT16DI16.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 <> KDT16DI16_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(TKDT16DI16_Vec)) <> SizeOf(TKDT16DI16_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 TKDT16DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT16DI16.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 TKDT16DI16.PrintNodeTree(const NodePtr: PKDT16DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT16DI16_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 TKDT16DI16.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 TKDT16DI16.Vec(const s: SystemString): TKDT16DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT16DI16_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 >= KDT16DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT16DI16.Vec(const v: TKDT16DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT16DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT16DI16.Distance(const v1, v2: TKDT16DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT16DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT16DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT16DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT16DI16.Test; var TKDT16DI16_Test: TKDT16DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT16DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT16DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT16DI16_Test := TKDT16DI16.Create; n.Append('...'); SetLength(TKDT16DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT16DI16_Test.TestBuff) - 1 do for j := 0 to KDT16DI16_Axis - 1 do TKDT16DI16_Test.TestBuff[i][j] := i * KDT16DI16_Axis + j; {$IFDEF FPC} TKDT16DI16_Test.BuildKDTreeM(length(TKDT16DI16_Test.TestBuff), nil, @TKDT16DI16_Test.Test_BuildM); {$ELSE FPC} TKDT16DI16_Test.BuildKDTreeM(length(TKDT16DI16_Test.TestBuff), nil, TKDT16DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT16DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT16DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT16DI16_Test.TestBuff) - 1 do begin p := TKDT16DI16_Test.Search(TKDT16DI16_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(TKDT16DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT16DI16_Test.TestBuff)); TKDT16DI16_Test.Search(TKDT16DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT16DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT16DI16_Test.Clear; { kMean test } TKDT16DI16_Test.BuildKDTreeWithCluster(TKDT16DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT16DI16_Test.Search(TKDT16DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT16DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT16DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT16DI16_Test); DoStatus(n); n := ''; end; function TKDT17DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT17DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT17DI16_Node; function SortCompare(const p1, p2: PKDT17DI16_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: PKDT17DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT17DI16_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: PKDT17DI16_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 KDT17DI16_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 TKDT17DI16.GetData(const Index: NativeInt): PKDT17DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT17DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT17DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT17DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT17DI16_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 TKDT17DI16.StoreBuffPtr: PKDT17DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT17DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT17DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT17DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT17DI16.BuildKDTreeWithCluster(const inBuff: TKDT17DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT17DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT17DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT17DI16_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 KDT17DI16_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 TKDT17DI16.BuildKDTreeWithCluster(const inBuff: TKDT17DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT17DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildCall); var TempStoreBuff: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI16_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 KDT17DI16_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 TKDT17DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildMethod); var TempStoreBuff: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI16_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 KDT17DI16_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 TKDT17DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT17DI16_BuildProc); var TempStoreBuff: TKDT17DI16_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(TKDT17DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT17DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT17DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT17DI16_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 KDT17DI16_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 TKDT17DI16.Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT17DI16_Node; var NearestNeighbour: PKDT17DI16_Node; function FindParentNode(const buffPtr: PKDT17DI16_Vec; NodePtr: PKDT17DI16_Node): PKDT17DI16_Node; var Next: PKDT17DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT17DI16_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: PKDT17DI16_Node; const buffPtr: PKDT17DI16_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 KDT17DI16_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: PKDT17DI16_Vec; const p1, p2: PKDT17DI16_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: PKDT17DI16_Vec); var i, j: NativeInt; p, t: PKDT17DI16_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: PKDT17DI16_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 := PKDT17DI16_Node(NearestNodes[0]); end; end; function TKDT17DI16.Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT17DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT17DI16.Search(const buff: TKDT17DI16_Vec; var SearchedDistanceMin: Double): PKDT17DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT17DI16.Search(const buff: TKDT17DI16_Vec): PKDT17DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT17DI16.SearchToken(const buff: TKDT17DI16_Vec): TPascalString; var p: PKDT17DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT17DI16.Search(const inBuff: TKDT17DI16_DynamicVecBuffer; var OutBuff: TKDT17DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT17DI16_DynamicVecBuffer; outBuffPtr: PKDT17DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT17DI16_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: PKDT17DI16_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: PKDT17DI16_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 TKDT17DI16.Search(const inBuff: TKDT17DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT17DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT17DI16_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: PKDT17DI16_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: PKDT17DI16_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 TKDT17DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT17DI16_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(TKDT17DI16_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 TKDT17DI16.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 <> KDT17DI16_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(TKDT17DI16_Vec)) <> SizeOf(TKDT17DI16_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 TKDT17DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT17DI16.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 TKDT17DI16.PrintNodeTree(const NodePtr: PKDT17DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT17DI16_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 TKDT17DI16.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 TKDT17DI16.Vec(const s: SystemString): TKDT17DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT17DI16_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 >= KDT17DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT17DI16.Vec(const v: TKDT17DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT17DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT17DI16.Distance(const v1, v2: TKDT17DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT17DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT17DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT17DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT17DI16.Test; var TKDT17DI16_Test: TKDT17DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT17DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT17DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT17DI16_Test := TKDT17DI16.Create; n.Append('...'); SetLength(TKDT17DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT17DI16_Test.TestBuff) - 1 do for j := 0 to KDT17DI16_Axis - 1 do TKDT17DI16_Test.TestBuff[i][j] := i * KDT17DI16_Axis + j; {$IFDEF FPC} TKDT17DI16_Test.BuildKDTreeM(length(TKDT17DI16_Test.TestBuff), nil, @TKDT17DI16_Test.Test_BuildM); {$ELSE FPC} TKDT17DI16_Test.BuildKDTreeM(length(TKDT17DI16_Test.TestBuff), nil, TKDT17DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT17DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT17DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT17DI16_Test.TestBuff) - 1 do begin p := TKDT17DI16_Test.Search(TKDT17DI16_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(TKDT17DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT17DI16_Test.TestBuff)); TKDT17DI16_Test.Search(TKDT17DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT17DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT17DI16_Test.Clear; { kMean test } TKDT17DI16_Test.BuildKDTreeWithCluster(TKDT17DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT17DI16_Test.Search(TKDT17DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT17DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT17DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT17DI16_Test); DoStatus(n); n := ''; end; function TKDT18DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT18DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT18DI16_Node; function SortCompare(const p1, p2: PKDT18DI16_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: PKDT18DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT18DI16_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: PKDT18DI16_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 KDT18DI16_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 TKDT18DI16.GetData(const Index: NativeInt): PKDT18DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT18DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT18DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT18DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT18DI16_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 TKDT18DI16.StoreBuffPtr: PKDT18DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT18DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT18DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT18DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT18DI16.BuildKDTreeWithCluster(const inBuff: TKDT18DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT18DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT18DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT18DI16_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 KDT18DI16_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 TKDT18DI16.BuildKDTreeWithCluster(const inBuff: TKDT18DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT18DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildCall); var TempStoreBuff: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI16_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 KDT18DI16_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 TKDT18DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildMethod); var TempStoreBuff: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI16_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 KDT18DI16_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 TKDT18DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT18DI16_BuildProc); var TempStoreBuff: TKDT18DI16_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(TKDT18DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT18DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT18DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT18DI16_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 KDT18DI16_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 TKDT18DI16.Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT18DI16_Node; var NearestNeighbour: PKDT18DI16_Node; function FindParentNode(const buffPtr: PKDT18DI16_Vec; NodePtr: PKDT18DI16_Node): PKDT18DI16_Node; var Next: PKDT18DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT18DI16_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: PKDT18DI16_Node; const buffPtr: PKDT18DI16_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 KDT18DI16_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: PKDT18DI16_Vec; const p1, p2: PKDT18DI16_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: PKDT18DI16_Vec); var i, j: NativeInt; p, t: PKDT18DI16_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: PKDT18DI16_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 := PKDT18DI16_Node(NearestNodes[0]); end; end; function TKDT18DI16.Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT18DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT18DI16.Search(const buff: TKDT18DI16_Vec; var SearchedDistanceMin: Double): PKDT18DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT18DI16.Search(const buff: TKDT18DI16_Vec): PKDT18DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT18DI16.SearchToken(const buff: TKDT18DI16_Vec): TPascalString; var p: PKDT18DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT18DI16.Search(const inBuff: TKDT18DI16_DynamicVecBuffer; var OutBuff: TKDT18DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT18DI16_DynamicVecBuffer; outBuffPtr: PKDT18DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT18DI16_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: PKDT18DI16_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: PKDT18DI16_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 TKDT18DI16.Search(const inBuff: TKDT18DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT18DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT18DI16_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: PKDT18DI16_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: PKDT18DI16_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 TKDT18DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT18DI16_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(TKDT18DI16_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 TKDT18DI16.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 <> KDT18DI16_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(TKDT18DI16_Vec)) <> SizeOf(TKDT18DI16_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 TKDT18DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT18DI16.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 TKDT18DI16.PrintNodeTree(const NodePtr: PKDT18DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT18DI16_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 TKDT18DI16.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 TKDT18DI16.Vec(const s: SystemString): TKDT18DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT18DI16_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 >= KDT18DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT18DI16.Vec(const v: TKDT18DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT18DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT18DI16.Distance(const v1, v2: TKDT18DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT18DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT18DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT18DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT18DI16.Test; var TKDT18DI16_Test: TKDT18DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT18DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT18DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT18DI16_Test := TKDT18DI16.Create; n.Append('...'); SetLength(TKDT18DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT18DI16_Test.TestBuff) - 1 do for j := 0 to KDT18DI16_Axis - 1 do TKDT18DI16_Test.TestBuff[i][j] := i * KDT18DI16_Axis + j; {$IFDEF FPC} TKDT18DI16_Test.BuildKDTreeM(length(TKDT18DI16_Test.TestBuff), nil, @TKDT18DI16_Test.Test_BuildM); {$ELSE FPC} TKDT18DI16_Test.BuildKDTreeM(length(TKDT18DI16_Test.TestBuff), nil, TKDT18DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT18DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT18DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT18DI16_Test.TestBuff) - 1 do begin p := TKDT18DI16_Test.Search(TKDT18DI16_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(TKDT18DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT18DI16_Test.TestBuff)); TKDT18DI16_Test.Search(TKDT18DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT18DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT18DI16_Test.Clear; { kMean test } TKDT18DI16_Test.BuildKDTreeWithCluster(TKDT18DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT18DI16_Test.Search(TKDT18DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT18DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT18DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT18DI16_Test); DoStatus(n); n := ''; end; function TKDT19DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT19DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT19DI16_Node; function SortCompare(const p1, p2: PKDT19DI16_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: PKDT19DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT19DI16_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: PKDT19DI16_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 KDT19DI16_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 TKDT19DI16.GetData(const Index: NativeInt): PKDT19DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT19DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT19DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT19DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT19DI16_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 TKDT19DI16.StoreBuffPtr: PKDT19DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT19DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT19DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT19DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT19DI16.BuildKDTreeWithCluster(const inBuff: TKDT19DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT19DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT19DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT19DI16_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 KDT19DI16_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 TKDT19DI16.BuildKDTreeWithCluster(const inBuff: TKDT19DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT19DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildCall); var TempStoreBuff: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI16_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 KDT19DI16_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 TKDT19DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildMethod); var TempStoreBuff: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI16_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 KDT19DI16_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 TKDT19DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT19DI16_BuildProc); var TempStoreBuff: TKDT19DI16_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(TKDT19DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT19DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT19DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT19DI16_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 KDT19DI16_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 TKDT19DI16.Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT19DI16_Node; var NearestNeighbour: PKDT19DI16_Node; function FindParentNode(const buffPtr: PKDT19DI16_Vec; NodePtr: PKDT19DI16_Node): PKDT19DI16_Node; var Next: PKDT19DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT19DI16_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: PKDT19DI16_Node; const buffPtr: PKDT19DI16_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 KDT19DI16_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: PKDT19DI16_Vec; const p1, p2: PKDT19DI16_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: PKDT19DI16_Vec); var i, j: NativeInt; p, t: PKDT19DI16_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: PKDT19DI16_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 := PKDT19DI16_Node(NearestNodes[0]); end; end; function TKDT19DI16.Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT19DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT19DI16.Search(const buff: TKDT19DI16_Vec; var SearchedDistanceMin: Double): PKDT19DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT19DI16.Search(const buff: TKDT19DI16_Vec): PKDT19DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT19DI16.SearchToken(const buff: TKDT19DI16_Vec): TPascalString; var p: PKDT19DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT19DI16.Search(const inBuff: TKDT19DI16_DynamicVecBuffer; var OutBuff: TKDT19DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT19DI16_DynamicVecBuffer; outBuffPtr: PKDT19DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT19DI16_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: PKDT19DI16_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: PKDT19DI16_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 TKDT19DI16.Search(const inBuff: TKDT19DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT19DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT19DI16_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: PKDT19DI16_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: PKDT19DI16_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 TKDT19DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT19DI16_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(TKDT19DI16_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 TKDT19DI16.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 <> KDT19DI16_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(TKDT19DI16_Vec)) <> SizeOf(TKDT19DI16_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 TKDT19DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT19DI16.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 TKDT19DI16.PrintNodeTree(const NodePtr: PKDT19DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT19DI16_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 TKDT19DI16.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 TKDT19DI16.Vec(const s: SystemString): TKDT19DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT19DI16_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 >= KDT19DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT19DI16.Vec(const v: TKDT19DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT19DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT19DI16.Distance(const v1, v2: TKDT19DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT19DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT19DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT19DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT19DI16.Test; var TKDT19DI16_Test: TKDT19DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT19DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT19DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT19DI16_Test := TKDT19DI16.Create; n.Append('...'); SetLength(TKDT19DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT19DI16_Test.TestBuff) - 1 do for j := 0 to KDT19DI16_Axis - 1 do TKDT19DI16_Test.TestBuff[i][j] := i * KDT19DI16_Axis + j; {$IFDEF FPC} TKDT19DI16_Test.BuildKDTreeM(length(TKDT19DI16_Test.TestBuff), nil, @TKDT19DI16_Test.Test_BuildM); {$ELSE FPC} TKDT19DI16_Test.BuildKDTreeM(length(TKDT19DI16_Test.TestBuff), nil, TKDT19DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT19DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT19DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT19DI16_Test.TestBuff) - 1 do begin p := TKDT19DI16_Test.Search(TKDT19DI16_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(TKDT19DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT19DI16_Test.TestBuff)); TKDT19DI16_Test.Search(TKDT19DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT19DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT19DI16_Test.Clear; { kMean test } TKDT19DI16_Test.BuildKDTreeWithCluster(TKDT19DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT19DI16_Test.Search(TKDT19DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT19DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT19DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT19DI16_Test); DoStatus(n); n := ''; end; function TKDT20DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT20DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT20DI16_Node; function SortCompare(const p1, p2: PKDT20DI16_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: PKDT20DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT20DI16_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: PKDT20DI16_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 KDT20DI16_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 TKDT20DI16.GetData(const Index: NativeInt): PKDT20DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT20DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT20DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT20DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT20DI16_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 TKDT20DI16.StoreBuffPtr: PKDT20DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT20DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT20DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT20DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT20DI16.BuildKDTreeWithCluster(const inBuff: TKDT20DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT20DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT20DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT20DI16_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 KDT20DI16_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 TKDT20DI16.BuildKDTreeWithCluster(const inBuff: TKDT20DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT20DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildCall); var TempStoreBuff: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI16_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 KDT20DI16_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 TKDT20DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildMethod); var TempStoreBuff: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI16_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 KDT20DI16_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 TKDT20DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT20DI16_BuildProc); var TempStoreBuff: TKDT20DI16_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(TKDT20DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT20DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT20DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT20DI16_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 KDT20DI16_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 TKDT20DI16.Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT20DI16_Node; var NearestNeighbour: PKDT20DI16_Node; function FindParentNode(const buffPtr: PKDT20DI16_Vec; NodePtr: PKDT20DI16_Node): PKDT20DI16_Node; var Next: PKDT20DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT20DI16_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: PKDT20DI16_Node; const buffPtr: PKDT20DI16_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 KDT20DI16_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: PKDT20DI16_Vec; const p1, p2: PKDT20DI16_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: PKDT20DI16_Vec); var i, j: NativeInt; p, t: PKDT20DI16_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: PKDT20DI16_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 := PKDT20DI16_Node(NearestNodes[0]); end; end; function TKDT20DI16.Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT20DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT20DI16.Search(const buff: TKDT20DI16_Vec; var SearchedDistanceMin: Double): PKDT20DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT20DI16.Search(const buff: TKDT20DI16_Vec): PKDT20DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT20DI16.SearchToken(const buff: TKDT20DI16_Vec): TPascalString; var p: PKDT20DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT20DI16.Search(const inBuff: TKDT20DI16_DynamicVecBuffer; var OutBuff: TKDT20DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT20DI16_DynamicVecBuffer; outBuffPtr: PKDT20DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT20DI16_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: PKDT20DI16_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: PKDT20DI16_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 TKDT20DI16.Search(const inBuff: TKDT20DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT20DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT20DI16_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: PKDT20DI16_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: PKDT20DI16_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 TKDT20DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT20DI16_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(TKDT20DI16_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 TKDT20DI16.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 <> KDT20DI16_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(TKDT20DI16_Vec)) <> SizeOf(TKDT20DI16_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 TKDT20DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT20DI16.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 TKDT20DI16.PrintNodeTree(const NodePtr: PKDT20DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT20DI16_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 TKDT20DI16.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 TKDT20DI16.Vec(const s: SystemString): TKDT20DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT20DI16_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 >= KDT20DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT20DI16.Vec(const v: TKDT20DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT20DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT20DI16.Distance(const v1, v2: TKDT20DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT20DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT20DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT20DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT20DI16.Test; var TKDT20DI16_Test: TKDT20DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT20DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT20DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT20DI16_Test := TKDT20DI16.Create; n.Append('...'); SetLength(TKDT20DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT20DI16_Test.TestBuff) - 1 do for j := 0 to KDT20DI16_Axis - 1 do TKDT20DI16_Test.TestBuff[i][j] := i * KDT20DI16_Axis + j; {$IFDEF FPC} TKDT20DI16_Test.BuildKDTreeM(length(TKDT20DI16_Test.TestBuff), nil, @TKDT20DI16_Test.Test_BuildM); {$ELSE FPC} TKDT20DI16_Test.BuildKDTreeM(length(TKDT20DI16_Test.TestBuff), nil, TKDT20DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT20DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT20DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT20DI16_Test.TestBuff) - 1 do begin p := TKDT20DI16_Test.Search(TKDT20DI16_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(TKDT20DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT20DI16_Test.TestBuff)); TKDT20DI16_Test.Search(TKDT20DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT20DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT20DI16_Test.Clear; { kMean test } TKDT20DI16_Test.BuildKDTreeWithCluster(TKDT20DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT20DI16_Test.Search(TKDT20DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT20DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT20DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT20DI16_Test); DoStatus(n); n := ''; end; function TKDT21DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT21DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT21DI16_Node; function SortCompare(const p1, p2: PKDT21DI16_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: PKDT21DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT21DI16_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: PKDT21DI16_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 KDT21DI16_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 TKDT21DI16.GetData(const Index: NativeInt): PKDT21DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT21DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT21DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT21DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT21DI16_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 TKDT21DI16.StoreBuffPtr: PKDT21DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT21DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT21DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT21DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT21DI16.BuildKDTreeWithCluster(const inBuff: TKDT21DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT21DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT21DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT21DI16_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 KDT21DI16_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 TKDT21DI16.BuildKDTreeWithCluster(const inBuff: TKDT21DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT21DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildCall); var TempStoreBuff: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI16_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 KDT21DI16_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 TKDT21DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildMethod); var TempStoreBuff: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI16_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 KDT21DI16_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 TKDT21DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT21DI16_BuildProc); var TempStoreBuff: TKDT21DI16_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(TKDT21DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT21DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT21DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT21DI16_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 KDT21DI16_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 TKDT21DI16.Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT21DI16_Node; var NearestNeighbour: PKDT21DI16_Node; function FindParentNode(const buffPtr: PKDT21DI16_Vec; NodePtr: PKDT21DI16_Node): PKDT21DI16_Node; var Next: PKDT21DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT21DI16_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: PKDT21DI16_Node; const buffPtr: PKDT21DI16_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 KDT21DI16_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: PKDT21DI16_Vec; const p1, p2: PKDT21DI16_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: PKDT21DI16_Vec); var i, j: NativeInt; p, t: PKDT21DI16_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: PKDT21DI16_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 := PKDT21DI16_Node(NearestNodes[0]); end; end; function TKDT21DI16.Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT21DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT21DI16.Search(const buff: TKDT21DI16_Vec; var SearchedDistanceMin: Double): PKDT21DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT21DI16.Search(const buff: TKDT21DI16_Vec): PKDT21DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT21DI16.SearchToken(const buff: TKDT21DI16_Vec): TPascalString; var p: PKDT21DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT21DI16.Search(const inBuff: TKDT21DI16_DynamicVecBuffer; var OutBuff: TKDT21DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT21DI16_DynamicVecBuffer; outBuffPtr: PKDT21DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT21DI16_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: PKDT21DI16_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: PKDT21DI16_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 TKDT21DI16.Search(const inBuff: TKDT21DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT21DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT21DI16_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: PKDT21DI16_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: PKDT21DI16_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 TKDT21DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT21DI16_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(TKDT21DI16_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 TKDT21DI16.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 <> KDT21DI16_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(TKDT21DI16_Vec)) <> SizeOf(TKDT21DI16_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 TKDT21DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT21DI16.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 TKDT21DI16.PrintNodeTree(const NodePtr: PKDT21DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT21DI16_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 TKDT21DI16.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 TKDT21DI16.Vec(const s: SystemString): TKDT21DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT21DI16_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 >= KDT21DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT21DI16.Vec(const v: TKDT21DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT21DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT21DI16.Distance(const v1, v2: TKDT21DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT21DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT21DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT21DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT21DI16.Test; var TKDT21DI16_Test: TKDT21DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT21DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT21DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT21DI16_Test := TKDT21DI16.Create; n.Append('...'); SetLength(TKDT21DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT21DI16_Test.TestBuff) - 1 do for j := 0 to KDT21DI16_Axis - 1 do TKDT21DI16_Test.TestBuff[i][j] := i * KDT21DI16_Axis + j; {$IFDEF FPC} TKDT21DI16_Test.BuildKDTreeM(length(TKDT21DI16_Test.TestBuff), nil, @TKDT21DI16_Test.Test_BuildM); {$ELSE FPC} TKDT21DI16_Test.BuildKDTreeM(length(TKDT21DI16_Test.TestBuff), nil, TKDT21DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT21DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT21DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT21DI16_Test.TestBuff) - 1 do begin p := TKDT21DI16_Test.Search(TKDT21DI16_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(TKDT21DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT21DI16_Test.TestBuff)); TKDT21DI16_Test.Search(TKDT21DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT21DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT21DI16_Test.Clear; { kMean test } TKDT21DI16_Test.BuildKDTreeWithCluster(TKDT21DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT21DI16_Test.Search(TKDT21DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT21DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT21DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT21DI16_Test); DoStatus(n); n := ''; end; function TKDT22DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT22DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT22DI16_Node; function SortCompare(const p1, p2: PKDT22DI16_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: PKDT22DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT22DI16_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: PKDT22DI16_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 KDT22DI16_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 TKDT22DI16.GetData(const Index: NativeInt): PKDT22DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT22DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT22DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT22DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT22DI16_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 TKDT22DI16.StoreBuffPtr: PKDT22DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT22DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT22DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT22DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT22DI16.BuildKDTreeWithCluster(const inBuff: TKDT22DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT22DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT22DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT22DI16_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 KDT22DI16_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 TKDT22DI16.BuildKDTreeWithCluster(const inBuff: TKDT22DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT22DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildCall); var TempStoreBuff: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI16_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 KDT22DI16_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 TKDT22DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildMethod); var TempStoreBuff: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI16_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 KDT22DI16_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 TKDT22DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT22DI16_BuildProc); var TempStoreBuff: TKDT22DI16_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(TKDT22DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT22DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT22DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT22DI16_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 KDT22DI16_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 TKDT22DI16.Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT22DI16_Node; var NearestNeighbour: PKDT22DI16_Node; function FindParentNode(const buffPtr: PKDT22DI16_Vec; NodePtr: PKDT22DI16_Node): PKDT22DI16_Node; var Next: PKDT22DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT22DI16_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: PKDT22DI16_Node; const buffPtr: PKDT22DI16_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 KDT22DI16_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: PKDT22DI16_Vec; const p1, p2: PKDT22DI16_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: PKDT22DI16_Vec); var i, j: NativeInt; p, t: PKDT22DI16_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: PKDT22DI16_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 := PKDT22DI16_Node(NearestNodes[0]); end; end; function TKDT22DI16.Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT22DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT22DI16.Search(const buff: TKDT22DI16_Vec; var SearchedDistanceMin: Double): PKDT22DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT22DI16.Search(const buff: TKDT22DI16_Vec): PKDT22DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT22DI16.SearchToken(const buff: TKDT22DI16_Vec): TPascalString; var p: PKDT22DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT22DI16.Search(const inBuff: TKDT22DI16_DynamicVecBuffer; var OutBuff: TKDT22DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT22DI16_DynamicVecBuffer; outBuffPtr: PKDT22DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT22DI16_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: PKDT22DI16_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: PKDT22DI16_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 TKDT22DI16.Search(const inBuff: TKDT22DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT22DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT22DI16_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: PKDT22DI16_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: PKDT22DI16_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 TKDT22DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT22DI16_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(TKDT22DI16_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 TKDT22DI16.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 <> KDT22DI16_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(TKDT22DI16_Vec)) <> SizeOf(TKDT22DI16_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 TKDT22DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT22DI16.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 TKDT22DI16.PrintNodeTree(const NodePtr: PKDT22DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT22DI16_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 TKDT22DI16.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 TKDT22DI16.Vec(const s: SystemString): TKDT22DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT22DI16_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 >= KDT22DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT22DI16.Vec(const v: TKDT22DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT22DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT22DI16.Distance(const v1, v2: TKDT22DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT22DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT22DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT22DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT22DI16.Test; var TKDT22DI16_Test: TKDT22DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT22DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT22DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT22DI16_Test := TKDT22DI16.Create; n.Append('...'); SetLength(TKDT22DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT22DI16_Test.TestBuff) - 1 do for j := 0 to KDT22DI16_Axis - 1 do TKDT22DI16_Test.TestBuff[i][j] := i * KDT22DI16_Axis + j; {$IFDEF FPC} TKDT22DI16_Test.BuildKDTreeM(length(TKDT22DI16_Test.TestBuff), nil, @TKDT22DI16_Test.Test_BuildM); {$ELSE FPC} TKDT22DI16_Test.BuildKDTreeM(length(TKDT22DI16_Test.TestBuff), nil, TKDT22DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT22DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT22DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT22DI16_Test.TestBuff) - 1 do begin p := TKDT22DI16_Test.Search(TKDT22DI16_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(TKDT22DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT22DI16_Test.TestBuff)); TKDT22DI16_Test.Search(TKDT22DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT22DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT22DI16_Test.Clear; { kMean test } TKDT22DI16_Test.BuildKDTreeWithCluster(TKDT22DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT22DI16_Test.Search(TKDT22DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT22DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT22DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT22DI16_Test); DoStatus(n); n := ''; end; function TKDT23DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT23DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT23DI16_Node; function SortCompare(const p1, p2: PKDT23DI16_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: PKDT23DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT23DI16_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: PKDT23DI16_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 KDT23DI16_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 TKDT23DI16.GetData(const Index: NativeInt): PKDT23DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT23DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT23DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT23DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT23DI16_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 TKDT23DI16.StoreBuffPtr: PKDT23DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT23DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT23DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT23DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT23DI16.BuildKDTreeWithCluster(const inBuff: TKDT23DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT23DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT23DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT23DI16_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 KDT23DI16_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 TKDT23DI16.BuildKDTreeWithCluster(const inBuff: TKDT23DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT23DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildCall); var TempStoreBuff: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI16_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 KDT23DI16_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 TKDT23DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildMethod); var TempStoreBuff: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI16_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 KDT23DI16_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 TKDT23DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT23DI16_BuildProc); var TempStoreBuff: TKDT23DI16_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(TKDT23DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT23DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT23DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT23DI16_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 KDT23DI16_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 TKDT23DI16.Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT23DI16_Node; var NearestNeighbour: PKDT23DI16_Node; function FindParentNode(const buffPtr: PKDT23DI16_Vec; NodePtr: PKDT23DI16_Node): PKDT23DI16_Node; var Next: PKDT23DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT23DI16_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: PKDT23DI16_Node; const buffPtr: PKDT23DI16_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 KDT23DI16_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: PKDT23DI16_Vec; const p1, p2: PKDT23DI16_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: PKDT23DI16_Vec); var i, j: NativeInt; p, t: PKDT23DI16_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: PKDT23DI16_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 := PKDT23DI16_Node(NearestNodes[0]); end; end; function TKDT23DI16.Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT23DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT23DI16.Search(const buff: TKDT23DI16_Vec; var SearchedDistanceMin: Double): PKDT23DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT23DI16.Search(const buff: TKDT23DI16_Vec): PKDT23DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT23DI16.SearchToken(const buff: TKDT23DI16_Vec): TPascalString; var p: PKDT23DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT23DI16.Search(const inBuff: TKDT23DI16_DynamicVecBuffer; var OutBuff: TKDT23DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT23DI16_DynamicVecBuffer; outBuffPtr: PKDT23DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT23DI16_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: PKDT23DI16_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: PKDT23DI16_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 TKDT23DI16.Search(const inBuff: TKDT23DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT23DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT23DI16_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: PKDT23DI16_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: PKDT23DI16_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 TKDT23DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT23DI16_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(TKDT23DI16_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 TKDT23DI16.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 <> KDT23DI16_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(TKDT23DI16_Vec)) <> SizeOf(TKDT23DI16_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 TKDT23DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT23DI16.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 TKDT23DI16.PrintNodeTree(const NodePtr: PKDT23DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT23DI16_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 TKDT23DI16.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 TKDT23DI16.Vec(const s: SystemString): TKDT23DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT23DI16_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 >= KDT23DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT23DI16.Vec(const v: TKDT23DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT23DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT23DI16.Distance(const v1, v2: TKDT23DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT23DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT23DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT23DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT23DI16.Test; var TKDT23DI16_Test: TKDT23DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT23DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT23DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT23DI16_Test := TKDT23DI16.Create; n.Append('...'); SetLength(TKDT23DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT23DI16_Test.TestBuff) - 1 do for j := 0 to KDT23DI16_Axis - 1 do TKDT23DI16_Test.TestBuff[i][j] := i * KDT23DI16_Axis + j; {$IFDEF FPC} TKDT23DI16_Test.BuildKDTreeM(length(TKDT23DI16_Test.TestBuff), nil, @TKDT23DI16_Test.Test_BuildM); {$ELSE FPC} TKDT23DI16_Test.BuildKDTreeM(length(TKDT23DI16_Test.TestBuff), nil, TKDT23DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT23DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT23DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT23DI16_Test.TestBuff) - 1 do begin p := TKDT23DI16_Test.Search(TKDT23DI16_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(TKDT23DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT23DI16_Test.TestBuff)); TKDT23DI16_Test.Search(TKDT23DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT23DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT23DI16_Test.Clear; { kMean test } TKDT23DI16_Test.BuildKDTreeWithCluster(TKDT23DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT23DI16_Test.Search(TKDT23DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT23DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT23DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT23DI16_Test); DoStatus(n); n := ''; end; function TKDT24DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT24DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT24DI16_Node; function SortCompare(const p1, p2: PKDT24DI16_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: PKDT24DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT24DI16_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: PKDT24DI16_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 KDT24DI16_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 TKDT24DI16.GetData(const Index: NativeInt): PKDT24DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT24DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT24DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT24DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT24DI16_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 TKDT24DI16.StoreBuffPtr: PKDT24DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT24DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT24DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT24DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT24DI16.BuildKDTreeWithCluster(const inBuff: TKDT24DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT24DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT24DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT24DI16_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 KDT24DI16_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 TKDT24DI16.BuildKDTreeWithCluster(const inBuff: TKDT24DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT24DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildCall); var TempStoreBuff: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI16_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 KDT24DI16_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 TKDT24DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildMethod); var TempStoreBuff: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI16_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 KDT24DI16_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 TKDT24DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT24DI16_BuildProc); var TempStoreBuff: TKDT24DI16_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(TKDT24DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT24DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT24DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT24DI16_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 KDT24DI16_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 TKDT24DI16.Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT24DI16_Node; var NearestNeighbour: PKDT24DI16_Node; function FindParentNode(const buffPtr: PKDT24DI16_Vec; NodePtr: PKDT24DI16_Node): PKDT24DI16_Node; var Next: PKDT24DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT24DI16_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: PKDT24DI16_Node; const buffPtr: PKDT24DI16_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 KDT24DI16_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: PKDT24DI16_Vec; const p1, p2: PKDT24DI16_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: PKDT24DI16_Vec); var i, j: NativeInt; p, t: PKDT24DI16_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: PKDT24DI16_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 := PKDT24DI16_Node(NearestNodes[0]); end; end; function TKDT24DI16.Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT24DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT24DI16.Search(const buff: TKDT24DI16_Vec; var SearchedDistanceMin: Double): PKDT24DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT24DI16.Search(const buff: TKDT24DI16_Vec): PKDT24DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT24DI16.SearchToken(const buff: TKDT24DI16_Vec): TPascalString; var p: PKDT24DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT24DI16.Search(const inBuff: TKDT24DI16_DynamicVecBuffer; var OutBuff: TKDT24DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT24DI16_DynamicVecBuffer; outBuffPtr: PKDT24DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT24DI16_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: PKDT24DI16_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: PKDT24DI16_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 TKDT24DI16.Search(const inBuff: TKDT24DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT24DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT24DI16_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: PKDT24DI16_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: PKDT24DI16_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 TKDT24DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT24DI16_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(TKDT24DI16_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 TKDT24DI16.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 <> KDT24DI16_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(TKDT24DI16_Vec)) <> SizeOf(TKDT24DI16_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 TKDT24DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT24DI16.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 TKDT24DI16.PrintNodeTree(const NodePtr: PKDT24DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT24DI16_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 TKDT24DI16.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 TKDT24DI16.Vec(const s: SystemString): TKDT24DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT24DI16_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 >= KDT24DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT24DI16.Vec(const v: TKDT24DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT24DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT24DI16.Distance(const v1, v2: TKDT24DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT24DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT24DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT24DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT24DI16.Test; var TKDT24DI16_Test: TKDT24DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT24DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT24DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT24DI16_Test := TKDT24DI16.Create; n.Append('...'); SetLength(TKDT24DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT24DI16_Test.TestBuff) - 1 do for j := 0 to KDT24DI16_Axis - 1 do TKDT24DI16_Test.TestBuff[i][j] := i * KDT24DI16_Axis + j; {$IFDEF FPC} TKDT24DI16_Test.BuildKDTreeM(length(TKDT24DI16_Test.TestBuff), nil, @TKDT24DI16_Test.Test_BuildM); {$ELSE FPC} TKDT24DI16_Test.BuildKDTreeM(length(TKDT24DI16_Test.TestBuff), nil, TKDT24DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT24DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT24DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT24DI16_Test.TestBuff) - 1 do begin p := TKDT24DI16_Test.Search(TKDT24DI16_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(TKDT24DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT24DI16_Test.TestBuff)); TKDT24DI16_Test.Search(TKDT24DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT24DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT24DI16_Test.Clear; { kMean test } TKDT24DI16_Test.BuildKDTreeWithCluster(TKDT24DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT24DI16_Test.Search(TKDT24DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT24DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT24DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT24DI16_Test); DoStatus(n); n := ''; end; function TKDT48DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT48DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT48DI16_Node; function SortCompare(const p1, p2: PKDT48DI16_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: PKDT48DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT48DI16_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: PKDT48DI16_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 KDT48DI16_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 TKDT48DI16.GetData(const Index: NativeInt): PKDT48DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT48DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT48DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT48DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT48DI16_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 TKDT48DI16.StoreBuffPtr: PKDT48DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT48DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT48DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT48DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT48DI16.BuildKDTreeWithCluster(const inBuff: TKDT48DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT48DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT48DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT48DI16_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 KDT48DI16_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 TKDT48DI16.BuildKDTreeWithCluster(const inBuff: TKDT48DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT48DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildCall); var TempStoreBuff: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI16_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 KDT48DI16_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 TKDT48DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildMethod); var TempStoreBuff: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI16_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 KDT48DI16_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 TKDT48DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT48DI16_BuildProc); var TempStoreBuff: TKDT48DI16_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(TKDT48DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT48DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT48DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT48DI16_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 KDT48DI16_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 TKDT48DI16.Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT48DI16_Node; var NearestNeighbour: PKDT48DI16_Node; function FindParentNode(const buffPtr: PKDT48DI16_Vec; NodePtr: PKDT48DI16_Node): PKDT48DI16_Node; var Next: PKDT48DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT48DI16_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: PKDT48DI16_Node; const buffPtr: PKDT48DI16_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 KDT48DI16_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: PKDT48DI16_Vec; const p1, p2: PKDT48DI16_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: PKDT48DI16_Vec); var i, j: NativeInt; p, t: PKDT48DI16_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: PKDT48DI16_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 := PKDT48DI16_Node(NearestNodes[0]); end; end; function TKDT48DI16.Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT48DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT48DI16.Search(const buff: TKDT48DI16_Vec; var SearchedDistanceMin: Double): PKDT48DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT48DI16.Search(const buff: TKDT48DI16_Vec): PKDT48DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT48DI16.SearchToken(const buff: TKDT48DI16_Vec): TPascalString; var p: PKDT48DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT48DI16.Search(const inBuff: TKDT48DI16_DynamicVecBuffer; var OutBuff: TKDT48DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT48DI16_DynamicVecBuffer; outBuffPtr: PKDT48DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT48DI16_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: PKDT48DI16_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: PKDT48DI16_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 TKDT48DI16.Search(const inBuff: TKDT48DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT48DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT48DI16_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: PKDT48DI16_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: PKDT48DI16_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 TKDT48DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT48DI16_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(TKDT48DI16_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 TKDT48DI16.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 <> KDT48DI16_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(TKDT48DI16_Vec)) <> SizeOf(TKDT48DI16_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 TKDT48DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT48DI16.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 TKDT48DI16.PrintNodeTree(const NodePtr: PKDT48DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT48DI16_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 TKDT48DI16.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 TKDT48DI16.Vec(const s: SystemString): TKDT48DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT48DI16_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 >= KDT48DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT48DI16.Vec(const v: TKDT48DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT48DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT48DI16.Distance(const v1, v2: TKDT48DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT48DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT48DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT48DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT48DI16.Test; var TKDT48DI16_Test: TKDT48DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT48DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT48DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT48DI16_Test := TKDT48DI16.Create; n.Append('...'); SetLength(TKDT48DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT48DI16_Test.TestBuff) - 1 do for j := 0 to KDT48DI16_Axis - 1 do TKDT48DI16_Test.TestBuff[i][j] := i * KDT48DI16_Axis + j; {$IFDEF FPC} TKDT48DI16_Test.BuildKDTreeM(length(TKDT48DI16_Test.TestBuff), nil, @TKDT48DI16_Test.Test_BuildM); {$ELSE FPC} TKDT48DI16_Test.BuildKDTreeM(length(TKDT48DI16_Test.TestBuff), nil, TKDT48DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT48DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT48DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT48DI16_Test.TestBuff) - 1 do begin p := TKDT48DI16_Test.Search(TKDT48DI16_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(TKDT48DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT48DI16_Test.TestBuff)); TKDT48DI16_Test.Search(TKDT48DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT48DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT48DI16_Test.Clear; { kMean test } TKDT48DI16_Test.BuildKDTreeWithCluster(TKDT48DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT48DI16_Test.Search(TKDT48DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT48DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT48DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT48DI16_Test); DoStatus(n); n := ''; end; function TKDT52DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT52DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT52DI16_Node; function SortCompare(const p1, p2: PKDT52DI16_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: PKDT52DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT52DI16_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: PKDT52DI16_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 KDT52DI16_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 TKDT52DI16.GetData(const Index: NativeInt): PKDT52DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT52DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT52DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT52DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT52DI16_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 TKDT52DI16.StoreBuffPtr: PKDT52DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT52DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT52DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT52DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT52DI16.BuildKDTreeWithCluster(const inBuff: TKDT52DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT52DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT52DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT52DI16_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 KDT52DI16_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 TKDT52DI16.BuildKDTreeWithCluster(const inBuff: TKDT52DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT52DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildCall); var TempStoreBuff: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI16_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 KDT52DI16_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 TKDT52DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildMethod); var TempStoreBuff: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI16_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 KDT52DI16_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 TKDT52DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT52DI16_BuildProc); var TempStoreBuff: TKDT52DI16_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(TKDT52DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT52DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT52DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT52DI16_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 KDT52DI16_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 TKDT52DI16.Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT52DI16_Node; var NearestNeighbour: PKDT52DI16_Node; function FindParentNode(const buffPtr: PKDT52DI16_Vec; NodePtr: PKDT52DI16_Node): PKDT52DI16_Node; var Next: PKDT52DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT52DI16_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: PKDT52DI16_Node; const buffPtr: PKDT52DI16_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 KDT52DI16_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: PKDT52DI16_Vec; const p1, p2: PKDT52DI16_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: PKDT52DI16_Vec); var i, j: NativeInt; p, t: PKDT52DI16_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: PKDT52DI16_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 := PKDT52DI16_Node(NearestNodes[0]); end; end; function TKDT52DI16.Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT52DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT52DI16.Search(const buff: TKDT52DI16_Vec; var SearchedDistanceMin: Double): PKDT52DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT52DI16.Search(const buff: TKDT52DI16_Vec): PKDT52DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT52DI16.SearchToken(const buff: TKDT52DI16_Vec): TPascalString; var p: PKDT52DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT52DI16.Search(const inBuff: TKDT52DI16_DynamicVecBuffer; var OutBuff: TKDT52DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT52DI16_DynamicVecBuffer; outBuffPtr: PKDT52DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT52DI16_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: PKDT52DI16_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: PKDT52DI16_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 TKDT52DI16.Search(const inBuff: TKDT52DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT52DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT52DI16_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: PKDT52DI16_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: PKDT52DI16_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 TKDT52DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT52DI16_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(TKDT52DI16_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 TKDT52DI16.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 <> KDT52DI16_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(TKDT52DI16_Vec)) <> SizeOf(TKDT52DI16_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 TKDT52DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT52DI16.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 TKDT52DI16.PrintNodeTree(const NodePtr: PKDT52DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT52DI16_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 TKDT52DI16.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 TKDT52DI16.Vec(const s: SystemString): TKDT52DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT52DI16_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 >= KDT52DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT52DI16.Vec(const v: TKDT52DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT52DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT52DI16.Distance(const v1, v2: TKDT52DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT52DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT52DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT52DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT52DI16.Test; var TKDT52DI16_Test: TKDT52DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT52DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT52DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT52DI16_Test := TKDT52DI16.Create; n.Append('...'); SetLength(TKDT52DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT52DI16_Test.TestBuff) - 1 do for j := 0 to KDT52DI16_Axis - 1 do TKDT52DI16_Test.TestBuff[i][j] := i * KDT52DI16_Axis + j; {$IFDEF FPC} TKDT52DI16_Test.BuildKDTreeM(length(TKDT52DI16_Test.TestBuff), nil, @TKDT52DI16_Test.Test_BuildM); {$ELSE FPC} TKDT52DI16_Test.BuildKDTreeM(length(TKDT52DI16_Test.TestBuff), nil, TKDT52DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT52DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT52DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT52DI16_Test.TestBuff) - 1 do begin p := TKDT52DI16_Test.Search(TKDT52DI16_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(TKDT52DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT52DI16_Test.TestBuff)); TKDT52DI16_Test.Search(TKDT52DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT52DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT52DI16_Test.Clear; { kMean test } TKDT52DI16_Test.BuildKDTreeWithCluster(TKDT52DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT52DI16_Test.Search(TKDT52DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT52DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT52DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT52DI16_Test); DoStatus(n); n := ''; end; function TKDT64DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT64DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT64DI16_Node; function SortCompare(const p1, p2: PKDT64DI16_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: PKDT64DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT64DI16_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: PKDT64DI16_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 KDT64DI16_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 TKDT64DI16.GetData(const Index: NativeInt): PKDT64DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT64DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT64DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT64DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT64DI16_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 TKDT64DI16.StoreBuffPtr: PKDT64DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT64DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT64DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT64DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT64DI16.BuildKDTreeWithCluster(const inBuff: TKDT64DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT64DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT64DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT64DI16_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 KDT64DI16_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 TKDT64DI16.BuildKDTreeWithCluster(const inBuff: TKDT64DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT64DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildCall); var TempStoreBuff: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI16_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 KDT64DI16_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 TKDT64DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildMethod); var TempStoreBuff: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI16_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 KDT64DI16_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 TKDT64DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT64DI16_BuildProc); var TempStoreBuff: TKDT64DI16_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(TKDT64DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT64DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT64DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT64DI16_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 KDT64DI16_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 TKDT64DI16.Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT64DI16_Node; var NearestNeighbour: PKDT64DI16_Node; function FindParentNode(const buffPtr: PKDT64DI16_Vec; NodePtr: PKDT64DI16_Node): PKDT64DI16_Node; var Next: PKDT64DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT64DI16_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: PKDT64DI16_Node; const buffPtr: PKDT64DI16_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 KDT64DI16_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: PKDT64DI16_Vec; const p1, p2: PKDT64DI16_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: PKDT64DI16_Vec); var i, j: NativeInt; p, t: PKDT64DI16_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: PKDT64DI16_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 := PKDT64DI16_Node(NearestNodes[0]); end; end; function TKDT64DI16.Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT64DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT64DI16.Search(const buff: TKDT64DI16_Vec; var SearchedDistanceMin: Double): PKDT64DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT64DI16.Search(const buff: TKDT64DI16_Vec): PKDT64DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT64DI16.SearchToken(const buff: TKDT64DI16_Vec): TPascalString; var p: PKDT64DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT64DI16.Search(const inBuff: TKDT64DI16_DynamicVecBuffer; var OutBuff: TKDT64DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT64DI16_DynamicVecBuffer; outBuffPtr: PKDT64DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT64DI16_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: PKDT64DI16_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: PKDT64DI16_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 TKDT64DI16.Search(const inBuff: TKDT64DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT64DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT64DI16_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: PKDT64DI16_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: PKDT64DI16_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 TKDT64DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT64DI16_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(TKDT64DI16_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 TKDT64DI16.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 <> KDT64DI16_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(TKDT64DI16_Vec)) <> SizeOf(TKDT64DI16_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 TKDT64DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT64DI16.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 TKDT64DI16.PrintNodeTree(const NodePtr: PKDT64DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT64DI16_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 TKDT64DI16.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 TKDT64DI16.Vec(const s: SystemString): TKDT64DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT64DI16_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 >= KDT64DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT64DI16.Vec(const v: TKDT64DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT64DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT64DI16.Distance(const v1, v2: TKDT64DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT64DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT64DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT64DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT64DI16.Test; var TKDT64DI16_Test: TKDT64DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT64DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT64DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT64DI16_Test := TKDT64DI16.Create; n.Append('...'); SetLength(TKDT64DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT64DI16_Test.TestBuff) - 1 do for j := 0 to KDT64DI16_Axis - 1 do TKDT64DI16_Test.TestBuff[i][j] := i * KDT64DI16_Axis + j; {$IFDEF FPC} TKDT64DI16_Test.BuildKDTreeM(length(TKDT64DI16_Test.TestBuff), nil, @TKDT64DI16_Test.Test_BuildM); {$ELSE FPC} TKDT64DI16_Test.BuildKDTreeM(length(TKDT64DI16_Test.TestBuff), nil, TKDT64DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT64DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT64DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT64DI16_Test.TestBuff) - 1 do begin p := TKDT64DI16_Test.Search(TKDT64DI16_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(TKDT64DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT64DI16_Test.TestBuff)); TKDT64DI16_Test.Search(TKDT64DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT64DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT64DI16_Test.Clear; { kMean test } TKDT64DI16_Test.BuildKDTreeWithCluster(TKDT64DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT64DI16_Test.Search(TKDT64DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT64DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT64DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT64DI16_Test); DoStatus(n); n := ''; end; function TKDT96DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT96DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT96DI16_Node; function SortCompare(const p1, p2: PKDT96DI16_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: PKDT96DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT96DI16_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: PKDT96DI16_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 KDT96DI16_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 TKDT96DI16.GetData(const Index: NativeInt): PKDT96DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT96DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT96DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT96DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT96DI16_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 TKDT96DI16.StoreBuffPtr: PKDT96DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT96DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT96DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT96DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT96DI16.BuildKDTreeWithCluster(const inBuff: TKDT96DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT96DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT96DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT96DI16_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 KDT96DI16_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 TKDT96DI16.BuildKDTreeWithCluster(const inBuff: TKDT96DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT96DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildCall); var TempStoreBuff: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI16_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 KDT96DI16_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 TKDT96DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildMethod); var TempStoreBuff: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI16_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 KDT96DI16_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 TKDT96DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT96DI16_BuildProc); var TempStoreBuff: TKDT96DI16_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(TKDT96DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT96DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT96DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT96DI16_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 KDT96DI16_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 TKDT96DI16.Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT96DI16_Node; var NearestNeighbour: PKDT96DI16_Node; function FindParentNode(const buffPtr: PKDT96DI16_Vec; NodePtr: PKDT96DI16_Node): PKDT96DI16_Node; var Next: PKDT96DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT96DI16_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: PKDT96DI16_Node; const buffPtr: PKDT96DI16_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 KDT96DI16_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: PKDT96DI16_Vec; const p1, p2: PKDT96DI16_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: PKDT96DI16_Vec); var i, j: NativeInt; p, t: PKDT96DI16_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: PKDT96DI16_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 := PKDT96DI16_Node(NearestNodes[0]); end; end; function TKDT96DI16.Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT96DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT96DI16.Search(const buff: TKDT96DI16_Vec; var SearchedDistanceMin: Double): PKDT96DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT96DI16.Search(const buff: TKDT96DI16_Vec): PKDT96DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT96DI16.SearchToken(const buff: TKDT96DI16_Vec): TPascalString; var p: PKDT96DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT96DI16.Search(const inBuff: TKDT96DI16_DynamicVecBuffer; var OutBuff: TKDT96DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT96DI16_DynamicVecBuffer; outBuffPtr: PKDT96DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT96DI16_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: PKDT96DI16_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: PKDT96DI16_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 TKDT96DI16.Search(const inBuff: TKDT96DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT96DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT96DI16_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: PKDT96DI16_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: PKDT96DI16_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 TKDT96DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT96DI16_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(TKDT96DI16_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 TKDT96DI16.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 <> KDT96DI16_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(TKDT96DI16_Vec)) <> SizeOf(TKDT96DI16_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 TKDT96DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT96DI16.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 TKDT96DI16.PrintNodeTree(const NodePtr: PKDT96DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT96DI16_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 TKDT96DI16.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 TKDT96DI16.Vec(const s: SystemString): TKDT96DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT96DI16_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 >= KDT96DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT96DI16.Vec(const v: TKDT96DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT96DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT96DI16.Distance(const v1, v2: TKDT96DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT96DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT96DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT96DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT96DI16.Test; var TKDT96DI16_Test: TKDT96DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT96DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT96DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT96DI16_Test := TKDT96DI16.Create; n.Append('...'); SetLength(TKDT96DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT96DI16_Test.TestBuff) - 1 do for j := 0 to KDT96DI16_Axis - 1 do TKDT96DI16_Test.TestBuff[i][j] := i * KDT96DI16_Axis + j; {$IFDEF FPC} TKDT96DI16_Test.BuildKDTreeM(length(TKDT96DI16_Test.TestBuff), nil, @TKDT96DI16_Test.Test_BuildM); {$ELSE FPC} TKDT96DI16_Test.BuildKDTreeM(length(TKDT96DI16_Test.TestBuff), nil, TKDT96DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT96DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT96DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT96DI16_Test.TestBuff) - 1 do begin p := TKDT96DI16_Test.Search(TKDT96DI16_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(TKDT96DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT96DI16_Test.TestBuff)); TKDT96DI16_Test.Search(TKDT96DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT96DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT96DI16_Test.Clear; { kMean test } TKDT96DI16_Test.BuildKDTreeWithCluster(TKDT96DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT96DI16_Test.Search(TKDT96DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT96DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT96DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT96DI16_Test); DoStatus(n); n := ''; end; function TKDT128DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT128DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT128DI16_Node; function SortCompare(const p1, p2: PKDT128DI16_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: PKDT128DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT128DI16_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: PKDT128DI16_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 KDT128DI16_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 TKDT128DI16.GetData(const Index: NativeInt): PKDT128DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT128DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT128DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT128DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT128DI16_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 TKDT128DI16.StoreBuffPtr: PKDT128DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT128DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT128DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT128DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT128DI16.BuildKDTreeWithCluster(const inBuff: TKDT128DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT128DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT128DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT128DI16_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 KDT128DI16_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 TKDT128DI16.BuildKDTreeWithCluster(const inBuff: TKDT128DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT128DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildCall); var TempStoreBuff: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI16_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 KDT128DI16_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 TKDT128DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildMethod); var TempStoreBuff: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI16_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 KDT128DI16_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 TKDT128DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT128DI16_BuildProc); var TempStoreBuff: TKDT128DI16_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(TKDT128DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT128DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT128DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT128DI16_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 KDT128DI16_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 TKDT128DI16.Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT128DI16_Node; var NearestNeighbour: PKDT128DI16_Node; function FindParentNode(const buffPtr: PKDT128DI16_Vec; NodePtr: PKDT128DI16_Node): PKDT128DI16_Node; var Next: PKDT128DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT128DI16_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: PKDT128DI16_Node; const buffPtr: PKDT128DI16_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 KDT128DI16_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: PKDT128DI16_Vec; const p1, p2: PKDT128DI16_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: PKDT128DI16_Vec); var i, j: NativeInt; p, t: PKDT128DI16_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: PKDT128DI16_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 := PKDT128DI16_Node(NearestNodes[0]); end; end; function TKDT128DI16.Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT128DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT128DI16.Search(const buff: TKDT128DI16_Vec; var SearchedDistanceMin: Double): PKDT128DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT128DI16.Search(const buff: TKDT128DI16_Vec): PKDT128DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT128DI16.SearchToken(const buff: TKDT128DI16_Vec): TPascalString; var p: PKDT128DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT128DI16.Search(const inBuff: TKDT128DI16_DynamicVecBuffer; var OutBuff: TKDT128DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT128DI16_DynamicVecBuffer; outBuffPtr: PKDT128DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT128DI16_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: PKDT128DI16_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: PKDT128DI16_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 TKDT128DI16.Search(const inBuff: TKDT128DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT128DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT128DI16_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: PKDT128DI16_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: PKDT128DI16_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 TKDT128DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT128DI16_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(TKDT128DI16_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 TKDT128DI16.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 <> KDT128DI16_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(TKDT128DI16_Vec)) <> SizeOf(TKDT128DI16_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 TKDT128DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT128DI16.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 TKDT128DI16.PrintNodeTree(const NodePtr: PKDT128DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT128DI16_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 TKDT128DI16.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 TKDT128DI16.Vec(const s: SystemString): TKDT128DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT128DI16_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 >= KDT128DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT128DI16.Vec(const v: TKDT128DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT128DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT128DI16.Distance(const v1, v2: TKDT128DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT128DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT128DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT128DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT128DI16.Test; var TKDT128DI16_Test: TKDT128DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT128DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT128DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT128DI16_Test := TKDT128DI16.Create; n.Append('...'); SetLength(TKDT128DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT128DI16_Test.TestBuff) - 1 do for j := 0 to KDT128DI16_Axis - 1 do TKDT128DI16_Test.TestBuff[i][j] := i * KDT128DI16_Axis + j; {$IFDEF FPC} TKDT128DI16_Test.BuildKDTreeM(length(TKDT128DI16_Test.TestBuff), nil, @TKDT128DI16_Test.Test_BuildM); {$ELSE FPC} TKDT128DI16_Test.BuildKDTreeM(length(TKDT128DI16_Test.TestBuff), nil, TKDT128DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT128DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT128DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT128DI16_Test.TestBuff) - 1 do begin p := TKDT128DI16_Test.Search(TKDT128DI16_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(TKDT128DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT128DI16_Test.TestBuff)); TKDT128DI16_Test.Search(TKDT128DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT128DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT128DI16_Test.Clear; { kMean test } TKDT128DI16_Test.BuildKDTreeWithCluster(TKDT128DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT128DI16_Test.Search(TKDT128DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT128DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT128DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT128DI16_Test); DoStatus(n); n := ''; end; function TKDT156DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT156DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT156DI16_Node; function SortCompare(const p1, p2: PKDT156DI16_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: PKDT156DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT156DI16_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: PKDT156DI16_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 KDT156DI16_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 TKDT156DI16.GetData(const Index: NativeInt): PKDT156DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT156DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT156DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT156DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT156DI16_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 TKDT156DI16.StoreBuffPtr: PKDT156DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT156DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT156DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT156DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT156DI16.BuildKDTreeWithCluster(const inBuff: TKDT156DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT156DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT156DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT156DI16_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 KDT156DI16_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 TKDT156DI16.BuildKDTreeWithCluster(const inBuff: TKDT156DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT156DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildCall); var TempStoreBuff: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI16_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 KDT156DI16_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 TKDT156DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildMethod); var TempStoreBuff: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI16_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 KDT156DI16_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 TKDT156DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT156DI16_BuildProc); var TempStoreBuff: TKDT156DI16_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(TKDT156DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT156DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT156DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT156DI16_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 KDT156DI16_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 TKDT156DI16.Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT156DI16_Node; var NearestNeighbour: PKDT156DI16_Node; function FindParentNode(const buffPtr: PKDT156DI16_Vec; NodePtr: PKDT156DI16_Node): PKDT156DI16_Node; var Next: PKDT156DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT156DI16_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: PKDT156DI16_Node; const buffPtr: PKDT156DI16_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 KDT156DI16_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: PKDT156DI16_Vec; const p1, p2: PKDT156DI16_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: PKDT156DI16_Vec); var i, j: NativeInt; p, t: PKDT156DI16_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: PKDT156DI16_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 := PKDT156DI16_Node(NearestNodes[0]); end; end; function TKDT156DI16.Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT156DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT156DI16.Search(const buff: TKDT156DI16_Vec; var SearchedDistanceMin: Double): PKDT156DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT156DI16.Search(const buff: TKDT156DI16_Vec): PKDT156DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT156DI16.SearchToken(const buff: TKDT156DI16_Vec): TPascalString; var p: PKDT156DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT156DI16.Search(const inBuff: TKDT156DI16_DynamicVecBuffer; var OutBuff: TKDT156DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT156DI16_DynamicVecBuffer; outBuffPtr: PKDT156DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT156DI16_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: PKDT156DI16_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: PKDT156DI16_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 TKDT156DI16.Search(const inBuff: TKDT156DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT156DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT156DI16_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: PKDT156DI16_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: PKDT156DI16_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 TKDT156DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT156DI16_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(TKDT156DI16_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 TKDT156DI16.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 <> KDT156DI16_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(TKDT156DI16_Vec)) <> SizeOf(TKDT156DI16_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 TKDT156DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT156DI16.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 TKDT156DI16.PrintNodeTree(const NodePtr: PKDT156DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT156DI16_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 TKDT156DI16.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 TKDT156DI16.Vec(const s: SystemString): TKDT156DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT156DI16_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 >= KDT156DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT156DI16.Vec(const v: TKDT156DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT156DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT156DI16.Distance(const v1, v2: TKDT156DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT156DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT156DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT156DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT156DI16.Test; var TKDT156DI16_Test: TKDT156DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT156DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT156DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT156DI16_Test := TKDT156DI16.Create; n.Append('...'); SetLength(TKDT156DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT156DI16_Test.TestBuff) - 1 do for j := 0 to KDT156DI16_Axis - 1 do TKDT156DI16_Test.TestBuff[i][j] := i * KDT156DI16_Axis + j; {$IFDEF FPC} TKDT156DI16_Test.BuildKDTreeM(length(TKDT156DI16_Test.TestBuff), nil, @TKDT156DI16_Test.Test_BuildM); {$ELSE FPC} TKDT156DI16_Test.BuildKDTreeM(length(TKDT156DI16_Test.TestBuff), nil, TKDT156DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT156DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT156DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT156DI16_Test.TestBuff) - 1 do begin p := TKDT156DI16_Test.Search(TKDT156DI16_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(TKDT156DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT156DI16_Test.TestBuff)); TKDT156DI16_Test.Search(TKDT156DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT156DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT156DI16_Test.Clear; { kMean test } TKDT156DI16_Test.BuildKDTreeWithCluster(TKDT156DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT156DI16_Test.Search(TKDT156DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT156DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT156DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT156DI16_Test); DoStatus(n); n := ''; end; function TKDT192DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT192DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT192DI16_Node; function SortCompare(const p1, p2: PKDT192DI16_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: PKDT192DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT192DI16_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: PKDT192DI16_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 KDT192DI16_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 TKDT192DI16.GetData(const Index: NativeInt): PKDT192DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT192DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT192DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT192DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT192DI16_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 TKDT192DI16.StoreBuffPtr: PKDT192DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT192DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT192DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT192DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT192DI16.BuildKDTreeWithCluster(const inBuff: TKDT192DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT192DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT192DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT192DI16_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 KDT192DI16_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 TKDT192DI16.BuildKDTreeWithCluster(const inBuff: TKDT192DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT192DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildCall); var TempStoreBuff: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI16_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 KDT192DI16_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 TKDT192DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildMethod); var TempStoreBuff: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI16_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 KDT192DI16_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 TKDT192DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT192DI16_BuildProc); var TempStoreBuff: TKDT192DI16_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(TKDT192DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT192DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT192DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT192DI16_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 KDT192DI16_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 TKDT192DI16.Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT192DI16_Node; var NearestNeighbour: PKDT192DI16_Node; function FindParentNode(const buffPtr: PKDT192DI16_Vec; NodePtr: PKDT192DI16_Node): PKDT192DI16_Node; var Next: PKDT192DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT192DI16_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: PKDT192DI16_Node; const buffPtr: PKDT192DI16_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 KDT192DI16_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: PKDT192DI16_Vec; const p1, p2: PKDT192DI16_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: PKDT192DI16_Vec); var i, j: NativeInt; p, t: PKDT192DI16_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: PKDT192DI16_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 := PKDT192DI16_Node(NearestNodes[0]); end; end; function TKDT192DI16.Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT192DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT192DI16.Search(const buff: TKDT192DI16_Vec; var SearchedDistanceMin: Double): PKDT192DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT192DI16.Search(const buff: TKDT192DI16_Vec): PKDT192DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT192DI16.SearchToken(const buff: TKDT192DI16_Vec): TPascalString; var p: PKDT192DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT192DI16.Search(const inBuff: TKDT192DI16_DynamicVecBuffer; var OutBuff: TKDT192DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT192DI16_DynamicVecBuffer; outBuffPtr: PKDT192DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT192DI16_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: PKDT192DI16_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: PKDT192DI16_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 TKDT192DI16.Search(const inBuff: TKDT192DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT192DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT192DI16_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: PKDT192DI16_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: PKDT192DI16_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 TKDT192DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT192DI16_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(TKDT192DI16_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 TKDT192DI16.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 <> KDT192DI16_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(TKDT192DI16_Vec)) <> SizeOf(TKDT192DI16_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 TKDT192DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT192DI16.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 TKDT192DI16.PrintNodeTree(const NodePtr: PKDT192DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT192DI16_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 TKDT192DI16.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 TKDT192DI16.Vec(const s: SystemString): TKDT192DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT192DI16_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 >= KDT192DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT192DI16.Vec(const v: TKDT192DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT192DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT192DI16.Distance(const v1, v2: TKDT192DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT192DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT192DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT192DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT192DI16.Test; var TKDT192DI16_Test: TKDT192DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT192DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT192DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT192DI16_Test := TKDT192DI16.Create; n.Append('...'); SetLength(TKDT192DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT192DI16_Test.TestBuff) - 1 do for j := 0 to KDT192DI16_Axis - 1 do TKDT192DI16_Test.TestBuff[i][j] := i * KDT192DI16_Axis + j; {$IFDEF FPC} TKDT192DI16_Test.BuildKDTreeM(length(TKDT192DI16_Test.TestBuff), nil, @TKDT192DI16_Test.Test_BuildM); {$ELSE FPC} TKDT192DI16_Test.BuildKDTreeM(length(TKDT192DI16_Test.TestBuff), nil, TKDT192DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT192DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT192DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT192DI16_Test.TestBuff) - 1 do begin p := TKDT192DI16_Test.Search(TKDT192DI16_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(TKDT192DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT192DI16_Test.TestBuff)); TKDT192DI16_Test.Search(TKDT192DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT192DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT192DI16_Test.Clear; { kMean test } TKDT192DI16_Test.BuildKDTreeWithCluster(TKDT192DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT192DI16_Test.Search(TKDT192DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT192DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT192DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT192DI16_Test); DoStatus(n); n := ''; end; function TKDT256DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT256DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT256DI16_Node; function SortCompare(const p1, p2: PKDT256DI16_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: PKDT256DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT256DI16_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: PKDT256DI16_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 KDT256DI16_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 TKDT256DI16.GetData(const Index: NativeInt): PKDT256DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT256DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT256DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT256DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT256DI16_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 TKDT256DI16.StoreBuffPtr: PKDT256DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT256DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT256DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT256DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT256DI16.BuildKDTreeWithCluster(const inBuff: TKDT256DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT256DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT256DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT256DI16_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 KDT256DI16_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 TKDT256DI16.BuildKDTreeWithCluster(const inBuff: TKDT256DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT256DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildCall); var TempStoreBuff: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI16_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 KDT256DI16_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 TKDT256DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildMethod); var TempStoreBuff: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI16_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 KDT256DI16_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 TKDT256DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT256DI16_BuildProc); var TempStoreBuff: TKDT256DI16_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(TKDT256DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT256DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT256DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT256DI16_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 KDT256DI16_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 TKDT256DI16.Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT256DI16_Node; var NearestNeighbour: PKDT256DI16_Node; function FindParentNode(const buffPtr: PKDT256DI16_Vec; NodePtr: PKDT256DI16_Node): PKDT256DI16_Node; var Next: PKDT256DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT256DI16_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: PKDT256DI16_Node; const buffPtr: PKDT256DI16_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 KDT256DI16_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: PKDT256DI16_Vec; const p1, p2: PKDT256DI16_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: PKDT256DI16_Vec); var i, j: NativeInt; p, t: PKDT256DI16_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: PKDT256DI16_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 := PKDT256DI16_Node(NearestNodes[0]); end; end; function TKDT256DI16.Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT256DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT256DI16.Search(const buff: TKDT256DI16_Vec; var SearchedDistanceMin: Double): PKDT256DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT256DI16.Search(const buff: TKDT256DI16_Vec): PKDT256DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT256DI16.SearchToken(const buff: TKDT256DI16_Vec): TPascalString; var p: PKDT256DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT256DI16.Search(const inBuff: TKDT256DI16_DynamicVecBuffer; var OutBuff: TKDT256DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT256DI16_DynamicVecBuffer; outBuffPtr: PKDT256DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT256DI16_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: PKDT256DI16_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: PKDT256DI16_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 TKDT256DI16.Search(const inBuff: TKDT256DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT256DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT256DI16_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: PKDT256DI16_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: PKDT256DI16_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 TKDT256DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT256DI16_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(TKDT256DI16_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 TKDT256DI16.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 <> KDT256DI16_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(TKDT256DI16_Vec)) <> SizeOf(TKDT256DI16_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 TKDT256DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT256DI16.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 TKDT256DI16.PrintNodeTree(const NodePtr: PKDT256DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT256DI16_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 TKDT256DI16.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 TKDT256DI16.Vec(const s: SystemString): TKDT256DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT256DI16_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 >= KDT256DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT256DI16.Vec(const v: TKDT256DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT256DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT256DI16.Distance(const v1, v2: TKDT256DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT256DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT256DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT256DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT256DI16.Test; var TKDT256DI16_Test: TKDT256DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT256DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT256DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT256DI16_Test := TKDT256DI16.Create; n.Append('...'); SetLength(TKDT256DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT256DI16_Test.TestBuff) - 1 do for j := 0 to KDT256DI16_Axis - 1 do TKDT256DI16_Test.TestBuff[i][j] := i * KDT256DI16_Axis + j; {$IFDEF FPC} TKDT256DI16_Test.BuildKDTreeM(length(TKDT256DI16_Test.TestBuff), nil, @TKDT256DI16_Test.Test_BuildM); {$ELSE FPC} TKDT256DI16_Test.BuildKDTreeM(length(TKDT256DI16_Test.TestBuff), nil, TKDT256DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT256DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT256DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT256DI16_Test.TestBuff) - 1 do begin p := TKDT256DI16_Test.Search(TKDT256DI16_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(TKDT256DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT256DI16_Test.TestBuff)); TKDT256DI16_Test.Search(TKDT256DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT256DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT256DI16_Test.Clear; { kMean test } TKDT256DI16_Test.BuildKDTreeWithCluster(TKDT256DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT256DI16_Test.Search(TKDT256DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT256DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT256DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT256DI16_Test); DoStatus(n); n := ''; end; function TKDT384DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT384DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT384DI16_Node; function SortCompare(const p1, p2: PKDT384DI16_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: PKDT384DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT384DI16_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: PKDT384DI16_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 KDT384DI16_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 TKDT384DI16.GetData(const Index: NativeInt): PKDT384DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT384DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT384DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT384DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT384DI16_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 TKDT384DI16.StoreBuffPtr: PKDT384DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT384DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT384DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT384DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT384DI16.BuildKDTreeWithCluster(const inBuff: TKDT384DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT384DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT384DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT384DI16_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 KDT384DI16_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 TKDT384DI16.BuildKDTreeWithCluster(const inBuff: TKDT384DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT384DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildCall); var TempStoreBuff: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI16_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 KDT384DI16_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 TKDT384DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildMethod); var TempStoreBuff: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI16_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 KDT384DI16_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 TKDT384DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT384DI16_BuildProc); var TempStoreBuff: TKDT384DI16_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(TKDT384DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT384DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT384DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT384DI16_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 KDT384DI16_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 TKDT384DI16.Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT384DI16_Node; var NearestNeighbour: PKDT384DI16_Node; function FindParentNode(const buffPtr: PKDT384DI16_Vec; NodePtr: PKDT384DI16_Node): PKDT384DI16_Node; var Next: PKDT384DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT384DI16_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: PKDT384DI16_Node; const buffPtr: PKDT384DI16_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 KDT384DI16_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: PKDT384DI16_Vec; const p1, p2: PKDT384DI16_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: PKDT384DI16_Vec); var i, j: NativeInt; p, t: PKDT384DI16_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: PKDT384DI16_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 := PKDT384DI16_Node(NearestNodes[0]); end; end; function TKDT384DI16.Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT384DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT384DI16.Search(const buff: TKDT384DI16_Vec; var SearchedDistanceMin: Double): PKDT384DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT384DI16.Search(const buff: TKDT384DI16_Vec): PKDT384DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT384DI16.SearchToken(const buff: TKDT384DI16_Vec): TPascalString; var p: PKDT384DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT384DI16.Search(const inBuff: TKDT384DI16_DynamicVecBuffer; var OutBuff: TKDT384DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT384DI16_DynamicVecBuffer; outBuffPtr: PKDT384DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT384DI16_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: PKDT384DI16_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: PKDT384DI16_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 TKDT384DI16.Search(const inBuff: TKDT384DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT384DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT384DI16_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: PKDT384DI16_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: PKDT384DI16_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 TKDT384DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT384DI16_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(TKDT384DI16_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 TKDT384DI16.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 <> KDT384DI16_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(TKDT384DI16_Vec)) <> SizeOf(TKDT384DI16_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 TKDT384DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT384DI16.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 TKDT384DI16.PrintNodeTree(const NodePtr: PKDT384DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT384DI16_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 TKDT384DI16.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 TKDT384DI16.Vec(const s: SystemString): TKDT384DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT384DI16_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 >= KDT384DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT384DI16.Vec(const v: TKDT384DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT384DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT384DI16.Distance(const v1, v2: TKDT384DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT384DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT384DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT384DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT384DI16.Test; var TKDT384DI16_Test: TKDT384DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT384DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT384DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT384DI16_Test := TKDT384DI16.Create; n.Append('...'); SetLength(TKDT384DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT384DI16_Test.TestBuff) - 1 do for j := 0 to KDT384DI16_Axis - 1 do TKDT384DI16_Test.TestBuff[i][j] := i * KDT384DI16_Axis + j; {$IFDEF FPC} TKDT384DI16_Test.BuildKDTreeM(length(TKDT384DI16_Test.TestBuff), nil, @TKDT384DI16_Test.Test_BuildM); {$ELSE FPC} TKDT384DI16_Test.BuildKDTreeM(length(TKDT384DI16_Test.TestBuff), nil, TKDT384DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT384DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT384DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT384DI16_Test.TestBuff) - 1 do begin p := TKDT384DI16_Test.Search(TKDT384DI16_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(TKDT384DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT384DI16_Test.TestBuff)); TKDT384DI16_Test.Search(TKDT384DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT384DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT384DI16_Test.Clear; { kMean test } TKDT384DI16_Test.BuildKDTreeWithCluster(TKDT384DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT384DI16_Test.Search(TKDT384DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT384DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT384DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT384DI16_Test); DoStatus(n); n := ''; end; function TKDT512DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT512DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT512DI16_Node; function SortCompare(const p1, p2: PKDT512DI16_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: PKDT512DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT512DI16_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: PKDT512DI16_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 KDT512DI16_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 TKDT512DI16.GetData(const Index: NativeInt): PKDT512DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT512DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT512DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT512DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT512DI16_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 TKDT512DI16.StoreBuffPtr: PKDT512DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT512DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT512DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT512DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT512DI16.BuildKDTreeWithCluster(const inBuff: TKDT512DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT512DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT512DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT512DI16_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 KDT512DI16_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 TKDT512DI16.BuildKDTreeWithCluster(const inBuff: TKDT512DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT512DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildCall); var TempStoreBuff: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI16_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 KDT512DI16_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 TKDT512DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildMethod); var TempStoreBuff: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI16_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 KDT512DI16_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 TKDT512DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT512DI16_BuildProc); var TempStoreBuff: TKDT512DI16_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(TKDT512DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT512DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT512DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT512DI16_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 KDT512DI16_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 TKDT512DI16.Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT512DI16_Node; var NearestNeighbour: PKDT512DI16_Node; function FindParentNode(const buffPtr: PKDT512DI16_Vec; NodePtr: PKDT512DI16_Node): PKDT512DI16_Node; var Next: PKDT512DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT512DI16_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: PKDT512DI16_Node; const buffPtr: PKDT512DI16_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 KDT512DI16_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: PKDT512DI16_Vec; const p1, p2: PKDT512DI16_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: PKDT512DI16_Vec); var i, j: NativeInt; p, t: PKDT512DI16_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: PKDT512DI16_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 := PKDT512DI16_Node(NearestNodes[0]); end; end; function TKDT512DI16.Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT512DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT512DI16.Search(const buff: TKDT512DI16_Vec; var SearchedDistanceMin: Double): PKDT512DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT512DI16.Search(const buff: TKDT512DI16_Vec): PKDT512DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT512DI16.SearchToken(const buff: TKDT512DI16_Vec): TPascalString; var p: PKDT512DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT512DI16.Search(const inBuff: TKDT512DI16_DynamicVecBuffer; var OutBuff: TKDT512DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT512DI16_DynamicVecBuffer; outBuffPtr: PKDT512DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT512DI16_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: PKDT512DI16_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: PKDT512DI16_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 TKDT512DI16.Search(const inBuff: TKDT512DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT512DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT512DI16_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: PKDT512DI16_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: PKDT512DI16_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 TKDT512DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT512DI16_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(TKDT512DI16_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 TKDT512DI16.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 <> KDT512DI16_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(TKDT512DI16_Vec)) <> SizeOf(TKDT512DI16_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 TKDT512DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT512DI16.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 TKDT512DI16.PrintNodeTree(const NodePtr: PKDT512DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT512DI16_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 TKDT512DI16.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 TKDT512DI16.Vec(const s: SystemString): TKDT512DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT512DI16_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 >= KDT512DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT512DI16.Vec(const v: TKDT512DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT512DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT512DI16.Distance(const v1, v2: TKDT512DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT512DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT512DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT512DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT512DI16.Test; var TKDT512DI16_Test: TKDT512DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT512DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT512DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT512DI16_Test := TKDT512DI16.Create; n.Append('...'); SetLength(TKDT512DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT512DI16_Test.TestBuff) - 1 do for j := 0 to KDT512DI16_Axis - 1 do TKDT512DI16_Test.TestBuff[i][j] := i * KDT512DI16_Axis + j; {$IFDEF FPC} TKDT512DI16_Test.BuildKDTreeM(length(TKDT512DI16_Test.TestBuff), nil, @TKDT512DI16_Test.Test_BuildM); {$ELSE FPC} TKDT512DI16_Test.BuildKDTreeM(length(TKDT512DI16_Test.TestBuff), nil, TKDT512DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT512DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT512DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT512DI16_Test.TestBuff) - 1 do begin p := TKDT512DI16_Test.Search(TKDT512DI16_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(TKDT512DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT512DI16_Test.TestBuff)); TKDT512DI16_Test.Search(TKDT512DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT512DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT512DI16_Test.Clear; { kMean test } TKDT512DI16_Test.BuildKDTreeWithCluster(TKDT512DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT512DI16_Test.Search(TKDT512DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT512DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT512DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT512DI16_Test); DoStatus(n); n := ''; end; function TKDT800DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT800DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT800DI16_Node; function SortCompare(const p1, p2: PKDT800DI16_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: PKDT800DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT800DI16_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: PKDT800DI16_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 KDT800DI16_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 TKDT800DI16.GetData(const Index: NativeInt): PKDT800DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT800DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT800DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT800DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT800DI16_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 TKDT800DI16.StoreBuffPtr: PKDT800DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT800DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT800DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT800DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT800DI16.BuildKDTreeWithCluster(const inBuff: TKDT800DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT800DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT800DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT800DI16_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 KDT800DI16_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 TKDT800DI16.BuildKDTreeWithCluster(const inBuff: TKDT800DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT800DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildCall); var TempStoreBuff: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI16_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 KDT800DI16_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 TKDT800DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildMethod); var TempStoreBuff: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI16_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 KDT800DI16_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 TKDT800DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT800DI16_BuildProc); var TempStoreBuff: TKDT800DI16_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(TKDT800DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT800DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT800DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT800DI16_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 KDT800DI16_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 TKDT800DI16.Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT800DI16_Node; var NearestNeighbour: PKDT800DI16_Node; function FindParentNode(const buffPtr: PKDT800DI16_Vec; NodePtr: PKDT800DI16_Node): PKDT800DI16_Node; var Next: PKDT800DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT800DI16_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: PKDT800DI16_Node; const buffPtr: PKDT800DI16_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 KDT800DI16_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: PKDT800DI16_Vec; const p1, p2: PKDT800DI16_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: PKDT800DI16_Vec); var i, j: NativeInt; p, t: PKDT800DI16_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: PKDT800DI16_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 := PKDT800DI16_Node(NearestNodes[0]); end; end; function TKDT800DI16.Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT800DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT800DI16.Search(const buff: TKDT800DI16_Vec; var SearchedDistanceMin: Double): PKDT800DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT800DI16.Search(const buff: TKDT800DI16_Vec): PKDT800DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT800DI16.SearchToken(const buff: TKDT800DI16_Vec): TPascalString; var p: PKDT800DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT800DI16.Search(const inBuff: TKDT800DI16_DynamicVecBuffer; var OutBuff: TKDT800DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT800DI16_DynamicVecBuffer; outBuffPtr: PKDT800DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT800DI16_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: PKDT800DI16_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: PKDT800DI16_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 TKDT800DI16.Search(const inBuff: TKDT800DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT800DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT800DI16_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: PKDT800DI16_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: PKDT800DI16_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 TKDT800DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT800DI16_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(TKDT800DI16_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 TKDT800DI16.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 <> KDT800DI16_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(TKDT800DI16_Vec)) <> SizeOf(TKDT800DI16_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 TKDT800DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT800DI16.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 TKDT800DI16.PrintNodeTree(const NodePtr: PKDT800DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT800DI16_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 TKDT800DI16.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 TKDT800DI16.Vec(const s: SystemString): TKDT800DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT800DI16_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 >= KDT800DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT800DI16.Vec(const v: TKDT800DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT800DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT800DI16.Distance(const v1, v2: TKDT800DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT800DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT800DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT800DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT800DI16.Test; var TKDT800DI16_Test: TKDT800DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT800DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT800DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT800DI16_Test := TKDT800DI16.Create; n.Append('...'); SetLength(TKDT800DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT800DI16_Test.TestBuff) - 1 do for j := 0 to KDT800DI16_Axis - 1 do TKDT800DI16_Test.TestBuff[i][j] := i * KDT800DI16_Axis + j; {$IFDEF FPC} TKDT800DI16_Test.BuildKDTreeM(length(TKDT800DI16_Test.TestBuff), nil, @TKDT800DI16_Test.Test_BuildM); {$ELSE FPC} TKDT800DI16_Test.BuildKDTreeM(length(TKDT800DI16_Test.TestBuff), nil, TKDT800DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT800DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT800DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT800DI16_Test.TestBuff) - 1 do begin p := TKDT800DI16_Test.Search(TKDT800DI16_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(TKDT800DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT800DI16_Test.TestBuff)); TKDT800DI16_Test.Search(TKDT800DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT800DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT800DI16_Test.Clear; { kMean test } TKDT800DI16_Test.BuildKDTreeWithCluster(TKDT800DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT800DI16_Test.Search(TKDT800DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT800DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT800DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT800DI16_Test); DoStatus(n); n := ''; end; function TKDT1024DI16.InternalBuildKdTree(const KDSourceBufferPtr: PKDT1024DI16_SourceBuffer; const PlanCount, Depth: NativeInt): PKDT1024DI16_Node; function SortCompare(const p1, p2: PKDT1024DI16_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: PKDT1024DI16_SourceBuffer; L, R: NativeInt; const axis: NativeInt); var i, j: NativeInt; p, t: PKDT1024DI16_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: PKDT1024DI16_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 KDT1024DI16_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 TKDT1024DI16.GetData(const Index: NativeInt): PKDT1024DI16_Source; begin Result := @KDStoreBuff[Index]; end; constructor TKDT1024DI16.Create; begin inherited Create; NodeCounter := 0; RootNode := nil; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); Clear; end; destructor TKDT1024DI16.Destroy; begin Clear; SetLength(KDNodes, 0); SetLength(KDStoreBuff, 0); SetLength(KDBuff, 0); inherited Destroy; end; procedure TKDT1024DI16.Clear; var i: NativeInt; begin i := 0; while i < length(KDNodes) do begin Dispose(PKDT1024DI16_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 TKDT1024DI16.StoreBuffPtr: PKDT1024DI16_DyanmicStoreBuffer; begin Result := @KDStoreBuff; end; procedure TKDT1024DI16.BuildKDTreeC(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1024DI16.BuildKDTreeM(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; procedure TKDT1024DI16.BuildKDTreeP(const PlanCount: NativeInt; const Data: Pointer; const OnTrigger: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, KDStoreBuff[i], Data); Inc(i); end; j := PlanCount; RootNode := InternalBuildKdTree(@KDBuff[0], j, 0); end; { k-means++ clusterization } procedure TKDT1024DI16.BuildKDTreeWithCluster(const inBuff: TKDT1024DI16_DynamicVecBuffer; const k, Restarts: NativeInt; var OutIndex: TKMIntegerArray); var Source: TKMFloat2DArray; KArray: TKMFloat2DArray; i, j: NativeInt; begin SetLength(Source, length(inBuff), KDT1024DI16_Axis); for i := 0 to length(inBuff) - 1 do for j := 0 to KDT1024DI16_Axis - 1 do Source[i, j] := inBuff[i, j]; if KMeansCluster(Source, KDT1024DI16_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 KDT1024DI16_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 TKDT1024DI16.BuildKDTreeWithCluster(const inBuff: TKDT1024DI16_DynamicVecBuffer; const k, Restarts: NativeInt); var OutIndex: TKMIntegerArray; begin BuildKDTreeWithCluster(inBuff, k, Restarts, OutIndex); SetLength(OutIndex, 0); end; procedure TKDT1024DI16.BuildKDTreeWithClusterC(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildCall); var TempStoreBuff: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI16_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 KDT1024DI16_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 TKDT1024DI16.BuildKDTreeWithClusterM(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildMethod); var TempStoreBuff: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI16_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 KDT1024DI16_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 TKDT1024DI16.BuildKDTreeWithClusterP(const PlanCount, k, Restarts: NativeInt; var OutIndex: TKMIntegerArray; const Data: Pointer; const OnTrigger: TKDT1024DI16_BuildProc); var TempStoreBuff: TKDT1024DI16_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(TKDT1024DI16_Vec), 0); OnTrigger(i, TempStoreBuff[i], Data); Inc(i); end; SetLength(Source, length(TempStoreBuff), KDT1024DI16_Axis); for i := 0 to length(TempStoreBuff) - 1 do for j := 0 to KDT1024DI16_Axis - 1 do Source[i, j] := TempStoreBuff[i].buff[j]; if KMeansCluster(Source, KDT1024DI16_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 KDT1024DI16_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 TKDT1024DI16.Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt; const NearestNodes: TCoreClassList): PKDT1024DI16_Node; var NearestNeighbour: PKDT1024DI16_Node; function FindParentNode(const buffPtr: PKDT1024DI16_Vec; NodePtr: PKDT1024DI16_Node): PKDT1024DI16_Node; var Next: PKDT1024DI16_Node; Depth, axis: NativeInt; begin Result := nil; Depth := 0; Next := NodePtr; while Next <> nil do begin Result := Next; axis := Depth mod KDT1024DI16_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: PKDT1024DI16_Node; const buffPtr: PKDT1024DI16_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 KDT1024DI16_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: PKDT1024DI16_Vec; const p1, p2: PKDT1024DI16_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: PKDT1024DI16_Vec); var i, j: NativeInt; p, t: PKDT1024DI16_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: PKDT1024DI16_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 := PKDT1024DI16_Node(NearestNodes[0]); end; end; function TKDT1024DI16.Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double; var SearchedCounter: NativeInt): PKDT1024DI16_Node; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter, nil); end; function TKDT1024DI16.Search(const buff: TKDT1024DI16_Vec; var SearchedDistanceMin: Double): PKDT1024DI16_Node; var SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1024DI16.Search(const buff: TKDT1024DI16_Vec): PKDT1024DI16_Node; var SearchedDistanceMin: Double; SearchedCounter: NativeInt; begin Result := Search(buff, SearchedDistanceMin, SearchedCounter); end; function TKDT1024DI16.SearchToken(const buff: TKDT1024DI16_Vec): TPascalString; var p: PKDT1024DI16_Node; begin p := Search(buff); if p <> nil then Result := p^.Vec^.Token else Result := ''; end; procedure TKDT1024DI16.Search(const inBuff: TKDT1024DI16_DynamicVecBuffer; var OutBuff: TKDT1024DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1024DI16_DynamicVecBuffer; outBuffPtr: PKDT1024DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1024DI16_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: PKDT1024DI16_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: PKDT1024DI16_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 TKDT1024DI16.Search(const inBuff: TKDT1024DI16_DynamicVecBuffer; var OutIndex: TKMIntegerArray); {$IFDEF parallel} var inBuffPtr: PKDT1024DI16_DynamicVecBuffer; outIndexPtr: PKMIntegerArray; {$IFDEF FPC} procedure FPC_ParallelFor(pass: Integer); var p: PKDT1024DI16_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: PKDT1024DI16_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: PKDT1024DI16_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 TKDT1024DI16.SaveToStream(stream: TCoreClassStream); var cnt: Int64; st, ID: Integer; i: NativeInt; token_B: TBytes; token_L: Integer; begin cnt := length(KDStoreBuff); st := SaveToken; ID := KDT1024DI16_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(TKDT1024DI16_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 TKDT1024DI16.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 <> KDT1024DI16_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(TKDT1024DI16_Vec)) <> SizeOf(TKDT1024DI16_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 TKDT1024DI16.SaveToFile(FileName: SystemString); var fs: TCoreClassFileStream; begin fs := TCoreClassFileStream.Create(FileName, fmCreate); try SaveToStream(fs); finally DisposeObject(fs); end; end; procedure TKDT1024DI16.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 TKDT1024DI16.PrintNodeTree(const NodePtr: PKDT1024DI16_Node); procedure DoPrintNode(prefix: SystemString; const p: PKDT1024DI16_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 TKDT1024DI16.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 TKDT1024DI16.Vec(const s: SystemString): TKDT1024DI16_Vec; var t: TTextParsing; SplitOutput: TArrayPascalString; i, j: NativeInt; begin for i := 0 to KDT1024DI16_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 >= KDT1024DI16_Axis then Break; end; end; DisposeObject(t); end; class function TKDT1024DI16.Vec(const v: TKDT1024DI16_Vec): SystemString; var i: NativeInt; begin Result := ''; for i := 0 to KDT1024DI16_Axis - 1 do begin if i > 0 then Result := Result + ','; Result := Result + umlIntToStr(v[i]); end; end; class function TKDT1024DI16.Distance(const v1, v2: TKDT1024DI16_Vec): Double; var i: NativeInt; begin Result := 0; for i := 0 to KDT1024DI16_Axis - 1 do Result := Result + (v2[i] - v1[i]) * (v2[i] - v1[i]); end; procedure TKDT1024DI16.Test_BuildM(const IndexFor: NativeInt; var Source: TKDT1024DI16_Source; const Data: Pointer); begin Source.buff := TestBuff[IndexFor]; Source.Token := umlIntToStr(IndexFor); end; class procedure TKDT1024DI16.Test; var TKDT1024DI16_Test: TKDT1024DI16; t: TTimeTick; i, j: NativeInt; TestResultBuff: TKDT1024DI16_DynamicVecBuffer; TestResultIndex: TKMIntegerArray; KMeanOutIndex: TKMIntegerArray; errored: Boolean; m64: TMemoryStream64; p: PKDT1024DI16_Node; n: TPascalString; begin errored := False; n := PFormat('test %s...', [ClassName]); t := GetTimeTick; n.Append('...build'); TKDT1024DI16_Test := TKDT1024DI16.Create; n.Append('...'); SetLength(TKDT1024DI16_Test.TestBuff, 1000); for i := 0 to length(TKDT1024DI16_Test.TestBuff) - 1 do for j := 0 to KDT1024DI16_Axis - 1 do TKDT1024DI16_Test.TestBuff[i][j] := i * KDT1024DI16_Axis + j; {$IFDEF FPC} TKDT1024DI16_Test.BuildKDTreeM(length(TKDT1024DI16_Test.TestBuff), nil, @TKDT1024DI16_Test.Test_BuildM); {$ELSE FPC} TKDT1024DI16_Test.BuildKDTreeM(length(TKDT1024DI16_Test.TestBuff), nil, TKDT1024DI16_Test.Test_BuildM); {$ENDIF FPC} { save/load test } n.Append('...save/load'); m64 := TMemoryStream64.CustomCreate(1024 * 1024); TKDT1024DI16_Test.SaveToStream(m64); m64.Position := 0; TKDT1024DI16_Test.LoadFromStream(m64); for i := 0 to length(TKDT1024DI16_Test.TestBuff) - 1 do begin p := TKDT1024DI16_Test.Search(TKDT1024DI16_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(TKDT1024DI16_Test.TestBuff)); SetLength(TestResultIndex, length(TKDT1024DI16_Test.TestBuff)); TKDT1024DI16_Test.Search(TKDT1024DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if Distance(TKDT1024DI16_Test.TestBuff[TestResultIndex[i]], TestResultBuff[TestResultIndex[i]]) <> 0 then errored := True; end; if not errored then begin n.Append('...kMean'); TKDT1024DI16_Test.Clear; { kMean test } TKDT1024DI16_Test.BuildKDTreeWithCluster(TKDT1024DI16_Test.TestBuff, 10, 1, KMeanOutIndex); { parallel search test } TKDT1024DI16_Test.Search(TKDT1024DI16_Test.TestBuff, TestResultBuff, TestResultIndex); for i := 0 to length(TestResultIndex) - 1 do if TestResultIndex[i] <> KMeanOutIndex[i] then errored := True; end; SetLength(TKDT1024DI16_Test.TestBuff, 0); SetLength(TestResultBuff, 0); SetLength(TestResultIndex, 0); SetLength(KMeanOutIndex, 0); TKDT1024DI16_Test.Clear; n.Append('...'); if errored then n.Append('error!') else n.Append('passed ok %dms', [GetTimeTick - t]); DisposeObject(TKDT1024DI16_Test); DoStatus(n); n := ''; end; procedure Test_All; begin TKDT1DI16.Test(); TKDT2DI16.Test(); TKDT3DI16.Test(); TKDT4DI16.Test(); TKDT5DI16.Test(); TKDT6DI16.Test(); TKDT7DI16.Test(); TKDT8DI16.Test(); TKDT9DI16.Test(); TKDT10DI16.Test(); TKDT11DI16.Test(); TKDT12DI16.Test(); TKDT13DI16.Test(); TKDT14DI16.Test(); TKDT15DI16.Test(); TKDT16DI16.Test(); TKDT17DI16.Test(); TKDT18DI16.Test(); TKDT19DI16.Test(); TKDT20DI16.Test(); TKDT21DI16.Test(); TKDT22DI16.Test(); TKDT23DI16.Test(); TKDT24DI16.Test(); TKDT48DI16.Test(); TKDT52DI16.Test(); TKDT64DI16.Test(); TKDT96DI16.Test(); TKDT128DI16.Test(); TKDT156DI16.Test(); TKDT192DI16.Test(); TKDT256DI16.Test(); TKDT384DI16.Test(); TKDT512DI16.Test(); TKDT800DI16.Test(); TKDT1024DI16.Test(); end; initialization finalization end.
procedure readToken(expected : tokentype); begin getToken(); if (nextToken.name <> expected) then {todo: convert 'identifiers' into proper keywords} if (nextToken.name <> identifier) then writeln('Unexpected token ', nextToken.text); writeln(nextToken.text); end; procedure identifierList(); begin {todo: read more than one id} readToken(identifier); end; procedure programHeading(); begin readToken(symprogram); readToken(identifier); {todo: peek and see if there is not an identifier list} readToken(parenleft); identifierList(); readToken(parenright); end; procedure procedureStatement(); begin {todo: handle more than just writeln} readToken(identifier); readToken(parenleft); {identifierList();} readToken(characterstring); readToken(parenright); end; procedure statement(); begin {todo: expand to more than just procedure statement} procedureStatement(); end; procedure statementSequence(); begin statement(); {todo: read semicolon and then more statements} end; procedure compoundStatement(); begin readToken(symbegin); statementSequence(); readToken(symend); end; procedure block(); begin {todo: label, const, type, variable, procedure declarations} compoundStatement(); end; procedure programStart(); begin programHeading(); readToken(semicolon); block(); readToken(period); end;
///////////////////////////////////////////////////////// // // // FlexGraphics library // // Copyright (c) 2002-2009, FlexGraphics software. // // // // Alpha blending buffer support // // // ///////////////////////////////////////////////////////// unit FlexAlpha; {$I FlexDefs.inc} interface uses Windows, Classes, Graphics; type PAlphaLine = ^TAlphaLine; TAlphaLine = array[0..MaxInt div SizeOf(TRGBQuad)-1] of TRGBQuad; TStoreDrawEvent = procedure(Sender: TObject; Canvas: TCanvas; Graphic: TGraphic) of object; TAlphaBuffer = class private FParent: TAlphaBuffer; FSourceDC: HDC; FCanvas: TCanvas; FCanvasDC: HDC; FCanvasDCBitmap: HBitmap; FPaintRect: TRect; FPaintWidth: integer; FPaintHeight: integer; FWidth: integer; FHeight: integer; FBits: PAlphaLine; FBytesPerLine: integer; FInfo: TBitmapInfo; FHandle: HBitmap; FStored: boolean; protected procedure ResetCanvas(DeleteDIB: boolean = false); procedure RecreateDIB(AWidth, AHeight: integer; ForceRecreate: boolean = false; FillColor: cardinal = $FF000000); public constructor Create(AParent: TAlphaBuffer = Nil); destructor Destroy; override; function BeginPaint(ASourceDC: HDC; const APaintRect: TRect): boolean; virtual; function EndPaint(Transparency: integer): boolean; virtual; function StoreFromGraphic(Graphic: TGraphic; OnDraw: TStoreDrawEvent = Nil): boolean; function PaintStored(Dest: TAlphaBuffer; const APaintRect, ASrcRect: TRect): boolean; property Canvas: TCanvas read FCanvas; property SourceDC: HDC read FSourceDC; property Handle: HBitmap read FHandle; property Width: integer read FWidth; property Height: integer read FHeight; end; implementation // TFlexAlphaBuffer /////////////////////////////////////////////////////////// constructor TAlphaBuffer.Create(AParent: TAlphaBuffer = Nil); begin FParent := AParent; FCanvas := TCanvas.Create; end; destructor TAlphaBuffer.Destroy; begin inherited; ResetCanvas(true); FCanvas.Free; end; procedure TAlphaBuffer.ResetCanvas(DeleteDIB: boolean = false); begin if FCanvasDC <> 0 then begin // Reset canvas DC FCanvas.Handle := 0; // Select old canvas bitmap SelectObject(FCanvasDC, FCanvasDCBitmap); FCanvasDCBitmap := 0; // Delete Canvas DC DeleteDC(FCanvasDC); FCanvasDC := 0; end; // Delete DIB-section if DeleteDIB then begin if FHandle <> 0 then begin DeleteObject(FHandle); FHandle := 0; end; FWidth := 0; FHeight := 0; end; FStored := false; end; procedure TAlphaBuffer.RecreateDIB(AWidth, AHeight: integer; ForceRecreate: boolean = false; FillColor: cardinal = $FF000000); var BitLine: PAlphaLine; x, y: integer; begin if ForceRecreate or (AWidth > FWidth) or (AHeight > FHeight) then begin // Source rect larger then existing. Enlarge DIB-section ResetCanvas(true); FWidth := AWidth; FHeight := AHeight; FillChar(FInfo, sizeof(FInfo), 0); with FInfo.bmiHeader do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := FWidth; biHeight := -FHeight; biPlanes := 1; biBitCount := 32; biCompression := BI_RGB; // Calc bytes per line FBytesPerLine := (((biBitCount * biWidth) + 31) and not 31) div 8; end; end; if FCanvasDC = 0 then begin // Create paint DC (for alpha blend) FCanvasDC := CreateCompatibleDC(0); // Recreate DIB section if (FHandle = 0) and (FWidth > 0) and (FHeight > 0) then begin FHandle := CreateDIBSection(FCanvasDC, FInfo, DIB_RGB_COLORS, pointer(FBits), 0, 0); if FHandle = 0 then begin // Error in DIB-section create ResetCanvas(true); exit; end; end; // Select DIB-section in FCanvasDC if FHandle <> 0 then FCanvasDCBitmap := SelectObject(FCanvasDC, FHandle); end; // set canvas bitmap completely transparent BitLine := FBits; for y:=0 to FHeight-1 do begin for x:=0 to FWidth-1 do cardinal(BitLine[x]) := FillColor; inc(integer(BitLine), FBytesPerLine); end; end; function TAlphaBuffer.BeginPaint(ASourceDC: HDC; const APaintRect: TRect): boolean; begin Result := false; if (FSourceDC <> 0) or (ASourceDC = 0) then exit; with APaintRect do begin FPaintWidth := Right - Left; FPaintHeight := Bottom - Top; end; if (FPaintWidth <= 0) or (FPaintHeight <= 0) then exit; FPaintRect := APaintRect; // Check recreate DIB RecreateDIB(FPaintWidth, FPaintHeight); FSourceDC := ASourceDC; // Select FCanvasDC in FCanvas FCanvas.Handle := FCanvasDC; Result := true; end; function TAlphaBuffer.EndPaint(Transparency: integer): boolean; var AlphaDC: HDC; AlphaDCBitmap: HBitmap; AlphaBitmap: HBitmap; AlphaBits: PAlphaLine; SrcLine: PAlphaLine; SrcPixel: PRGBQuad; SrcLineInc: integer; DestLine: PAlphaLine; DestLineInc: integer; SrcAlpha: integer; DstAlpha: integer; Tmp, A, C: integer; x, y: integer; begin Result := false; AlphaDC := 0; AlphaDCBitmap := 0; AlphaBitmap := 0; try if (FSourceDC = 0) or (FCanvasDC = 0) or (FHandle = 0) or (Transparency < 0) then exit; if Transparency >= 100 then begin // Image completely transparent. Not necessary to paint something Result := true; exit; end; if Assigned(FParent) and (FSourceDC = FParent.FCanvasDC) and EqualRect(FPaintRect, FParent.FPaintRect) then begin // Is child alpha buffer. No need to create temp alpha bitmap DestLine := FParent.FBits; DestLineInc := FParent.FBytesPerLine; end else begin // Create alpha DC AlphaDC := CreateCompatibleDC(0); if AlphaDC = 0 then exit; // Create alpha bitmap AlphaBitmap := CreateDIBSection(AlphaDC, FInfo, DIB_RGB_COLORS, pointer(AlphaBits), 0, 0); // Select alpha bitmap in alpha DC AlphaDCBitmap := SelectObject(AlphaDC, AlphaBitmap); // Copy current image from SourceDC to AlphaDC StretchBlt(AlphaDC, 0, 0, FPaintWidth, FPaintHeight, FSourceDC, FPaintRect.Left, FPaintRect.Top, FPaintWidth, FPaintHeight, SRCCOPY); // Set destination start DestLine := AlphaBits; DestLineInc := FBytesPerLine; end; // Alpha blend. Mix AlphaDC with FCanvasDC SrcLine := FBits; SrcLineInc := FBytesPerLine; for y:=0 to FPaintHeight-1 do begin for x:=0 to FPaintWidth-1 do with DestLine[x] do begin SrcPixel := @SrcLine[x]; SrcAlpha := 255 - SrcPixel.rgbReserved; if SrcAlpha = 0 then continue; if Transparency > 0 then SrcAlpha := (100 - Transparency) * SrcAlpha div 100; DstAlpha := 255 - rgbReserved; if (SrcAlpha = 255) and (DstAlpha = 0) then DestLine[x] := SrcLine[x] else begin Tmp := (255 - SrcAlpha) * (255 - DstAlpha) + $80; A := 255 - ((Tmp + (Tmp shr 8)) shr 8); C := ((SrcAlpha shl 16) + (A shr 1)) div A; rgbRed := rgbRed + (((SrcPixel.rgbRed - rgbRed) * C + $8000) shr 16); rgbGreen := rgbGreen + (((SrcPixel.rgbGreen - rgbGreen) * C + $8000) shr 16); rgbBlue := rgbBlue + (((SrcPixel.rgbBlue - rgbBlue) * C + $8000) shr 16); rgbReserved := 255 - A; end; end; inc(integer(SrcLine), SrcLineInc); inc(integer(DestLine), DestLineInc); end; if AlphaDC <> 0 then // Draws alpha bitmap on the foreground BitBlt(FSourceDC, FPaintRect.Left, FPaintRect.Top, FPaintWidth, FPaintHeight, AlphaDC, 0, 0, SRCCOPY); // Alpha blend complete Result := true; finally // Delete alpha buffer if AlphaDC <> 0 then begin SelectObject(AlphaDC, AlphaDCBitmap); DeleteDC(AlphaDC); if AlphaBitmap <> 0 then DeleteObject(AlphaBitmap); end; // End paint FSourceDC := 0; ResetCanvas; end; end; function TAlphaBuffer.StoreFromGraphic(Graphic: TGraphic; OnDraw: TStoreDrawEvent = Nil): boolean; begin Result := false; if (FSourceDC <> 0) then exit; if not Assigned(Graphic) then begin ResetCanvas(true); Result := true; exit; end; // Create DIB RecreateDIB(Graphic.Width, Graphic.Height, true); // Select FCanvasDC in FCanvas FCanvas.Handle := FCanvasDC; // Copy graphic to DIB if Assigned(OnDraw) then OnDraw(Self, FCanvas, Graphic) else FCanvas.Draw(0, 0, Graphic); // All done FStored := true; Result := true; end; function TAlphaBuffer.PaintStored(Dest: TAlphaBuffer; const APaintRect, ASrcRect: TRect): boolean; var DestRect: TRect; Size, PaintSize, SrcSize: TPoint; XPoints: array of integer; x, y, YLine: integer; SrcLine, DestLine: PAlphaLine; XCoeff, YCoeff: double; begin Result := false; if not FStored or (FWidth <= 0) or (FHeight <= 0) or (ASrcRect.Left < 0) or (ASrcRect.Top < 0) or (ASrcRect.Right > FWidth) or (ASrcRect.Bottom > FHeight) then exit; if not IntersectRect(DestRect, Rect(0, 0, Dest.Width, Dest.Height), APaintRect) then begin // Picture is completely invisible Result := true; exit; end; // Calculate size with Size, DestRect do begin X := Right - Left; Y := Bottom - Top; end; with PaintSize, APaintRect do begin X := Right - Left; Y := Bottom - Top; end; with SrcSize, ASrcRect do begin X := Right - Left; Y := Bottom - Top; end; // Calculate x points XCoeff := SrcSize.X / PaintSize.X; SetLength(XPoints, Size.X); for x:=0 to Size.X-1 do begin XPoints[x] := ASrcRect.Left + Trunc((x + (DestRect.Left - APaintRect.Left)) * XCoeff); if XPoints[x] < 0 then XPoints[x] := 0 else if XPoints[x] >= FWidth then XPoints[x] := FWidth; end; // Cycle for every visible scanline YCoeff := SrcSize.Y / PaintSize.Y; DestLine := PAlphaLine(PAnsiChar(Dest.FBits) + DestRect.Top * Dest.FBytesPerLine); for y:=DestRect.Top to DestRect.Bottom-1 do begin YLine := ASrcRect.Top + Trunc((y - APaintRect.Top) * YCoeff); if YLine >= FHeight then YLine := FHeight-1 else if YLine < 0 then YLine := 0; Srcline := PAlphaLine(PAnsiChar(FBits) + YLine * FBytesPerLine); for x:=0 to Size.X-1 do DestLine[x + DestRect.Left] := SrcLine[XPoints[x]]; inc(PAnsiChar(DestLine), Dest.FBytesPerLine); end; // All ok Result := true; end; end.
unit CSCMsgProcessor; {$B-} {Complete Boolean Evaluation} {$I+} {Input/Output-Checking} {$P+} {Open Parameters} {$T-} {Typed @ Operator} {$W-} {Windows Stack Frame} {$X+} {Extended Syntax} interface uses Windows, Classes, Forms, Messages, CSCBase, CSCQueue, CSCCustomBase, SysUtils; type TCSCOnMsgRec = procedure (Sender: TObject; Msg: TCSCMessage) of object; TCSCMsgProcessor = class(TComponent) protected FCCBase : TCSCCustomCommBase; FHandle : hWnd; {our window handle} FOnMsgRec : TCSCOnMsgRec; procedure MsgWndProc(var Msg : TMessage); procedure SetCCBase(Value: TCSCCustomCommBase); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property CustomCommBase: TCSCCustomCommBase read FCCBase write SetCCBase; property OnMsgRec : TCSCOnMsgRec read FOnMsgRec write FOnMsgRec; end; implementation constructor TCSCMsgProcessor.Create(AOwner: TComponent); begin inherited Create(AOwner); FCCBase := nil; FOnMsgRec := nil; FHandle := AllocateHWnd(MsgWndProc); end; destructor TCSCMsgProcessor.Destroy; begin DeallocateHWnd(FHandle); inherited Destroy; end; procedure TCSCMsgProcessor.MsgWndProc(var Msg : TMessage); var DataMsg : PCSCMessage; begin with Msg do if Msg <> cscm_EventReceived then DefWindowProc(FHandle, Msg, wParam, lParam) else while true do begin if (FCCBase=nil) then Exit; DataMsg := FCCBase.MsgQueue.ExamineEvents; if (DataMsg = nil) then Exit; FCCBase.MsgQueue.RemoveEventFromQueue(DataMsg); try if Assigned(FOnMsgRec) then FOnMsgRec(Self, DataMsg^); finally FCCBase.MsgQueue.DisposeEvent(DataMsg); end; end; end; procedure TCSCMsgProcessor.SetCCBase(Value: TCSCCustomCommBase); begin if Value = FCCBase then Exit; if FCCBase <> nil then try FCCBase.NotifyHandle := 0; except end; FCCBase := Value; if FCCBase <> nil then try FCCBase.NotifyHandle := FHandle; except end; end; end.
{* ------------------------------------------------------------------------ * * Command Parttern ♥ TCommand * ------------------------------------------------------------------------ *} unit Pattern.Command; interface uses System.Classes, System.SysUtils, System.TypInfo, System.Diagnostics, System.TimeSpan; type ICommand = interface procedure Execute(); end; TCommand = class(TComponent, ICommand) private const Version = '1.0'; protected fStopwatch: TStopwatch; fBusy: boolean; procedure DoGuard; virtual; procedure DoExecute; virtual; abstract; public class procedure AdhocExecute<T: TCommand>(const Injections : array of const); static; function WithInjections(const Injections: array of const): TCommand; procedure Execute; virtual; function GetElapsedTime: TTimeSpan; function GetElapsedTimeMs: integer; function IsBusy: boolean; virtual; end; TPropertyInfo = record Kind: TTypeKind; PropertyName: string; ClassName: string; function isAvaliableForInjection(const aInjection: TVarRec): boolean; end; TPropertyArray = array of TPropertyInfo; TComponentMetadata = class public class function GetPublishedPropetries(aComponent: TComponent) : TPropertyArray; end; TComponentInjector = class class procedure InjectProperties(aComponent: TComponent; const Injections: array of const); private class procedure AssertParameters(const Injections: array of const); static; end; type TCommandClass = class of TCommand; implementation uses System.RTTI; // ------------------------------------------------------------------------ // TCommand // ------------------------------------------------------------------------ const ERRMSG_NotSupportedParameter = 'Not supported parameter type to inject!' + 'Parameter index (zaro-based): %d. Paramter type: %s'; procedure TCommand.Execute; begin DoGuard; fStopwatch := TStopwatch.StartNew; fBusy := True; try DoExecute; finally fBusy := False; fStopwatch.Stop; end; end; function TCommand.GetElapsedTime: TTimeSpan; begin Result := fStopwatch.Elapsed; end; function TCommand.GetElapsedTimeMs: integer; begin Result := fStopwatch.ElapsedMilliseconds; end; function TCommand.IsBusy: boolean; begin Result := fBusy; end; procedure TCommand.DoGuard; begin end; function TCommand.WithInjections(const Injections: array of const): TCommand; begin TComponentInjector.InjectProperties(Self, Injections); Result := Self; end; class procedure TCommand.AdhocExecute<T>(const Injections: array of const); var AClass: TCommandClass; Command: T; begin try // ----------------------------------------- AClass := T; Command := T(AClass.Create(nil)); // 10.3 Rio: Command := T.Create(nil); // ----------------------------------------- TComponentInjector.InjectProperties(Command, Injections); Command.Execute; finally Command.Free; end; end; // ------------------------------------------------------------------------ // TComponentInjector // ------------------------------------------------------------------------ { TPropertyInfo } procedure SetInterfaceProperty(aComponent: TComponent; const aPropertyName: string; const aInjection: TVarRec); var ctx: TRttiContext; typ: TRttiType; prop: TRttiProperty; val: TValue; begin typ := ctx.GetType(aComponent.ClassType); val := TValue.From(IInterface(aInjection.VInterface) as TObject); for prop in typ.GetProperties do if prop.Name = aPropertyName then prop.SetValue(aComponent, val); end; function IsInterfaceInjectionImplementsInterface(const aInjection: TVarRec; const aInterfaceName: string): boolean; var obj: TObject; implementedList: TArray<TRttiInterfaceType>; IntfType: TRttiInterfaceType; ctx: TRttiContext; begin System.Assert(aInjection.VType = vtInterface); obj := IInterface(aInjection.VInterface) as TObject; implementedList := (ctx.GetType(obj.ClassType) as TRttiInstanceType) .GetImplementedInterfaces; for IntfType in implementedList do if IntfType.Name = aInterfaceName then Exit(true); Result := False; end; function TPropertyInfo.isAvaliableForInjection(const aInjection : TVarRec): boolean; var ClassType: TClass; begin if (Self.Kind = tkInterface) and (aInjection.VType = vtInterface) then Result := IsInterfaceInjectionImplementsInterface(aInjection, Self.ClassName) else if (Self.Kind = tkClass) and (aInjection.VType = vtObject) then begin Result := (aInjection.VObject.ClassName = Self.ClassName); ClassType := aInjection.VObject.ClassType; while not(Result) and (ClassType.ClassParent <> nil) do begin Result := (ClassType.ClassParent.ClassName = Self.ClassName); ClassType := ClassType.ClassParent; end; end else Result := (Self.Kind = tkInteger) and (aInjection.VType = vtInteger) or (Self.Kind = tkEnumeration) and (aInjection.VType = vtBoolean) or (Self.Kind = tkFloat) and (aInjection.VType = vtExtended); end; function TypeKindToStr(value: TTypeKind): string; begin Result := System.TypInfo.GetEnumName(TypeInfo(TTypeKind), Integer(value)); end; function VTypeToStr(value: byte): string; begin case value of {$REGION 'case VType values 0 .. 17, vtInteger = 0, vtBoolean = 1, ...'} 0: Result := 'vtInteger'; 1: Result := 'vtBoolean'; 2: Result := 'vtChar'; 3: Result := 'vtExtended'; 4: Result := 'vtString'; 5: Result := 'vtPointer'; 6: Result := 'vtPChar'; 7: Result := 'vtObject'; 8: Result := 'vtClass'; 9: Result := 'vtWideChar'; 10: Result := 'vtPWideChar'; 11: Result := 'vtAnsiString'; 12: Result := 'vtCurrency'; 13: Result := 'vtVariant'; 14: Result := 'vtInterface'; 15: Result := 'vtWideString'; 16: Result := 'vtInt64'; 17: Result := 'vtUnicodeString'; {$ENDREGION} end; end; class procedure TComponentInjector.AssertParameters(const Injections : array of const); var j: Integer; begin for j := 0 to High(Injections) do if not(Injections[j].VType in [vtObject, vtInterface, vtInteger, vtBoolean, vtExtended]) then Assert(False, Format(ERRMSG_NotSupportedParameter, [j, VTypeToStr(Injections[j].VType)])); end; // - - - - - - - - - - - - - - - - - - - - - - - - - // TPropertyInfo.Kind: tkInteger, tkChar, tkEnumeration, tkFloat, tkString, // tkSet, tkWChar, tkLString, tkWString, tkVariant, tkArray, tkRecord, // tkInterface, tkInt64, tkDynArray, tkUString // - - - - - - - - - - - - - - - - - - - - - - - - - class procedure TComponentInjector.InjectProperties(aComponent: TComponent; const Injections: array of const); var i: Integer; j: Integer; PropertyList: TPropertyArray; propInfo: TPropertyInfo; UsedInjection: TArray<boolean>; begin AssertParameters(Injections); PropertyList := TComponentMetadata.GetPublishedPropetries(aComponent); SetLength(UsedInjection, Length(Injections)); for i := 0 to High(PropertyList) do begin propInfo := PropertyList[i]; for j := 0 to High(Injections) do begin if not(UsedInjection[j]) and propInfo.isAvaliableForInjection (Injections[j]) then begin UsedInjection[j] := true; case propInfo.Kind of tkInterface: SetInterfaceProperty(aComponent, propInfo.PropertyName, Injections[j]); tkClass: SetObjectProp(aComponent, propInfo.PropertyName, Injections[j].VObject); tkInteger, tkEnumeration: SetOrdProp(aComponent, propInfo.PropertyName, Injections[j].VInteger); tkFloat: SetFloatProp(aComponent, propInfo.PropertyName, Injections[j].VExtended^); end; Break; end; end end; end; // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ { TClassPropertyList } class function TComponentMetadata.GetPublishedPropetries(aComponent: TComponent) : TPropertyArray; var aStandardComponent: TComponent; FPropList: PPropList; FStandardPropList: PPropList; aStandardCount: Integer; aCount: Integer; i: Integer; begin aCount := System.TypInfo.GetPropList(aComponent, FPropList); aStandardComponent := TComponent.Create(nil); aStandardCount := System.TypInfo.GetPropList(aStandardComponent, FStandardPropList); try SetLength(Result, aCount - aStandardCount); for i := 0 to aCount - aStandardCount - 1 do begin Result[i].Kind := FPropList^[aStandardCount + i].PropType^.Kind; Result[i].PropertyName := string(FPropList^[aStandardCount + i].Name); Result[i].ClassName := string(FPropList^[aStandardCount + i].PropType^.Name); end; finally FreeMem(FPropList); aStandardComponent.Free; FreeMem(FStandardPropList); end; end; end.
unit amSplitter; // ----------------------------------------------------------------------------- // TSplitter enhanced with grab bar // The original author is Anders Melander, anders@melander.dk, http://melander.dk // Copyright © 2008 Anders Melander // ----------------------------------------------------------------------------- // License: // Creative Commons Attribution-Share Alike 3.0 Unported // http://creativecommons.org/licenses/by-sa/3.0/ // ----------------------------------------------------------------------------- interface uses ExtCtrls; //------------------------------------------------------------------------------ // // TSplitter enhanced with grab bar // //------------------------------------------------------------------------------ type TSplitter = class(ExtCtrls.TSplitter) protected procedure Paint; override; end; implementation uses Windows, Graphics, Controls, Classes; //------------------------------------------------------------------------------ // // TSplitter enhanced with grab bar // //------------------------------------------------------------------------------ procedure TSplitter.Paint; var R: TRect; X, Y: integer; DX, DY: integer; i: integer; Brush: TBitmap; begin R := ClientRect; Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); X := (R.Left+R.Right) div 2; Y := (R.Top+R.Bottom) div 2; if (Align in [alLeft, alRight]) then begin DX := 0; DY := 3; end else begin DX := 3; DY := 0; end; dec(X, DX*2); dec(Y, DY*2); Brush := TBitmap.Create; try Brush.SetSize(2, 2); Brush.Canvas.Brush.Color := clBtnHighlight; Brush.Canvas.FillRect(Rect(0,0,1,1)); Brush.Canvas.Pixels[0, 0] := clBtnShadow; for i := 0 to 4 do begin Canvas.Draw(X, Y, Brush); inc(X, DX); inc(Y, DY); end; finally Brush.Free; end; end; end.
unit uTokenizer; interface type TTokenizer = class(TObject) private FSource, FDelimeter: string; FPos: Integer; public { ASource is your source text ADelimeter is a string of one or more chars treated as individual delimeters e.g. TTokenizer.Create('This, is a test', ', ') would tokenize into 'This' 'is' 'a' and 'test' } constructor Create(const ASource, ADelimeter: string); virtual; function HasMoreTokens: Boolean; function NextToken: string; function PeekToken: string; procedure Reset; procedure SkipToken; end; implementation { TTokenizer } constructor TTokenizer.Create(const ASource, ADelimeter: string); begin FSource := ASource; FDelimeter := ADelimeter; FPos := 1; end; function TTokenizer.HasMoreTokens: Boolean; begin Result := FPos <= Length(FSource); end; function TTokenizer.NextToken: string; var I, EndP: Integer; begin EndP := 0; Result := ''; for I := FPos to Length(FSource) do begin if Pos(FSource[I], FDelimeter) > 0 then begin EndP := I; Break; end; EndP := I + 1; end; if EndP > 0 then begin Result := Copy(FSource, FPos, EndP - FPos); FPos := EndP + 1; while (FPos < Length(FSource)) and (Pos(FSource[FPos], FDelimeter) > 0) do Inc(FPos); end; end; function TTokenizer.PeekToken: string; var I, EndP: Integer; begin EndP := 0; Result := ''; for I := FPos to Length(FSource) do begin if Pos(FSource[I], FDelimeter) > 0 then begin EndP := I; Break; end; EndP := I + 1; end; if EndP > 0 then Result := Copy(FSource, FPos, EndP - FPos); end; procedure TTokenizer.Reset; begin FPos := 1; end; procedure TTokenizer.SkipToken; begin NextToken; end; end.
unit EmployerSearch; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseSearch, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, RzDBGrid, Vcl.Mask, RzEdit, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, RzButton; type TfrmEmployerSearch = class(TfrmBaseSearch) procedure FormCreate(Sender: TObject); private { Private declarations } protected procedure SearchList; override; procedure SetReturn; override; procedure Add; override; procedure Cancel; override; end; var frmEmployerSearch: TfrmEmployerSearch; implementation {$R *.dfm} uses EntitiesData, Employer, Group; procedure TfrmEmployerSearch.FormCreate(Sender: TObject); begin dmEntities := TdmEntities.Create(self); inherited; end; procedure TfrmEmployerSearch.SearchList; var filter: string; begin inherited; if Trim(edSearchKey.Text) <> '' then filter := 'name like ''*' + edSearchKey.Text + '*''' else filter := ''; grSearch.DataSource.DataSet.Filter := filter; end; procedure TfrmEmployerSearch.SetReturn; var gp: TGroup; begin with dmEntities.dstEmployers do begin gp := TGroup.Create; gp.GroupId := FieldByName('grp_id').AsString; gp.GroupName := FieldByName('grp_name').AsString; emp.Id := FieldByName('emp_id').AsString; emp.Name := FieldByName('emp_name').AsString; emp.Address := FieldByName('emp_add').AsString; emp.Group := gp; end; end; procedure TfrmEmployerSearch.Add; begin // no need to implement.. this is implemented in a different window end; procedure TfrmEmployerSearch.Cancel; begin emp.Destroy; end; end.
unit FC.StockChart.UnitTask.MBB.CalculateProfit; {$I Compiler.inc} interface uses SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses FC.StockChart.UnitTask.MBB.CalculateProfitDialog; type TStockUnitTaskMBBCalculateProfit = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskMBBCalculateProfit } function TStockUnitTaskMBBCalculateProfit.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorMBB); if result then aOperationName:='MBB: Calculate Profit'; end; procedure TStockUnitTaskMBBCalculateProfit.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); begin TfmMBBCalculateProfitDialog.Run(aIndicator as ISCIndicatorMBB); end; initialization StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskMBBCalculateProfit.Create); end.
{------------------------- MiniCRT Unit -------------------------} {$A-,B-,E-,F-,G+,I-,N-,O-,P-,Q-,R-,S-,T-,V-,X-} unit minicrt; interface procedure MINICRT_INIT; procedure CRT_CHAR(x,y:integer; cha:char; color:byte); procedure CRT_LINEX(x,y,x1:integer; cha:char; color:byte); procedure CRT_LINEY(x,y,y1:integer; cha:char; color:byte); procedure CRT_SHADEX(x,y,x1:integer); procedure CRT_SHADEY(x,y,y1:integer); procedure CRT_PRINT(x,y:integer; txt:pointer; color:byte); procedure CRT_PCOPY(upto,from:word); function CRT_READKEY : integer; procedure CRT_ECHO(txt:pointer); procedure CRT_BOXFILL(x,y,x1,y1,color:integer); implementation {$L minicrt.obj} {$F+} procedure MINICRT_INIT; external; procedure CRT_CHAR(x,y:integer; cha:char; color:byte); external; procedure CRT_LINEX(x,y,x1:integer; cha:char; color:byte); external; procedure CRT_LINEY(x,y,y1:integer; cha:char; color:byte); external; procedure CRT_SHADEX(x,y,x1:integer); external; procedure CRT_SHADEY(x,y,y1:integer); external; procedure CRT_PRINT(x,y:integer; txt:pointer; color:byte); external; procedure CRT_PCOPY(upto,from:word); external; function CRT_READKEY : integer; external; procedure CRT_ECHO(txt:pointer); external; procedure CRT_BOXFILL(x,y,x1,y1,color:integer); external; begin minicrt_init; end.
unit taxcalform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { TForm1 } TForm1 = class(TForm) btn1: TButton; edValue: TEdit; edVat: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; ledGross: TLabeledEdit; ledGrossFromVat: TLabeledEdit; ledNet: TLabeledEdit; ledNetFromVat: TLabeledEdit; ledVat: TLabeledEdit; ledVatFromGross: TLabeledEdit; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; pnlgross: TPanel; pnlgrossfromvat: TPanel; pnlnet: TPanel; pnlnetfromvat: TPanel; pnlvalue: TPanel; pnlvatamount: TPanel; pnlvatfromgross: TPanel; procedure btn1Click(Sender: TObject); procedure edValueChange(Sender: TObject); procedure FormShow(Sender: TObject); private fVatRate: double; { private declarations } public property VatRate : double read fVatRate; constructor Create (const vatValue : double); function Vat(const netValue : double) : double; function Gross(const netValue : double) : double; function Net(const grossValue : double) : double; function VatFromGross(const grossValue : double) : double; function NetFromVat(const vatValue : double) : double; function GrossFromVat(const vatValue : double) : double; { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.btn1Click(Sender: TObject); var vc : Tform1; valueIn : double; begin valueIn := StrToFloat(edValue.Text) ; vc := Tform1.Create(StrToFloat(edVat.Text)); try ledVat.Text := FormatFloat('.00',vc.Vat(valueIn)); ledGross.Text := FormatFloat('.00',vc.Gross(valueIn)); ledNet.Text := FormatFloat('.00',vc.Net(valueIn)); ledVatFromGross.Text := FormatFloat('.00',vc.VatFromGross(valueIn)); ledNetFromVat.Text := FormatFloat('.00',vc.NetFromVat(valueIn)); ledGrossFromVat.Text := FormatFloat('.00',vc.GrossFromVat(valueIn)); finally vc.Free; end; end; procedure TForm1.edValueChange(Sender: TObject); begin if (edVat.Text <> '') and (edValue.Text <> '') then begin btn1.Click; end; end; procedure TForm1.FormShow(Sender: TObject); begin edValue.SetFocus; end; constructor TForm1.Create(const vatValue: double); begin fVatRate := vatValue; end; function TForm1.Vat(const netValue: double): double; begin result := VatRate * netValue / 100 ; end; function TForm1.Gross(const netValue: double): double; begin result := netValue + Vat(netValue); end; function TForm1.Net(const grossValue: double): double; begin result := 100 / (100 + VatRate) * grossValue; end; function TForm1.VatFromGross(const grossValue: double): double; begin result := grossValue - Net(grossValue); end; function TForm1.NetFromVat(const vatValue: double): double; begin result := vatValue * 100 / VatRate; end; function TForm1.GrossFromVat(const vatValue: double): double; begin result := vatValue + NetFromVat(vatValue); end; end.
unit BillContentView2; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ProductsBaseView0, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxMaskEdit, cxDBLookupComboBox, cxDropDownEdit, cxButtonEdit, cxTLdxBarBuiltInMenu, dxSkinsCore, dxSkinsDefaultPainters, cxCalendar, cxCurrencyEdit, Vcl.ExtCtrls, Vcl.Menus, System.Actions, Vcl.ActnList, dxBar, cxBarEditItem, cxClasses, Vcl.ComCtrls, cxInplaceContainer, cxDBTL, cxTLData, BillContentQry, ProductsBaseQuery0, BillContentViewModel; type TViewBillContent2 = class(TViewProductsBase0) procedure cxDBTreeListEditing(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn; var Allow: Boolean); private procedure DoAfterLoad(Sender: TObject); function GetBillContentModel: TBillContentViewModel; procedure SetBillContentModel(const Value: TBillContentViewModel); { Private declarations } protected function CreateProductView: TViewProductsBase0; override; function GetW: TBaseProductsW; override; procedure InitializeColumns; override; public property BillContentModel: TBillContentViewModel read GetBillContentModel write SetBillContentModel; { Public declarations } end; implementation uses NotifyEvents; {$R *.dfm} function TViewBillContent2.CreateProductView: TViewProductsBase0; begin Result := TViewBillContent2.Create(nil); end; procedure TViewBillContent2.cxDBTreeListEditing(Sender: TcxCustomTreeList; AColumn: TcxTreeListColumn; var Allow: Boolean); begin inherited; Allow := False; end; procedure TViewBillContent2.DoAfterLoad(Sender: TObject); begin MyApplyBestFit; end; function TViewBillContent2.GetBillContentModel: TBillContentViewModel; begin Result := M as TBillContentViewModel; end; function TViewBillContent2.GetW: TBaseProductsW; begin Result := BillContentModel.qBillContent.W; end; procedure TViewBillContent2.InitializeColumns; begin inherited; Assert(M <> nil); InitializeLookupColumn(clStorehouseId, BillContentModel.qStoreHouseList.W.DataSource, lsEditFixedList, BillContentModel.qStoreHouseList.W.Abbreviation.FieldName); end; procedure TViewBillContent2.SetBillContentModel(const Value : TBillContentViewModel); begin M := Value; if Value <> nil then TNotifyEventWrap.Create(Value.qBillContent.AfterLoad, DoAfterLoad, FEventList); end; end.
unit shaderu; {$IFDEF FPC}{$mode objfpc}{$H+}{$ENDIF} {$D-,L-,O+,Q-,R-,Y-,S-} {$include opts.inc} interface uses {$IFDEF DGL} dglOpenGL, {$ELSE DGL} {$IFDEF COREGL} glcorearb, {$ELSE} gl, glext, {$ENDIF} {$ENDIF DGL} sysutils,dialogs; const kMaxUniform = 10; kError = 666; kNote = 777; kBool = 0; kInt = 1; kFloat = 2; kSet = 3; type TUniform = record Name: string; Widget: integer; id: GLint; Min,DefaultV,Max: single; Bool: boolean; end; TShader = record FragmentProgram,VertexProgram,Note, Vendor: String; OverlayVolume, SinglePass: integer; nUniform: integer; Uniform: array [1..kMaxUniform] of TUniform; {$IFDEF COREGL} nface, vao_point2d, vbo_face2d, program2d: GLuint; {$ENDIF} end; var gShader: TShader; function LoadShader(lFilename: string; var lShader: TShader): boolean; procedure AdjustShaders (lShader: TShader); implementation uses raycast_common, {$IFDEF COREGL} raycast_core, {$ENDIF} mainunit; procedure AdjustShaders (lShader: TShader); //sends the uniform values to the GPU var i: integer; begin if (lShader.nUniform < 1) or (lShader.nUniform > kMaxUniform) then exit; {$IFDEF SLOWSHADER} //always request ShaderID from name = slow for i := 1 to lShader.nUniform do begin case lShader.Uniform[i].Widget of kFloat: uniform1f(lShader.Uniform[i].name,lShader.Uniform[i].defaultV); kInt: uniform1i(lShader.Uniform[i].name,round(lShader.Uniform[i].defaultV)); kBool: begin if lShader.Uniform[i].bool then uniform1i(lShader.Uniform[i].name,1) else uniform1i(lShader.Uniform[i].name,0); end; end;//case end; //for each uniform {$ELSE} //store ShaderID from name = fase for i := 1 to lShader.nUniform do begin if lShader.Uniform[i].id = 0 then lShader.Uniform[i].id := glGetUniformLocation(gRayCast.GLSLprogram, pAnsiChar(lShader.Uniform[i].name)); case lShader.Uniform[i].Widget of kFloat: glUniform1f(lShader.Uniform[i].id,lShader.Uniform[i].defaultV); kInt: glUniform1i(lShader.Uniform[i].id,round(lShader.Uniform[i].defaultV)); kBool: begin if lShader.Uniform[i].bool then glUniform1i(lShader.Uniform[i].id,1) else glUniform1i(lShader.Uniform[i].id,0); end; end;//case end; //for each uniform {$ENDIF} end; //AdjustShaders function strtofloat0 (lS:string): single; begin result := 0; if length(lS) < 1 then exit; if (upcase (lS[1]) = 'T') or (upcase (lS[1]) = 'F') then exit; //old unsupported 'SET' used true/false booleans try result := strtofloat(lS); except on Exception : EConvertError do result := 0; end; end; function StrToUniform(lS: string): TUniform; var lV: string; lC: char; lLen,lP,lN: integer; begin result.Name := ''; result.Widget := kError; result.id:= 0; lLen := length(lS); //read values lV := ''; lP := 1; lN := 0; while (lP <= lLen) do begin if lS[lP] = '/' then exit; if lS[lP] <> '|' then lV := lV + lS[lP]; if (lS[lP] = '|') or (lP = lLen) then begin inc(lN); case lN of 1: result.Name := lV; 2: begin lC := upcase (lV[1]); case lC of 'S' : result.Widget := kSet; 'B' : result.Widget := kBool; 'I' : result.Widget := kInt; 'F' : result.Widget := kFloat; 'N' : begin result.Widget := kNote; exit; end; else showmessage('Unkown uniform type :'+lV); exit; end; end; 3: begin if (result.Widget = kBool) {or (result.Widget = kSet)} then begin result.bool := upcase (lV[1]) = 'T'; end else result.min := strtofloat0(lV); end; 4: result.defaultv := strtofloat0(lV); 5: result.max := strtofloat0(lV); end; lV := ''; end; inc(lP); end; end; {$IFDEF COREGL} const kDefaultVertex = '#version 330 core' +#10'layout(location = 0) in vec3 vPos;' +#10'out vec3 TexCoord1;' +#10'uniform int zoom = 1;' +#10'uniform mat4 modelViewProjectionMatrix;' +#10'void main() {' +#10' TexCoord1 = vPos;' +#10' gl_Position = modelViewProjectionMatrix * vec4(vPos, 1.0);' +#10' gl_Position.xy *= zoom;' +#10'}'; const kDefaultFragment = '#version 330 core' +#10'in vec3 TexCoord1;' +#10'out vec4 FragColor;' +#10'uniform mat4 modelViewMatrixInverse;' +#10'uniform int loops;' +#10'uniform float stepSize, sliceSize, viewWidth, viewHeight;' +#10'uniform sampler3D intensityVol;' +#10'uniform sampler3D gradientVol;' +#10'uniform sampler2D backFace;' +#10'uniform vec3 clearColor,lightPosition, clipPlane;' +#10'uniform float clipPlaneDepth;' +#10'uniform float ambient = 1.0;' +#10'uniform float diffuse = 0.3;' +#10'uniform float specular = 0.25;' +#10'uniform float shininess = 10.0;' +#10'uniform float edgeThresh = 0.01;' +#10'uniform float edgeExp = 0.15;' +#10'uniform float boundExp = 0.0;' +#10'void main() {' +#10' vec3 backPosition = texture(backFace,vec2(gl_FragCoord.x/viewWidth,gl_FragCoord.y/viewHeight)).xyz;' +#10' vec3 start = TexCoord1.xyz;' +#10' if (backPosition == clearColor) discard;' +#10' vec3 dir = backPosition - start;' +#10' float len = length(dir);' +#10' dir = normalize(dir);' +#10' if (clipPlaneDepth > -0.5) {' +#10' FragColor.rgb = vec3(1.0,0.0,0.0);' +#10' bool frontface = (dot(dir , clipPlane) > 0.0);' +#10' float dis = dot(dir,clipPlane);' +#10' if (dis != 0.0 ) dis = (-clipPlaneDepth - dot(clipPlane, start.xyz-0.5)) / dis;' +#10' if ((frontface) && (dis >= len)) len = 0.0;' +#10' if ((!frontface) && (dis <= 0.0)) len = 0.0;' +#10' if ((dis > 0.0) && (dis < len)) {' +#10' if (frontface) {' +#10' start = start + dir * dis;' +#10' } else {' +#10' backPosition = start + dir * (dis);' +#10' }' +#10' dir = backPosition - start;' +#10' len = length(dir);' +#10' dir = normalize(dir);' +#10' }' +#10' }' +#10' vec3 deltaDir = dir * stepSize;' +#10' vec4 colorSample,gradientSample,colAcc = vec4(0.0,0.0,0.0,0.0);' +#10' float lengthAcc = 0.0;' +#10' vec3 samplePos = start.xyz + deltaDir* (fract(sin(gl_FragCoord.x * 12.9898 + gl_FragCoord.y * 78.233) * 43758.5453));' +#10' vec4 prevNorm = vec4(0.0,0.0,0.0,0.0);' +#10' vec3 lightDirHeadOn = normalize(modelViewMatrixInverse * vec4(0.0,0.0,1.0,0.0)).xyz ;' +#10' float stepSizex2 = sliceSize * 2.0;' +#10' for(int i = 0; i < loops; i++) {' +#10' //colorSample = texture(gradientVol, samplePos);' +#10' colorSample = texture(intensityVol,samplePos);' +#10' if ((lengthAcc <= stepSizex2) && (colorSample.a > 0.01) ) colorSample.a = sqrt(colorSample.a);' +#10' colorSample.a = 1.0-pow((1.0 - colorSample.a), stepSize/sliceSize);' +#10' if ((colorSample.a > 0.01) && (lengthAcc > stepSizex2) ) {' +#10' gradientSample= texture(gradientVol,samplePos);' +#10' gradientSample.rgb = normalize(gradientSample.rgb*2.0 - 1.0);' +#10' if (gradientSample.a < prevNorm.a)' +#10' gradientSample.rgb = prevNorm.rgb;' +#10' prevNorm = gradientSample;' +#10' float lightNormDot = dot(gradientSample.rgb, lightDirHeadOn);' +#10' float edgeVal = pow(1.0-abs(lightNormDot),edgeExp);' +#10' edgeVal = edgeVal * pow(gradientSample.a,0.3);' +#10' if (edgeVal >= edgeThresh)' +#10' colorSample.rgb = mix(colorSample.rgb, vec3(0.0,0.0,0.0), pow((edgeVal-edgeThresh)/(1.0-edgeThresh),4.0));' +#10' if (boundExp > 0.0)' +#10' colorSample.a = colorSample.a * pow(gradientSample.a,boundExp)*pow(1.0-abs(lightNormDot),6.0);' +#10' lightNormDot = dot(gradientSample.rgb, lightPosition);' +#10' vec3 a = colorSample.rgb * ambient;' +#10' vec3 d = max(lightNormDot, 0.0) * colorSample.rgb * diffuse;' +#10' float s = specular * pow(max(dot(reflect(lightPosition, gradientSample.rgb), dir), 0.0), shininess);' +#10' colorSample.rgb = a + d + s;' +#10' }' +#10' colorSample.rgb *= colorSample.a;' +#10' colAcc= (1.0 - colAcc.a) * colorSample + colAcc;' +#10' samplePos += deltaDir;' +#10' lengthAcc += stepSize;' +#10' if ( lengthAcc >= len || colAcc.a > 0.95 )' +#10' break;' +#10' }' +#10' colAcc.a = colAcc.a/0.95;' +#10' if ( colAcc.a < 1.0 )' +#10' colAcc.rgb = mix(clearColor,colAcc.rgb,colAcc.a);' +#10' if (len == 0.0) colAcc.rgb = clearColor;' +#10' FragColor = colAcc;' +#10'}'; {$ELSE} const kDefaultVertex = 'void main() { gl_TexCoord[1] = gl_MultiTexCoord1; gl_Position = ftransform();}' ; const kDefaultFragment = 'uniform int loops;' +'uniform float stepSize, sliceSize, viewWidth, viewHeight, clipPlaneDepth;' +'uniform sampler3D intensityVol;' +'uniform sampler2D backFace;' +'uniform vec3 clearColor, clipPlane;' +'void main() {' +' vec3 backPosition = texture2D(backFace,vec2(gl_FragCoord.x/viewWidth,gl_FragCoord.y/viewHeight)).xyz;' +' vec3 start = gl_TexCoord[1].xyz;' +' vec3 dir = backPosition - start;' +' float len = length(dir);' +' dir = normalize(dir);' +' if (clipPlaneDepth > -0.5) {' +' bool frontface = (dot(dir , clipPlane) > 0.0);' +' float dis = dot(dir,clipPlane);' +' if (dis != 0.0 ) dis = (-clipPlaneDepth - dot(clipPlane, start.xyz-0.5)) / dis;' +' if ((frontface) && (dis >= len)) len = 0.0;' +' if ((!frontface) && (dis <= 0.0)) len = 0.0;' +' if ((dis > 0.0) && (dis < len)) {' +' if (frontface) {' +' start = start + dir * dis;' +' } else {' +' backPosition = start + dir * (dis); ' +' }' +' dir = backPosition - start;' +' len = length(dir);' +' dir = normalize(dir); ' +' }' +' }' +' vec3 deltaDir = dir * stepSize;' +' vec4 colorSample,colAcc = vec4(0.0,0.0,0.0,0.0);' +' float lengthAcc = 0.0;' +' float opacityCorrection = stepSize/sliceSize;' +' vec3 samplePos = start.xyz;' +' for(int i = 0; i < loops; i++) {' +' colorSample = texture3D(intensityVol,samplePos);' +' colorSample.a = 1.0-pow((1.0 - colorSample.a), opacityCorrection); ' +' colorSample.rgb *= colorSample.a; ' +' colAcc= (1.0 - colAcc.a) * colorSample + colAcc;' +' samplePos += deltaDir;' +' lengthAcc += stepSize;' +' if ( lengthAcc >= len || colAcc.a > 0.95 )' +' break;' +' }' +' colAcc.rgb = mix(clearColor,colAcc.rgb,colAcc.a);' +' gl_FragColor = colAcc;' +'}'; {$ENDIF} function DefaultShader: TShader; begin result.Note := 'Please reinstall this software: Unable to find the shader folder'; result.VertexProgram := kDefaultVertex; result.nUniform := 0; result.OverlayVolume := 0;//false; result.SinglePass := 0; result.FragmentProgram := kDefaultFragment; end; function LoadShader(lFilename: string; var lShader: TShader): boolean; //modes const //kCR = chr (13)+chr(10); //UNIX end of line //kCR = chr(10); //UNIX end of line knone=0; kpref=1; kvert = 2; kfrag = 3; var mode: integer; F : TextFile; S: string; U: TUniform; begin Result := false; lShader.Note := ''; lShader.VertexProgram := ''; lShader.nUniform := 0; lShader.OverlayVolume := 0;//false; lShader.SinglePass := 0; lShader.FragmentProgram := ''; if not fileexists(lFilename) then lFilename := lFilename +'.txt'; if not fileexists(lFilename) then begin lShader := DefaultShader; exit; end; mode := knone; FileMode := fmOpenRead; AssignFile(F,lFilename); Reset(F); while not Eof(F) do begin ReadLn(F, S); if S = '//pref' then mode := kpref else if S = '//frag' then mode := kfrag else if S = '//vert' then mode := kvert else if mode = kpref then begin U := StrToUniform(S); if U.Widget = kSet then begin if U.Name = 'singlePass' then lShader.SinglePass:= round(U.min) ; if U.Name = 'overlayVolume' then lShader.OverlayVolume:= round(U.min) ; //U.Bool; end else if U.Widget = kNote then lShader.Note := U.Name else if U.Widget <> kError then begin if (lShader.nUniform < kMaxUniform) then begin inc(lShader.nUniform); lShader.Uniform[lShader.nUniform] := U; end else showmessage('Too many preferences'); end ; //mode := kpref end else if mode = kfrag then lShader.FragmentProgram := lShader.FragmentProgram + S+#13#10 //kCR else if mode = kvert then lShader.VertexProgram := lShader.VertexProgram + S+#13#10; end;//EOF CloseFile(F); if lShader.VertexProgram = '' then lShader.VertexProgram := kDefaultVertex; if lShader.FragmentProgram = '' then begin lShader.nUniform := 0; lShader.OverlayVolume := 0;//false; lShader.FragmentProgram := kDefaultFragment; end; result := true; end; end.
unit uHttpDownloader2; interface uses Windows, Messages, SysUtils, Variants, Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, math, uFileBlockStream; Const _1seg = 1/24/3600; _500ms = 1/24/3600/2; type THttpDownloaderProgress = procedure (Sender: TObject; aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate:boolean) of Object; THttpDownloader = class; THttpDownloadThread = class(TThread) private FOnProgress : THttpDownloaderProgress; IdHTTP1: TIdHTTP; fHttpDownloader : THttpDownloader; FIniTime : TDateTime; FVelInst : double; //FVelMedia : double; FLastTime : TDateTime; FLastUpdate : TDateTime; FLastBytes : int64; fs : TFileBlockStream; fSyncPosition, fSyncSize: int64; fSyncPercent, fSyncVel: double; fSyncTimeLeft: TDateTime; fSyncaMayUpdate: boolean; procedure SyncOnProgress; procedure doOnProgress (aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate:boolean); protected procedure Execute; override; public result : boolean; property OnProgress : THttpDownloaderProgress read FOnProgress write FOnProgress; procedure BufferEvent(Sender: TObject; var Buffer; Count: Longint; isLast:boolean); constructor Create(aHttpDownloader:THttpDownloader); destructor Destroy; override; end; THttpDownloader = class(TComponent) private fHttpDownloadThread : THttpDownloadThread; FHost : string; FURLpath : string; FFilename : string; FdnFolder : string; FDelay : integer; FOnProgress : THttpDownloaderProgress; procedure SetdnFolder (adnFolder : string); { Private declarations } public property Delay : integer read FDelay write FDelay; property Host : string read FHost write FHost; property URLpath : string read FURLpath write FURLpath; property Filename : string read FFilename write FFilename; property dnFolder : string read FdnFolder write SetdnFolder; property OnProgress : THttpDownloaderProgress read FOnProgress write FOnProgress; function Download:boolean; procedure fHttpDownloadThreadOnProgress(Sender: TObject; aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate:boolean); procedure Cancel; constructor Create(AOwner: TComponent); override; destructor Destroy; override; { Public declarations } end; implementation constructor THttpDownloader.Create(AOwner: TComponent); begin inherited Create(AOwner); fHttpDownloadThread := THttpDownloadThread.Create(self); end; destructor THttpDownloader.Destroy; begin fHttpDownloadThread.free; inherited Destroy; end; procedure THttpDownloader.SetdnFolder (adnFolder: string); begin if adnFolder<>FdnFolder then begin FdnFolder := adnFolder; forcedirectories (FdnFolder); end; end; procedure THttpDownloader.Cancel; begin fHttpDownloadThread.IdHTTP1.Disconnect; end; function THttpDownloader.Download:boolean; begin fHttpDownloadThread.OnProgress := fHttpDownloadThreadOnProgress; fHttpDownloadThread.Resume; repeat sleep(100); until fHttpDownloadThread.Terminated; result := fHttpDownloadThread.result; end; procedure THttpDownloader.fHttpDownloadThreadOnProgress(Sender: TObject; aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate: boolean); begin if assigned(FOnProgress) then FOnProgress(Self, aPosition, aSize, aPercent, aVel, aTimeLeft, aMayUpdate); end; { THttpDownloadThread } constructor THttpDownloadThread.Create(aHttpDownloader:THttpDownloader); begin inherited create(true); fHttpDownloader := aHttpDownloader; IdHTTP1 := TIdHTTP.Create(nil); end; destructor THttpDownloadThread.Destroy; begin IdHTTP1.Free; inherited; end; procedure THttpDownloadThread.doOnProgress(aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate: boolean); begin fSyncPosition := aPosition; fSyncSize := aSize; fSyncPercent := aPercent; fSyncVel := aVel; fSyncTimeLeft := aTimeLeft; fSyncaMayUpdate := aMayUpdate; Synchronize(SyncOnProgress); end; procedure THttpDownloadThread.SyncOnProgress; begin if assigned(FOnProgress) then FOnProgress(Self, fSyncPosition, fSyncSize, fSyncPercent, fSyncVel, fSyncTimeLeft, fSyncaMayUpdate); end; procedure THttpDownloadThread.Execute; var cl : integer; err : boolean; procedure cleanup; begin fs.Free; if err and (fileexists(fHttpDownloader.dnFolder+fHttpDownloader.Filename)) then deletefile(fHttpDownloader.dnFolder+fHttpDownloader.Filename); end; begin result := false; err:= true; cl:=0; FLastTime :=0; FLastUpdate :=0; FLastBytes :=0; if fileexists(fHttpDownloader.dnFolder+fHttpDownloader.Filename) then deletefile(fHttpDownloader.dnFolder+fHttpDownloader.Filename); fs := TFileBlockStream.Create(fHttpDownloader.dnFolder+fHttpDownloader.Filename, fmCreate ); fs.WriteBlockSize := $FFFF; fs.OnWriteBuffer := BufferEvent; IdHTTP1.Host := fHttpDownloader.Host; try IdHTTP1.head(fHttpDownloader.URLpath+fHttpDownloader.Filename); fs.WriteBlockSize := $FFFF;// * 10; FIniTime := now; IdHTTP1.get(fHttpDownloader.URLpath+fHttpDownloader.Filename, fs); if IdHTTP1.Response.HasContentLength then cl := IdHTTP1.Response.ContentLength; err:=( cl>0)and(cl<>fs.size); result:=( cl>0)and(cl=fs.size); except on e:exception do begin cleanup; raise; end; end; cleanup; end; procedure THttpDownloadThread.BufferEvent(Sender: TObject; var Buffer; Count: Longint; isLast:boolean); var TimeLeft: TDateTime; MayUpdate : boolean; begin TimeLeft := 0; MayUpdate := false; if now-FLastTime>0 then begin FVelInst := (fs.Position - FLastBytes) / ((now-FLastTime)*24*3600); try TimeLeft := ( (fs.Size - fs.Position) / FVelInst / 24 / 3600 ) + _1seg; ; except TimeLeft := 0; end; MayUpdate := (now-FLastUpdate) > _500ms ; if MayUpdate then FLastUpdate := 0; end; doOnProgress(fs.Position, fs.Size, (fs.Position/fs.Size)*100, FVelInst, TimeLeft, MayUpdate); FLastTime := now; FLastBytes := fs.Position; if fHttpDownloader.Delay>0 then sleep(fHttpDownloader.Delay); end; end.
unit Ths.Erp.Database.Table.View.SysViewTables; interface {$I ThsERP.inc} uses SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils, FireDAC.Stan.Param, System.Variants, Data.DB, Ths.Erp.Database, Ths.Erp.Database.Table, Ths.Erp.Database.Table.View; type TSysViewTables = class(TView) private FTableName: TFieldDB; FTableType: TFieldDB; protected published constructor Create(OwnerDatabase:TDatabase);override; public procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override; procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override; function Clone():TTable;override; Property TableName1: TFieldDB read FTableName write FTableName; Property TableType: TFieldDB read FTableType write FTableType; end; implementation uses Ths.Erp.Database.Singleton; constructor TSysViewTables.Create(OwnerDatabase:TDatabase); begin inherited Create(OwnerDatabase); TableName := 'sys_view_tables'; SourceCode := '1000'; FTableName := TFieldDB.Create('table_name', ftString, ''); FTableType := TFieldDB.Create('table_type', ftString, ''); end; procedure TSysViewTables.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin with QueryOfDS do begin Close; SQL.Clear; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + FTableName.FieldName, TableName + '.' + FTableType.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; Active := True; Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'Table Name'; Self.DataSource.DataSet.FindField(FTableType.FieldName).DisplayLabel := 'Table Type'; end; end; end; procedure TSysViewTables.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); begin if IsAuthorized(ptRead, pPermissionControl) then begin if (pLock) then pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT'; with QueryOfList do begin Close; SQL.Text := Database.GetSQLSelectCmd(TableName, [ TableName + '.' + FTableName.FieldName, TableName + '.' + FTableType.FieldName ]) + 'WHERE 1=1 ' + pFilter; Open; FreeListContent(); List.Clear; while NOT EOF do begin FTableName.Value := FormatedVariantVal(FieldByName(FTableName.FieldName).DataType, FieldByName(FTableName.FieldName).Value); FTableType.Value := FormatedVariantVal(FieldByName(FTableType.FieldName).DataType, FieldByName(FTableType.FieldName).Value); List.Add(Self.Clone()); Next; end; EmptyDataSet; Close; end; end; end; function TSysViewTables.Clone():TTable; begin Result := TSysViewTables.Create(Database); FTableName.Clone(TSysViewTables(Result).FTableName); FTableType.Clone(TSysViewTables(Result).FTableType); end; end.
unit ULog; interface uses windows,SysUtils; type TLog = class private mFile:TextFile; public constructor Create(FileName:String); destructor Destroy(); override; procedure WriteLog(S: String); end; var Log:TLog; implementation { TLog } constructor TLog.Create(FileName: String); begin AssignFile(mFile, FileName); if FileExists(FileName) then begin Append(mFile); end else begin Rewrite(mFile); end; end; destructor TLog.Destroy; begin CloseFile(mFile); end; procedure TLog.WriteLog(S: String); begin Writeln(mFile,TimeToStr(Now)+' ' + S); Flush(mFile); end; end.
unit FileUtil; { LLCL - FPC/Lazarus Light LCL based upon LVCL - Very LIGHT VCL ---------------------------- This file is a part of the Light LCL (LLCL). This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. Copyright (c) 2015-2016 ChrisF Based upon the Very LIGHT VCL (LVCL): Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr Version 1.02: * DeleteFileUTF8 and RenameFileUTF8 added Version 1.01: Version 1.00: * File creation. * UTF8 file functions (equivalent of SysUtils ones - mapped to LazFileutils) * Some other ones (SysToUTF8, UTF8ToSys) Notes: - specific to FPC/Lazarus (not used with Delphi). } {$IFDEF FPC} {$define LLCL_FPC_MODESECTION} {$I LLCLFPCInc.inc} // For mode {$undef LLCL_FPC_MODESECTION} {$ENDIF} {$I LLCLOptions.inc} // Options //------------------------------------------------------------------------------ interface uses SysUtils; function FileCreateUTF8(const FileName: string) : THandle; function FileOpenUTF8(const FileName: string; Mode: cardinal) : THandle; function FileExistsUTF8(const Filename: string): boolean; function FileSetDateUTF8(const FileName: string; Age: integer): integer; function FileAgeUTF8(const FileName: string): integer; function FindFirstUTF8(const Path: string; Attr: longint; out Rslt: TSearchRec): longint; function FindNextUTF8(var Rslt: TSearchRec): longint; procedure FindCloseUTF8(var F: TSearchrec); function FileSize(const Filename: string): int64; function GetCurrentDirUTF8(): string; function SetCurrentDirUTF8(const NewDir: string): boolean; function DirectoryExistsUTF8(const Directory: string): boolean; function ForceDirectoriesUTF8(const Dir: string): boolean; function CreateDirUTF8(const Dir: string): boolean; function RemoveDirUTF8(const Dir: string): boolean; function DeleteFileUTF8(const FileName: string): boolean; function RenameFileUTF8(const OldName, NewName: string): boolean; // (No GetFileVersionUTF8 function) function SysErrorMessageUTF8(ErrorCode: integer): string; {$IFDEF UNICODE} function UTF8ToSys(const S: utf8string): ansistring; function SysToUTF8(const S: ansistring): utf8string; {$ELSE UNICODE} function UTF8ToSys(const S: string): string; function SysToUTF8(const S: string): string; {$ENDIF UNICODE} //------------------------------------------------------------------------------ implementation uses LazFileUtils, LazUTF8; {$IFDEF FPC} {$PUSH} {$HINTS OFF} {$ENDIF} function FileCreateUTF8(const FileName: string) : THandle; begin result := LazFileUtils.FileCreateUTF8(FileName); end; function FileOpenUTF8(const FileName: string; Mode: cardinal) : THandle; begin result := LazFileUtils.FileOpenUTF8(FileName, Mode); end; function FileExistsUTF8(const Filename: string): boolean; begin result := LazFileUtils.FileExistsUTF8(Filename); end; function FileSetDateUTF8(const FileName: string; Age: integer): integer; begin result := LazFileUtils.FileSetDateUTF8(Filename, Age); end; function FileAgeUTF8(const FileName: string): integer; begin result := LazFileUtils.FileAgeUTF8(Filename); end; function FindFirstUTF8(const Path: string; Attr: longint; out Rslt: TSearchRec): longint; begin result := LazFileUtils.FindFirstUTF8(Path, Attr, Rslt); end; function FindNextUTF8(var Rslt: TSearchRec): longint; begin result := LazFileUtils.FindNextUTF8(Rslt); end; procedure FindCloseUTF8(var F: TSearchrec); begin LazFileUtils.FindCloseUTF8(F); end; // (FileSize for Fileutil and FileSizeUTF8 for LazFileUtils) function FileSize(const Filename: string): int64; begin result := LazFileUtils.FileSizeUTF8(Filename); end; function GetCurrentDirUTF8(): string; begin result := LazFileUtils.GetCurrentDirUTF8(); end; function SetCurrentDirUTF8(const NewDir: string): boolean; begin result := LazFileUtils.SetCurrentDirUTF8(NewDir); end; function DirectoryExistsUTF8(const Directory: string): boolean; begin result := LazFileUtils.DirectoryExistsUTF8(Directory); end; function ForceDirectoriesUTF8(const Dir: string): boolean; begin result := LazFileUtils.ForceDirectoriesUTF8(Dir); end; function CreateDirUTF8(const Dir: string): boolean; begin result := LazFileUtils.CreateDirUTF8(Dir); end; function RemoveDirUTF8(const Dir: string): boolean; begin result := LazFileUtils.RemoveDirUTF8(Dir); end; function DeleteFileUTF8(const FileName: string): boolean; begin result := LazFileUtils.DeleteFileUTF8(FileName); end; function RenameFileUTF8(const OldName, NewName: string): boolean; begin result := LazFileUtils.RenameFileUTF8(OldName, NewName); end; //------------------------------------------------------------------------------ // (Functions belonging to LazUTF8) function SysErrorMessageUTF8(ErrorCode: integer): string; begin result := LazUTF8.SysErrorMessageUTF8(ErrorCode); end; {$IFDEF UNICODE} function UTF8ToSys(const S: utf8string): ansistring; {$ELSE UNICODE} function UTF8ToSys(const S: string): string; {$ENDIF UNICODE} begin result := LazUTF8.UTF8ToSys(S); end; {$IFDEF UNICODE} function SysToUTF8(const S: ansistring): utf8string; {$ELSE UNICODE} function SysToUTF8(const S: string): string; {$ENDIF UNICODE} begin result := LazUTF8.SysToUTF8(S); end; //------------------------------------------------------------------------------ {$IFDEF FPC} {$POP} {$ENDIF} end.
unit PlotMath; interface uses // Classes, // TeEngine, // StringCalc, SpectrumTypes{, Plots}; type TSelectGraphsDlgOption = (sgdoAllowReorder); TSelectGraphsDlgOptions = set of TSelectGraphsDlgOption; //function SelectGraphs(const ACaption: String; APlot: TPlot; // var Selects: TGraphArray; Selected: TCustomSeriesList = nil; // Options: TSelectGraphsDlgOptions = []): Boolean; overload; //function SelectGraph(): TGraph; overload; //function AskTrimParams(var AParams: TTrimParams): Boolean; function AskRandomSampleParams(out AParams: TRandomSampleParams): Boolean; //function AskOffsetParams(var AParams: TOffsetParams): Boolean; //function AskNormalizeParams(var AParams: TNormalizeParams): Boolean; //function AskScaleParams(var AParams: TScaleParams): Boolean; //function AskFlipParams(var AParams: TMiscParams): Boolean; //function AskInverseParams(var AParams: TMiscParams): Boolean; //function AskVarianceParams(var AParams: TVarianceParams): Boolean; //function AskDespikeParams(var AParams: TDespikeParams): Boolean; //function AskFormulaParams(AParams: TFormulaParams): Boolean; //function EditFormulaParams(AParams: TFormulaParams): Boolean; function GetSampleGraph(var AParams: TRandomSampleParams): TGraphRec; procedure FillSampleValues(out ValuesX: TValueArray; out ValuesY: TValueArray; Count: Integer); overload; procedure FillSampleValues(out ValuesX: TValueArray; out ValuesY: TValueArray; var AParams: TRandomSampleParams); overload; function TrimValuesLeft(var ValuesX: TValueArray; var ValuesY: TValueArray; const Value: TValue; Refine: Boolean): Boolean; function TrimValuesRight(var ValuesX: TValueArray; var ValuesY: TValueArray; const Value: TValue; Refine: Boolean): Boolean; procedure NormalizeValues(var Values: TValueArray; const Value: TValue; PerMax: Boolean); procedure ScaleValues(var Values: TValueArray; CenterKind: TScaleCenterKind; const CenterValue, Value: TValue); procedure OffsetValues(var Values: TValueArray; Kind: TOffsetKind; const Value: TValue); overload; procedure OffsetValues(var Values: TValueArray; const Value: TValue); overload; procedure InverseValues(var Values, Values1: TValueArray; const Value: TValue); procedure FlipValues(var Values: TValueArray; const Value: TValue); procedure DespikePer(var Values: TValueArray; RangeMin, RangeMax: TValue); procedure DespikeAbs(var Values: TValueArray; RangeMin, RangeMax: TValue); procedure ReorderValues(var ValuesX, ValuesY: TValueArray); procedure Sort(var ValuesX, ValuesY: TValueArray); overload; procedure Sort(var G: TGraphRec2); overload; type TPartialFunc = function (const Values: TValueArray; Index1, Index2: Integer): TValue; function CallPartialFunc(const ValuesX, ValuesY: TValueArray; const Limit1, Limit2: TValue; Func: TPartialFunc): TValue; procedure GetPartialBounds(const Values: TValueArray; const Limit1, Limit2: TValue; out Index1, Index2: Integer); function GetPointCount(const Values: TValueArray; Min, Max: TValue): Integer; //procedure GetOverlapLimits(const Graphs: TGraphArray; out Min, Max: TValue); function CalcOverlapGraph(const Gr1, Gr2: TGraphRec; AllPoints: Boolean = False; Min: TValue = VALUE_MIN; Max: TValue = VALUE_MAX): TGraphRec2; function MeanAM(const Values: TValueArray): TValue; overload; function MeanAM(const ValuesX, ValuesY: TValueArray; const Limit1, Limit2: TValue): TValue; overload; function MeanAMPart(const Values: TValueArray; Index1, Index2: Integer): TValue; function MaxValue(const Values: TValueArray): TValue; function MinValue(const Values: TValueArray): TValue; function MaxValueIndex(const Values: TValueArray): Integer; function MinValueIndex(const Values: TValueArray): Integer; procedure GetMinMax(const Values: TValueArray; out MinValue, MaxValue: TValue); function AverageValue(const Values: TValueArray): Extended; // тоже что MeanAM procedure Differentiate(const X, Y: TValueArray; var DY: TValueArray); procedure Differentiate2(const X, Y: TValueArray; var DY: TValueArray); procedure Variance(const X, Y: TValueArray; var SX, SY: TValueArray); procedure Regularity(const Values: TValueArray; var X, Y: TValueArray); //procedure SumGraphs(var Selects: TGraphArray); //function CheckFormula(const Formula: String): Boolean; //procedure ParseFormula(const Formula: String; Calc: TStringCalc); //procedure PlotFormula(Params: TFormulaParams; var ValuesX, ValuesY: TValueArray); function FormulaExpression(const Formula: String): String; //function GraphToRec(Graph: TGraph): TGraphRec; inline; implementation uses SysUtils, Controls, Classes, Math, OriUtils, OriStrings, DlgParamsRandom; // WinGraphsSelect, WinParamsTrim, WinParamsRandomSample, WinParamsOffset, // WinParamsNorm, WinParamsScale, WinParamsMisc, WinParamsAllan, WinParamsDespike, // WinFormula; {%region 'Ask params routines'} { function AskTrimParams(var AParams: TTrimParams): Boolean; begin Result := TwndParamsTrim.Create(@AParams).ShowModal = mrOk; end; } function AskRandomSampleParams(out AParams: TRandomSampleParams): Boolean; begin Result := TRandomParamsDlg.Create(AParams).ShowModal = mrOK; end; { function AskOffsetParams(var AParams: TOffsetParams): Boolean; begin Result := TwndParamsOffset.Create(@AParams).ShowModal = mrOK; end; function AskNormalizeParams(var AParams: TNormalizeParams): Boolean; begin Result := TwndParamsNorm.Create(@AParams).ShowModal = mrOK; end; function AskScaleParams(var AParams: TScaleParams): Boolean; begin Result := TwndParamsScale.Create(@AParams).ShowModal = mrOK; end; function AskFlipParams(var AParams: TMiscParams): Boolean; begin Result := TwndParamsMisc.CreateFlip(@AParams).ShowModal = mrOK; end; function AskInverseParams(var AParams: TMiscParams): Boolean; begin Result := TwndParamsMisc.CreateInverse(@AParams).ShowModal = mrOK; end; function AskVarianceParams(var AParams: TVarianceParams): Boolean; begin Result := TwndParamsAllan.Create(@AParams).ShowModal = mrOK; end; function AskDespikeParams(var AParams: TDespikeParams): Boolean; begin Result := TwndParamsDespike.Create(@AParams).ShowModal = mrOK; end; function AskFormulaParams(AParams: TFormulaParams): Boolean; begin Result := TwndFormula.Create(AParams).ShowModal = mrOK; end; function EditFormulaParams(AParams: TFormulaParams): Boolean; begin Result := TwndFormula.CreateEdit(AParams).ShowModal = mrOK; end; } {%endregion} //function SelectGraphs(const ACaption: String; APlot: TPlot; // var Selects: TGraphArray; Selected: TCustomSeriesList; // Options: TSelectGraphsDlgOptions): Boolean; overload; //begin // Result := False; // if APlot.Count > 0 then // with TwndGraphsSelect.Create(ACaption, APlot) do // try // SetOrderBtnsVisible(sgdoAllowReorder in Options); // if Assigned(Selected) // then SetSelected(Selected) // else SetSelected(Selects); // Result := ShowModal = mrOk; // if Result then // Selects := GetSelected; // finally // Free; // end; //end; { Уточнение границы: F0 = F1 + (F2 - F1)(X0 - X1)/(X2 - X1) где X0 - положение границы (точка обрезки) F0 - значение графика в точке обрезки X1, X2 - ближайшие точки слева и справа от X0 F1, F2 - значения графика в точках X1, X2 } function TrimValuesLeft(var ValuesX: TValueArray; var ValuesY: TValueArray; const Value: TValue; Refine: Boolean): Boolean; var I: Integer; TrimIndex: Integer; // точка, начиная с которой нужно оставить begin TrimIndex := 0; for I := 0 to Length(ValuesX)-1 do if ValuesX[I] > Value then begin if Refine and (I > 0) then begin TrimIndex := I-1; ValuesY[TrimIndex] := ValuesY[I-1] + (ValuesY[I] - ValuesY[I-1])* (Value - ValuesX[I-1]) / (ValuesX[I] - ValuesX[I-1]); ValuesX[TrimIndex] := Value; end else // оставляем ближайшую к заданной точку if (I > 0) and (ValuesX[I]-Value > Value-ValuesX[I-1]) then TrimIndex := I-1 else TrimIndex := I; Break; end; // (Length(ValuesX)-2) т.к. нужно чтобы в графике осталось хотя бы две точки. // В противном случае считаем, что линии обрезки лежит за пределами // графика и никакой обрезки не присходит. Result := ((TrimIndex > 0) or Refine) and (TrimIndex < Length(ValuesX)-2); if Result then begin ValuesX := Copy(ValuesX, TrimIndex, MaxInt); ValuesY := Copy(ValuesY, TrimIndex, MaxInt); end; end; function TrimValuesRight(var ValuesX: TValueArray; var ValuesY: TValueArray; const Value: TValue; Refine: Boolean): Boolean; var I: Integer; TrimIndex: Integer; // точка, начиная с которой нужно удалить begin TrimIndex := 0; for I := 0 to Length(ValuesX)-1 do if ValuesX[I] > Value then begin if Refine and (I > 0) then begin TrimIndex := I; ValuesY[TrimIndex] := ValuesY[I-1] + (ValuesY[I] - ValuesY[I-1])* (Value - ValuesX[I-1]) / (ValuesX[I] - ValuesX[I-1]); ValuesX[TrimIndex] := Value; end else // Оставляем ближайшую к заданной точку. if (I > 0) and (ValuesX[I]-Value > Value-ValuesX[I-1]) then TrimIndex := I-1 else TrimIndex := I; Break; end; // (TrimIndex > 1) т.к. нужно чтобы в графике осталось хотя бы две точки. // В противном случае считаем, что линии обрезки лежит за пределами // графика и никакой обрезки не присходит. Result := (TrimIndex > 1) and ((TrimIndex < Length(ValuesX)-1) or Refine); if Result then begin SetLength(ValuesX, TrimIndex+1); SetLength(ValuesY, TrimIndex+1); end; end; function GetSampleGraph(var AParams: TRandomSampleParams): TGraphRec; begin FillSampleValues(Result.X, Result.Y, AParams); end; procedure FillSampleValues(out ValuesX: TValueArray; out ValuesY: TValueArray; Count: Integer); const H = 25.0; var i: Integer; Y: TValue; begin SetLength(ValuesX, Count); SetLength(ValuesY, Count); Y := Random(100)*H*0.01; for i := 0 to Count-1 do begin Y := Abs(Y + Random(100)*H*0.01 - H*0.5); ValuesX[i] := i; ValuesY[i] := Y; end; end; procedure FillSampleValues(out ValuesX: TValueArray; out ValuesY: TValueArray; var AParams: TRandomSampleParams); var I, Count: Integer; Y, X, StepX, H: TValue; begin CalcStep(AParams.X, Count, StepX); SetLength(ValuesX, Count); SetLength(ValuesY, Count); Randomize; H := (AParams.MaxY - AParams.MinY) / Count * 25; X := AParams.X.Min; Y := Random*H; for I := 0 to Count-1 do begin ValuesX[I] := X; ValuesY[I] := Y; X := X + StepX; Y := Y + Random*H - H*0.5; if Y > AParams.MaxY then Y := 2* AParams.X.Max - Y else if Y < AParams.MinY then Y := 2* AParams.X.Min - Y; end; end; procedure NormalizeValues(var Values: TValueArray; const Value: TValue; PerMax: Boolean); var I: Integer; Fact: Extended; begin if PerMax then begin Fact := -MaxExtended; for I := 0 to Length(Values)-1 do if Values[I] > Fact then Fact := Values[I]; end else Fact := Value; for I := 0 to Length(Values)-1 do Values[I] := Values[I] / Fact; end; procedure ScaleValues(var Values: TValueArray; CenterKind: TScaleCenterKind; const CenterValue, Value: TValue); var I: Integer; OffsetValue: TValue; begin case CenterKind of sckNone: OffsetValue := 0; sckMax: OffsetValue := MaxValue(Values); sckMin: OffsetValue := MinValue(Values); sckAvg: OffsetValue := AverageValue(Values); else OffsetValue := CenterValue; end; for I := 0 to Length(Values)-1 do Values[I] := (Values[I] - OffsetValue) * Value + OffsetValue; end; procedure OffsetValues(var Values: TValueArray; Kind: TOffsetKind; const Value: TValue); var OffsetValue: TValue; begin case Kind of ofkMax: OffsetValue := -MaxValue(Values); ofkMin: OffsetValue := -MinValue(Values); ofkAvg: OffsetValue := -AverageValue(Values); else OffsetValue := Value; end; OffsetValues(Values, OffsetValue); end; procedure OffsetValues(var Values: TValueArray; const Value: TValue); var I: Integer; begin for I := 0 to Length(Values)-1 do Values[I] := Values[I] + Value; end; procedure FlipValues(var Values: TValueArray; const Value: TValue); var I: Integer; begin for I := 0 to Length(Values)-1 do Values[I] := Value - Values[I]; end; // Чтобы избежать деления на ноль выбрасываем нулевые точки из обрабатываеммого // массива. Но, т.к. массив часть графика, то нужно выбросить и соответствующую // точку и из парного массива. procedure InverseValues(var Values, Values1: TValueArray; const Value: TValue); var I, J: Integer; begin J := 0; for I := 0 to Length(Values)-1 do if Values[I] <> 0 then begin Values[J] := Value / Values[I]; Values1[J] := Values1[I]; Inc(J); end; SetLength(Values, J); SetLength(Values1, J); end; procedure Differentiate(const X, Y: TValueArray; var DY: TValueArray); var I: Integer; begin SetLength(DY, Length(X)); DY[0] := (Y[1] - Y[0]) / (X[1] - X[0]); for I := 1 to Length(X)-2 do DY[I] := ((Y[I+1] - Y[I]) / (X[I+1] - X[I]) + (Y[I] - Y[I-1]) / (X[I] - X[I-1])) / 2; I := Length(X)-1; DY[I] := (Y[I] - Y[I-1]) / (X[I] - X[I-1]); end; procedure Differentiate2(const X, Y: TValueArray; var DY: TValueArray); var I: Integer; begin SetLength(DY, Length(X)-2); for I := 1 to Length(X)-2 do DY[I-1] := (Y[I+1] + Y[I-1] - Y[I] - Y[I]) / (X[I+1] - X[I]) / (X[I] - X[I-1]); end; function MaxValue(const Values: TValueArray): TValue; var I: Integer; begin Result := -MaxDouble; for I := 0 to Length(Values)-1 do if Values[I] > Result then Result := Values[I]; end; function MinValue(const Values: TValueArray): TValue; var I: Integer; begin Result := MaxDouble; for I := 0 to Length(Values)-1 do if Values[I] < Result then Result := Values[I]; end; function MaxValueIndex(const Values: TValueArray): Integer; var I: Integer; Tmp: TValue; begin Result := -1; Tmp := -MaxDouble; for I := 0 to Length(Values)-1 do if Values[I] > Tmp then begin Tmp := Values[I]; Result := I; end; end; function MinValueIndex(const Values: TValueArray): Integer; var I: Integer; Tmp: TValue; begin Result := -1; Tmp := MaxDouble; for I := 0 to Length(Values)-1 do if Values[I] < Tmp then begin Tmp := Values[I]; Result := I; end; end; procedure GetMinMax(const Values: TValueArray; out MinValue, MaxValue: TValue); var I: Integer; begin MinValue := CMaxValue; MaxValue := CMinValue; for I := 0 to Length(Values)-1 do begin if Values[I] > MaxValue then MaxValue := Values[I]; if Values[I] < MinValue then MinValue := Values[I]; end; end; function AverageValue(const Values: TValueArray): Extended; var I: Integer; begin Result := 0; for I := 0 to Length(Values)-1 do Result := Result + Values[I]; Result := Result / Length(Values); end; procedure Variance(const X, Y: TValueArray; var SX, SY: TValueArray); var I: Integer; MinS, MaxS, AvgS, S: Extended; begin SX := X; SY := Y; MinS := MaxExtended; MaxS := -MinS; AvgS := 0; for I := 0 to Length(Y)-2 do begin S := Sqrt(Sqr(Y[I+1] - Y[I]) / 2); if S < MinS then MinS := S; if S > MaxS then MaxS := S; AvgS := AvgS + S; end; AvgS := AvgS / (Length(Y) - 1); //DebugPrint('MinS = %g; S = %g; MaxS = %g', [MinS, AvgS, MaxS]); end; procedure GetPartialBounds(const Values: TValueArray; const Limit1, Limit2: TValue; out Index1, Index2: Integer); var I: Integer; begin if Limit1 <> Limit2 then for I := 0 to Length(Values)-1 do begin if Values[I] < Limit1 then begin Index1 := I+1; Continue; end; if Values[I] > Limit2 then begin Index2 := I-1; Break; end; end else begin Index1 := 0; Index2 := Length(Values)-1; end; end; function CallPartialFunc(const ValuesX, ValuesY: TValueArray; const Limit1, Limit2: TValue; Func: TPartialFunc): TValue; var Index1, Index2: Integer; begin GetPartialBounds(ValuesX, Limit1, Limit2, Index1, Index2); Result := Func(ValuesY, Index1+1, Index2-1); end; function MeanAM(const Values: TValueArray): TValue; begin Result := MeanAMPart(Values, 0, Length(Values)-1); end; function MeanAM(const ValuesX, ValuesY: TValueArray; const Limit1, Limit2: TValue): TValue; begin Result := CallPartialFunc(ValuesX, ValuesY, Limit1, Limit2, @MeanAMPart); end; function MeanAMPart(const Values: TValueArray; Index1, Index2: Integer): TValue; var I: Integer; begin Result := 0; for I := Index1 to Index2 do Result := Result + Values[I]; Result := Result / (Index2 - Index1 + 1); end; procedure DespikePer(var Values: TValueArray; RangeMin, RangeMax: TValue); var I: Integer; V, Avg: Extended; BoundMin, BoundMax: Extended; Indexes: TIntegerList; begin BoundMin := 1 - RangeMin/100; BoundMax := 1 + RangeMax/100; Indexes := TIntegerList.Create; try for I := 0 to Length(Values)-1 do Indexes.Add(I); I := Random(Indexes.Count); Avg := Values[Indexes[I]]; Indexes.Delete(I); while Indexes.Count > 0 do begin I := Random(Indexes.Count); V := Values[Indexes[I]]; if (V < Avg * BoundMin) or (V > Avg * BoundMax) then Values[Indexes[I]] := Avg else Avg := (Avg + V) / 2; Indexes.Delete(I); end; finally Indexes.Free; end; end; procedure DespikeAbs(var Values: TValueArray; RangeMin, RangeMax: TValue); var I: Cardinal; V, Avg: Extended; Indexes: TIntegerList; begin Indexes := TIntegerList.Create; try for I := 0 to Length(Values)-1 do Indexes.Add(I); I := Random(Indexes.Count); Avg := Values[Indexes[I]]; Indexes.Delete(I); while Indexes.Count > 0 do begin I := Random(Indexes.Count); // We have to analize something only if average value is suited inside // the specified range, to avoid such erroneous situation when the range // is set to be laying lower or upper of graph's trend. if (Avg >= RangeMin) and (Avg <= RangeMax) then begin V := Values[Indexes[I]]; if (V < RangeMin) or (V > RangeMax) then Values[Indexes[I]] := Avg else Avg := (Avg + V) / 2; end; Indexes.Delete(I); end; finally Indexes.Free; end; end; procedure ReorderValues(var ValuesX, ValuesY: TValueArray); var I, L: Integer; Tmp: TValue; begin L := Length(ValuesX); for I := 0 to L div 2 do begin Tmp := ValuesX[I]; ValuesX[I] := ValuesX[L-I-1]; ValuesX[L-I-1] := Tmp; Tmp := ValuesY[I]; ValuesY[I] := ValuesY[L-I-1]; ValuesY[L-I-1] := Tmp; end; end; function FormulaExpression(const Formula: String): String; var Code, Line: String; P, Index: Integer; begin Code := Formula + ';'; Index := CharPos(Code, ';'); while Index > 0 do begin Line := Copy(Code, 1, Index-1); P := CharPos(Line, '='); if (P > 0) and (Trim(Copy(Line, 1, P-1)) = 'Y') then begin Result := Trim(Copy(Line, P+1, MaxInt)); Exit; end; Code := Copy(Code, Index+1, MaxInt); Index := CharPos(Code, ';'); end; Result := Formula; end; {procedure ParseFormula(const Formula: String; Calc: TStringCalc); var Code, Line, Name, S: String; Index, P: Integer; Value: Extended; fmt: TFormatSettings; begin fmt.DecimalSeparator := '.'; Code := Formula + ';'; Index := CharPos(Code, ';'); while Index > 0 do begin Line := Copy(Code, 1, Index-1); P := CharPos(Line, '='); if P > 0 then begin Name := Trim(Copy(Line, 1, P-1)); S := Trim(Copy(Line, P+1, MaxInt)); if Name <> 'Y' then begin if not TryStrToFloat(S, Value, fmt) then raise Exception.CreateFmt(Constant('ParamErr_WrongFloat'), [S]); Calc.SetConstant(Name, Value); end else Calc.Expression := S; end; Code := Copy(Code, Index+1, MaxInt); Index := CharPos(Code, ';'); end; end;} //function CheckFormula(const Formula: String): Boolean; //var // Calc: TStringCalc; //begin // Calc := TStringCalc.Create; // try // ParseFormula(Formula, Calc); // if Calc.Expression = '' then // raise Exception.Create(Constant('FormulaErr_EmptyY')); // Calc.AddVariable('X'); // Calc.Compile; // finally // Calc.Free; // end; // Result := True; //end; //procedure PlotFormula(Params: TFormulaParams; var ValuesX, ValuesY: TValueArray); //var // I, Count: Integer; // Y, X, Step: TValue; // Calc: TStringCalc; //begin // Calc := TStringCalc.Create; // try // ParseFormula(Params.Formula, Calc); // Calc.AddVariable('X'); // Calc.Compile; // // Params.Range.CalcStep(Count, Step); // SetLength(ValuesX, Count); // SetLength(ValuesY, Count); // X := Params.Range.Min; // for I := 0 to Count-1 do // begin // Calc.SetVariable('X', X); // Y := Calc.Calculate; // // ValuesX[I] := X; // ValuesY[I] := Y; // // X := X + Step; // end; // finally // Calc.Free; // end; //end; function CrossValues(const G1, G2: TGraphRec): TGraphRec2; var I, J, RI, L1, L2: Integer; V1, V2: TGraphRec; X, Y1, Y2: TValue; begin // первым графиком будет тот, который начинается "позже" if G1.X[0] >= G2.X[0] then begin V1 := G1; V2 := G2; end else begin V1 := G2; V2 := G1; end; L1 := Length(G1.X); L2 := Length(G2.X); SetLength(Result.X, L1+L2); SetLength(Result.Y1, L1+L2); SetLength(Result.Y2, L1+L2); // находим индекс, начиная с которого нужно учитывать второй график for I := 0 to Length(V2.X)-1 do if V2.X[I] > V1.X[0] then begin J := I; Break; end; I := 0; RI := 0; repeat X := V1.X[I]; Y1 := V1.Y[I]; Y2 := (V2.Y[J-1]*(V2.X[J] - X) + V2.Y[J]*(X - V2.X[J-1]))/(V2.X[J] - V2.X[J-1]); Result.X[RI] := X; Result.Y1[RI] := Y1; Result.Y2[RI] := Y2; Inc(RI); if I+1 < L1 then begin X := V2.X[J]; Y1 := (V1.Y[I]*(V1.X[I+1] - X) + V1.Y[I+1]*(X - V1.X[I]))/(V1.X[I+1] - V1.X[I]); Y2 := V2.Y[J]; Result.X[RI] := X; Result.Y1[RI] := Y1; Result.Y2[RI] := Y2; Inc(RI); end; Inc(I); Inc(J); until (J > L2-1) and (I > L1-1); SetLength(Result.X, RI); SetLength(Result.Y1, RI); SetLength(Result.Y2, RI); end; function GetPointCount(const Values: TValueArray; Min, Max: TValue): Integer; var I: Integer; begin Result := 0; for I := 0 to Length(Values)-1 do begin if Values[I] >= Min then Inc(Result); if Values[I] >= Max then Break; end; end; //procedure GetOverlapLimits(const Graphs: TGraphArray; out Min, Max: TValue); //var // I: Integer; //begin // Min := CMinValue; // Max := CMaxValue; // for I := 0 to Length(Graphs)-1 do // with Graphs[I] do // begin // if ValueX[0] > Min then Min := ValueX[0]; // if ValuesX[ValueCount-1] < Max then Max := ValuesX[ValueCount-1]; // end; //end; // В качестве первого (опорного) берется тот график, который плотнее (имеет // больше точек) на заданном промежутке. При использовании процедуры, этот график // следует рассматривать как "модифицируемый", т.е. его точки модифицуруются // соответствующими им значениями второго графика. // // Например используем так: имеем спектр содержащий много точек, и монотонно // возрастающую кривую с малым кол-вом точек (например, это результат формулы). // Нужно умножить спектр на кривую, чтобы "усилить" его правую часть. // При помощи CalcOverlapGraph находим "перекрытие" спектра и кривой. // В TGraphRec2.X и Y1 будут содержаться копии точек опорного графика (спектра) // из заданного промежутка (за исключением крайних точек, там будут интерополированные // значения, соответствующие пределам (Min и Max), если они не совпадают с точками // первого графика). TGraphRec2.Y2 будут значения Y второго графика, полученные // в результате интерполяции двух его точек, ближайших к соответствующей // точке первого графика. Т.е. точек второго графика как таковых в "перекрытии" // может и не содержаться, и форма кривой (X;Y2) будет отличаться от исходной // формы второго графика. Теперь для выполнени "усиления" достаточно пробежаться // по всем точкам "перекрытия" (TGraphRec2), и умножить Y1 на Y2. // // Все это имеет смысл только если графики имеют разную плотность на заданном // промежутке. Если же они построенны на одних и тех же значениях X, то "перекрытием" // будет просто хитро полученные копии участков каждого графика. Если известно, // что значения X графиков совпадают, то следует применить более простую процедуру. // // Подобным образом можно выполнить разные "модифицирующие" процедуры - произведение, // сумма, и т.п. Однако для таких процедур как "средняя линия" или "огибающая" // уже нельзя рассматривать только точки одного из графиков. В этих случаях // используется флаг AllPoint. Если он выставлен, то в "перекрытии" появляются // дополнительные точки - это точки второго графика, и соответствующие им // интерполированные значения первого графика. Теперь формы кривых (X;Y1) и (X;Y2) // будут совпадать с формами первого и второго графика, но в них будут дополнительные // точки. Их X-значения для первого графика соответствуют X-ам точек второго и наооборот. // Все это опять же имеет смысл только если исходные графики построены по разным наборам X. // function CalcOverlapGraph(const Gr1, Gr2: TGraphRec; AllPoints: Boolean; Min, Max: TValue): TGraphRec2; var I, J, I1, I2, RI, L1, L2: Integer; G1, G2: TGraphRec; function Interpolate(G: TGraphRec; X: TValue; I: Integer): TValue; inline; begin Result := (G.Y[I-1]*(G.X[I] - X) + G.Y[I]*(X - G.X[I-1]))/(G.X[I] - G.X[I-1]); end; begin RI := 0; L1 := Length(Gr1.X); L2 := Length(Gr2.X); // Если заданы слишком "обширные" пределы, то диапазон обработки будет // ограничиваться "концами" графиков - наибольшим минимумом и наименьшим максимумом. if (Min < Gr1.X[0]) or (Min < Gr2.X[0]) then Min := Math.Max(Gr1.X[0], Gr2.X[0]); if (Max > Gr1.X[L1-1]) or (Max > Gr2.X[L2-1]) then Max := Math.Min(Gr1.X[L1-1], Gr2.X[L2-1]); if Min > Max then Exit; // далее будет ошибка "слишком мало точек для построения" if GetPointCount(Gr1.X, Min, Max) >= GetPointCount(Gr2.X, Min, Max) then begin G1 := Gr1; G2 := Gr2; end else begin G1 := Gr2; G2 := Gr1; end; SetLength(Result.X, L1+L2); SetLength(Result.Y1, L1+L2); SetLength(Result.Y2, L1+L2); // Первый график - опорный, он содержит больше точек чем второй (или столько же). // Найдем индекс, начиная с которого нужно обрабатывать график. // Как минимум это будет вторая точка графика, I1 = 1 for I := 0 to L1-1 do if G1.X[I] > Min then begin I1 := I; Break; end; // Найдем точку на втором графике, перед которой находится текущий X (Min, в // данном случае). Она и ей предшествующая точка (I2-1), будут использоваться // для интерполяции значений второго графика. // Как минимум это будет вторая точка графика, I2 = 1 for I := 0 to L2-1 do if G2.X[I] > Min then begin I2 := I; // Если нужно, ищем интерполированную точку на первом графике, // соответствующую найденной точке на втором графике. N1) Точка I2 // может отстоять как угодно далеко от текущего X, т.е. перед ней // может находиться несколько непройденных точек опорного графика. Тогда // последовательность Resul.X может оказатья неупорядоченной и потом нужно // будет ее отсортировать. N2) Точка I2 может находиться в том числе и за Max, // если он задан явно в параметре процедуры, тогда ее добавлять не надо. // N3) Если I2 совпадает по X с одной из точек первого графика, то ее добавлять // не надо, т.к. это будет сделано в основном цикле. if AllPoints and (G2.X[I2] < Max) then for J := I1 to L1-1 do if G1.X[J] > G2.X[I2] then begin if G1.X[J-1] < G2.X[I2] then // N3) begin Result.X[RI] := G2.X[I2]; Result.Y2[RI] := G2.Y[I2]; Result.Y1[RI] := Interpolate(G1, G2.X[I2], J); Inc(RI); end; Break; end; Break; end; Result.X[RI] := Min; // Интерполированная точка на первом графике, которая соответствует минимальному X // Если граница точно совпадает с точкой графика, то интерполировать не нужно. if G1.X[I1-1] < Min then Result.Y1[RI] := Interpolate(G1, Min, I1) else Result.Y1[RI] := G1.Y[I1-1]; // Интерполированная точка на втором графике, которая соответствует минимальному X // Если граница точно совпадает с точкой графика, то интерполировать не нужно. if G2.X[I2-1] < Min then Result.Y2[RI] := Interpolate(G2, Min, I2) else Result.Y2[RI] := G2.Y[I2-1]; Inc(RI); // Обрабатываем все точки первого графика repeat // Если очередная точка первого графика оказалась дальше точки I2 второго // графика, то нужно найти новую точку I2, перед которой находится текущий X. if G1.X[I1] > G2.X[I2] then for I := I2 to L2-1 do if G2.X[I] > G1.X[I1] then begin I2 := I; if AllPoints and (G2.X[I2] < Max) then for J := I1 to L1-1 do if G1.X[J] > G2.X[I2] then begin if G1.X[J-1] < G2.X[I2] then // N3) begin Result.X[RI] := G2.X[I2]; Result.Y2[RI] := G2.Y[I2]; Result.Y1[RI] := Interpolate(G1, G2.X[I2], J); Inc(RI); end; Break; end; Break; end; Result.X[RI] := G1.X[I1]; Result.Y1[RI] := G1.Y[I1]; // Интерполированная точка на втором графике, которая соответствует заданному X // Если X точно совпадает с точкой графика, то интерполировать не нужно. if G2.X[I2-1] < G1.X[I1] then Result.Y2[RI] := Interpolate(G2, G1.X[I1], I2) else Result.Y2[RI] := G2.Y[I2-1]; Inc(I1); Inc(RI); until (I1 = L1) or (G1.X[I1] > Max); // Интерполированная точка на первом графике, которая соответствует максимальному X if (G1.X[I1] > Max) and (G1.X[I1-1] < Max) then begin Result.X[RI] := Max; Result.Y1[RI] := Interpolate(G1, Max, I1); // Интерполированная точка на втором графике, которая соответствует максимальному X // Если граница точно совпадает с точкой графика, то интерполировать не нужно. if G2.X[I2] > Max then Result.Y2[RI] := Interpolate(G2, Max, I2) else Result.Y2[RI] := G2.Y[I2]; Inc(RI); end; SetLength(Result.X, RI); SetLength(Result.Y1, RI); SetLength(Result.Y2, RI); if AllPoints then Sort(Result); end; procedure Regularity(const Values: TValueArray; var X, Y: TValueArray); var I: Integer; begin SetLength(X, Length(Values)-1); SetLength(Y, Length(Values)-1); for I := 0 to Length(Values)-2 do begin X[I] := I; Y[I] := Values[I+1] - Values[I]; end; end; procedure Sort(var ValuesX, ValuesY: TValueArray); var I, J: Integer; Tmp: TValue; begin for I := 0 to Length(ValuesX)-1 do for J := 0 to I-1 do if ValuesX[J] > ValuesX[J+1] then begin Tmp := ValuesX[J+1]; ValuesX[J+1] := ValuesX[J]; ValuesX[J] := Tmp; Tmp := ValuesY[J+1]; ValuesY[J+1] := ValuesY[J]; ValuesY[J] := Tmp; end; end; procedure Sort(var G: TGraphRec2); var I, J: Integer; Tmp: TValue; begin for I := 0 to Length(G.X)-1 do for J := 0 to I-1 do if G.X[J] > G.X[J+1] then begin Tmp := G.X[J+1]; G.X[J+1] := G.X[J]; G.X[J] := Tmp; Tmp := G.Y1[J+1]; G.Y1[J+1] := G.Y1[J]; G.Y1[J] := Tmp; Tmp := G.Y2[J+1]; G.Y2[J+1] := G.Y2[J]; G.Y2[J] := Tmp; end; end; //function GraphToRec(Graph: TGraph): TGraphRec; inline; //begin // Result.X := Graph.ValuesX; // Result.Y := Graph.ValuesY; //end; end.
unit uEditComandosSQL; interface uses Windows, Messages, SysUtils, StrUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Padrao1, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit, cxMemo, FMTBcd, DB, SqlExpr, Buttons, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, Provider, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, DbClient, Grids, DBGrids; type TfrmEditComandosSQL = class(TfrmPadrao1) Panel: TPanel; GroupBox1: TGroupBox; Memo1: TMemo; btnLimpar: TButton; btnFechar: TBitBtn; btnRun: TBitBtn; btnOcultTrigProc: TBitBtn; btnAbir: TBitBtn; OpenDialog1: TOpenDialog; DataSource1: TDataSource; DBGrid1: TDBGrid; Qry1: TSQLQuery; dsp1: TDataSetProvider; cds1: TClientDataSet; procedure FormShow(Sender: TObject); procedure btnLimparClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnRunClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnOcultTrigProcClick(Sender: TObject); procedure btnAbirClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private procedure ExecutaConsulta; { Private declarations } public { Public declarations } end; var frmEditComandosSQL: TfrmEditComandosSQL; implementation uses udmPrincipal, gsLib, UtilsDb; {$R *.dfm} procedure TfrmEditComandosSQL.btnAbirClick(Sender: TObject); Var slTexto: TStringList; begin if not OpenDialog1.Execute then exit; slTexto := TStringList.Create; slTexto.LoadFromFile(OpenDialog1.FileName); Memo1.Lines.Clear; Memo1.Text := slTexto.Text; end; procedure TfrmEditComandosSQL.btnLimparClick(Sender: TObject); begin Memo1.Lines.Clear; cds1.Close; Memo1.SetFocus; end; procedure TfrmEditComandosSQL.btnOcultTrigProcClick(Sender: TObject); Var iErro: Integer; dDtAtual: TDate; oQry1 : TSQLQuery; begin //slComandoSQL := TStringList.Create; Screen.Cursor := crHourGlass; iErro := 0; if not OcultaTriggers_e_procs then iErro := 1; Screen.Cursor := crDefault; if iErro = 0 then begin dDtAtual := StrToDate(LeftStr(DateToStr(Date),10)); oQry1 := TSQLQuery.Create(Self); oQry1.SQLConnection := dmPrincipal.SConPrincipal; oQry1.sql.Add('update config_sistema set dt_ver_db = :pDt where id = 1'); oQry1.Params[0].AsDate := dDtAtual; try oQry1.ExecSQL; finally FreeAndNil(oQry1); end; Mensagem('Operação realizada com sucesso ...', 'Aviso !!!',MB_OK+MB_ICONEXCLAMATION); end; end; procedure TfrmEditComandosSQL.btnRunClick(Sender: TObject); Var iErro, iConta: Integer; lConsulta: Boolean; begin //slComandoSQL := TStringList.Create; iErro := 0; if Memo1.Lines.Count = 0 then exit; lConsulta := False; iConta := 0; while iConta <= Memo1.Lines.Count - 1 do begin if (LeftStr(UpperCase(Memo1.Lines[iConta]),6) = 'CREATE') or (LeftStr(UpperCase(Memo1.Lines[iConta]),11) = 'ALTER TABLE') then begin lConsulta := False; break; end; if (Trim(Memo1.Lines[iConta]) <> '') and (Trim(Memo1.Lines[iConta]) <> '//') then begin if UpperCase(LeftStr(Trim(Memo1.Lines[iConta]),6)) = 'SELECT' then begin lConsulta := True; Break; end; end; Inc(iConta); end; if lConsulta then ExecutaConsulta else begin try dmPrincipal.SConPrincipal.ExecuteDirect(Memo1.Text); except on E: Exception do begin iErro := 1; Mensagem('Não foi possível executar essas instruções ...'+#13+ '('+E.Message+')', 'E R R O !!!',MB_OK+MB_ICONERROR); end; end; if iErro = 0 then Mensagem('Operação realizada com sucesso ...', 'Aviso !!!',MB_OK+MB_ICONEXCLAMATION); end; end; procedure TfrmEditComandosSQL.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Screen.Cursor := crHourGlass; dmPrincipal.SConPrincipal.Connected := False; dmPrincipal.SConPrincipal.Connected := True; Screen.Cursor := crDefault; end; procedure TfrmEditComandosSQL.FormCreate(Sender: TObject); begin inherited; Memo1.Lines.Clear; end; procedure TfrmEditComandosSQL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_F9:btnLimparClick(Self); end; end; procedure TfrmEditComandosSQL.FormShow(Sender: TObject); begin inherited; Memo1.SetFocus; end; procedure TfrmEditComandosSQL.ExecutaConsulta; Var iErro, iConta: integer; begin iErro := 0; cds1.Close; Qry1.SQL.Clear; for iConta := 0 to Memo1.Lines.Count - 1 do Qry1.SQL.Add(Memo1.Lines[iConta]); try cds1.Open; except on E: Exception do begin iErro := 1; Mensagem('Não foi possível executar essa Consulta ...'+#13+ '('+E.Message+')', 'E R R O !!!',MB_OK+MB_ICONERROR); end; end; if iErro = 0 then begin DBGrid1.SetFocus; end; { Mensagem('Operação realizada com sucesso ...', 'Aviso !!!',MB_OK+MB_ICONEXCLAMATION); } end; end.
unit f10_tambahjumlah; interface uses buku_handler, utilitas; { DEKLARASI FUNGSI DAN PROSEDUR } procedure tambah_jumlah(var data_buku: tabel_buku); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure tambah_jumlah(var data_buku: tabel_buku); { DESKRIPSI : prosedur untuk menambahkan jumlah buku yang sudah ada ke tabel buku } { PARAMETER : data buku } { KAMUS LOKAL } var id: string; where, banyak: integer; { ALGORITMA } begin write('Masukkan ID Buku: '); readln(id); write('Masukkan jumlah buku yang ditambahkan: '); readln(banyak); where := findID(data_buku, id); data_buku.t[where].jumlah_buku := IntToString(StringToInt(data_buku.t[where].jumlah_buku) + banyak); writeln('Pembaharuan jumlah buku berhasil dilakukan, total buku ', data_buku.t[where].judul_buku, ' di perpustakaan menjadi ', data_buku.t[where].jumlah_buku); end; end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Graphics, Controls, Forms, Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, Math, Contnrs, SynEditHighlighter, SynHighlighterPas, SynEdit, SynEditCodeFolding, uPSComponent, uPSDebugger, uPSRuntime, upsCompiler, uPSPreProcessor, ImgList, ToolWin, Menus, ActnList, StdActns, ShellApi, Clipbrd, System.Actions, Generics.Collections, System.UITypes, System.ImageList, Vcl.Grids, IOUtils, System.Classes; type TPointPair = class public X1: Double; Y1: Double; X2: Double; Y2: Double; Color: TColor; constructor Create(AX1, AY1, AX2, AY2: Double; AColor: TColor); end; TCircle = class public CX: Double; CY: Double; R: Integer; Color: TColor; constructor Create(ACX, ACY: Double; AR: Integer; AColor: TColor); end; TTextLabel = class public CX: Double; CY: Double; Text: String; Color: TColor; constructor Create(ACX, ACY: Double; AText: String; AColor: TColor); end; TMainForm = class(TForm) Toolbar: TToolBar; ConsoleMemo: TMemo; ColorShape: TShape; PaintBox: TPaintBox; CodeEditor: TSynEdit; StatusBar: TStatusBar; SynPasSyn: TSynPasSyn; WatchTable: TStringGrid; ActionList: TActionList; ColorDialog: TColorDialog; OpenFileDialog: TOpenDialog; PascalScript: TPSScriptDebugger; SaveAction: TAction; SaveAsAction: TAction; SaveBmpDialog: TSaveDialog; SaveFileDialog: TSaveDialog; ToolbarImages: TImageList; ToolbarImagesDisabled: TImageList; SpeedScrollBar: TScrollBar; LeftPanelWidthScrollBar: TScrollBar; SpeedLabel: TLabel; ColorLabel: TLabel; EditorWidthLabel: TLabel; TopPanel: TPanel; LeftPanel: TPanel; RightPanel: TPanel; BottomPanel: TPanel; CutMenuItem: TMenuItem; CopyMenuItem: TMenuItem; SaveMenuItem: TMenuItem; PasteMenuItem: TMenuItem; SaveAsMenuItem: TMenuItem; SaveFilePopup: TPopupMenu; CodeEditorPopup: TPopupMenu; RunButton: TToolButton; HelpButton: TToolButton; StopButton: TToolButton; NewFileButton: TToolButton; OpenFileButton: TToolButton; SaveFileButton: TToolButton; StepIntoButton: TToolButton; RealSizeButton: TToolButton; SettingsButton: TToolButton; ExportImageButton: TToolButton; ClearScreenButton: TToolButton; ToolbarSeparator1: TToolButton; ToolbarSeparator2: TToolButton; ToolbarSeparator3: TToolButton; StepOverButton: TToolButton; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure RightPanelResize(Sender: TObject); procedure LeftPanelWidthScrollBarChange(Sender: TObject); procedure NewFileButtonClick(Sender: TObject); procedure OpenFileButtonClick(Sender: TObject); procedure RunButtonClick(Sender: TObject); procedure StepIntoButtonClick(Sender: TObject); procedure StepOverButtonClick(Sender: TObject); procedure RealSizeButtonClick(Sender: TObject); procedure StopButtonClick(Sender: TObject); procedure ExportImageButtonClick(Sender: TObject); procedure ClearScreenButtonClick(Sender: TObject); procedure SettingsButtonClick(Sender: TObject); procedure HelpButtonClick(Sender: TObject); procedure ColorShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SaveActionExecute(Sender: TObject); procedure SaveAsActionExecute(Sender: TObject); procedure CodeEditorPopupPopup(Sender: TObject); procedure CutMenuItemClick(Sender: TObject); procedure CopyMenuItemClick(Sender: TObject); procedure PasteMenuItemClick(Sender: TObject); procedure WatchTableSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure WatchTableDblClick(Sender: TObject); procedure PaintBoxPaint(Sender: TObject); procedure PaintBoxMouseLeave(Sender: TObject); procedure PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure CodeEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CodeEditorGutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark); procedure CodeEditorSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor); /// <summary> /// Novi potprogram u Pascal Script dodajemo tako što ga prvo implementiramo ovde kod nas, pa /// ga baš u ovoj ovde metodi registrujemo prosleđujući pointer na njega i željeno zaglavlje. /// Po principu callback-a će ga Pascal Script zvati po potrebi. /// </summary> procedure PascalScriptCompile(Sender: TPSScript); procedure PascalScriptIdle(Sender: TObject); procedure PascalScriptAfterExecute(Sender: TPSScript); procedure PascalScriptBreakpoint(Sender: TObject; const FileName: AnsiString; Position, Row, Col: Cardinal); procedure PascalScriptLineInfo(Sender: TObject; const FileName: AnsiString; Position, Row, Col: Cardinal); /// <summary> /// Čita sadržaj fajla za potrebe <c>{$INCLUDE ...}</c> direktive. /// </summary> function PascalScriptNeedFile(Sender: TObject; const OrginFileName: AnsiString; var FileName, Output: AnsiString): Boolean; private { Private declarations } FGridWH: Integer; FActiveLine: Integer; FRealSize: Boolean; FCurrentFileName: String; FStack: TList<Integer>; // TStack nije pogodno za iteraciju, ne bih mogao lako da ispišem sve elemente steka FLines: TObjectList<TPointPair>; FCircles: TObjectList<TCircle>; FEllipses: TObjectList<TPointPair>; FTextLabels: TObjectList<TTextLabel>; /// <summary> /// <c>False</c> ako klik na Run označava početak izvršavanja algoritma. <c>True</c> ako označava /// nastavak normalnog izvršavanja nakon udara u breakpoint ili kliktanja na Step Over/Step Into. /// </summary> FResume: Boolean; /// <summary> /// Pascal Script koristi '.' kao decimalni separator. Funkcije za konverziju iz stringa u relan broj i obratno po /// defaultu koriste sitemska podešavanja, te vrednosti promenljivih neće biti ispravno fomatirane ako u sistemu /// nije postavljen baš taj separator. Zato ja podešavam i prosleđujem ovaj objekat svim tim funkcijama. /// </summary> FFormat: TFormatSettings; function Compile: Boolean; function Execute: Boolean; function FormatComplex(s: String): String; function PixelExists(X, Y: Integer): Boolean; function MixBytes(FG, BG, TRANS: Byte): Byte; function MixColors(FG, BG: TColor; T: Byte): TColor; /// <summary> /// Transformiše fiktivne u realne koordinate. U realnosti je piksel sa koordinatama (0, 0) uvek onaj u /// gornjem-levom uglu platna. Ali ako smo smestili koordinatni sistem u centar platna, nećemo misliti na /// ugaoni piksel dok budemo stavljali te koordinate jer bi on za nas tada bio na nekoj negativnoj poziciji. /// </summary> function OffsetCoordinate(X: Integer): Integer; overload; function OffsetCoordinate(X: Double): Double; overload; function UnoffsetCoordinate(X: Integer): Integer; procedure ClearScreen; procedure AdjustRightPanel; procedure WatchTableRefresh; procedure RefreshPaintBoxes; procedure CheckRange(Arr: Array of Integer); procedure SaveFile(FileName: String); procedure ToggleBreakPoint(Line: Integer); procedure SetCurrentFile(FileName: String); procedure ScrollToActiveLine(Row: Cardinal); procedure PutPixel(X, Y: Integer; Color: TColor); procedure RemovePixel(X, Y: Integer); // ** naši potprogrami ** // function MyFrac(X: Double): Double; function MyRandomRange(AFrom, ATo: Integer): Integer; procedure ReadInt(var X: Integer); procedure ReadFloat(var X: Double); function IsEmpty: Boolean; procedure Push(X: Integer); procedure Pop(var X: Integer); procedure Plot(X, Y: Integer); procedure PlotEx(X, Y, Alpha: Integer); procedure TurnOff(X, Y: Integer); procedure Invert(X, Y: Integer); function IsOn(X, Y: Integer): Boolean; procedure DrawLine(X1, Y1, X2, Y2: Double); procedure DrawCircle(CX, CY: Double; R: Integer); procedure DrawEllipse(X1, Y1, X2, Y2: Double); procedure DrawText(CX, CY: Double; Text: String); procedure SetColor(Color: String); procedure SetColorRGB(R, G, B: Byte); procedure WriteLn(Text: String); public { Public declarations } FCenterOrigin: Boolean; FPixelsPerQuadrantSide: Integer; /// <summary> /// "Matrica" piksela. Prava matrica bi zauzela dosta memorije, od koje bi većina u /// realnosti ostala neiskorišćena. Ovo pre svega važi ako je upaljen prikaz piksela /// u realnoj večini pošto bi u tom slučaju matrica bila velikih dimenzija. U rečniku /// zato čuvam samo obojene piksele. Elementi rečnika su oblika <c>{x: {y: color}}</c>. /// </summary> FPixels: TObjectDictionary<Integer, TDictionary<Integer, TColor>>; procedure ResizeGrid(Dimensions: Integer); procedure SetRealSize(RealSize: Boolean); procedure SetCenterOrigin(CenterOrigin: Boolean); end; const LINE_WIDTH = 1; BLANK_COLOR = clCream; AXIS_COLOR = clGreen; GRID_COLOR = clMoneyGreen; SLEEP_INTERVAL_DURATION = 20; INITIAL_PIXELS_PER_QUADRANT_SIDE = 20; WATCH_TABLE_VARIABLE_ROW = 1; WATCH_TABLE_VALUE_ROW = 2; HELP_FILE_NAME = 'MrPixel.pdf'; NEW_FILE_TEMPLATE_FILENAME = 'NewFileTemplate.txt'; var MainForm: TMainForm; implementation {$R *.dfm} uses RealSizeUnit, SettingsUnit, InspectVariableUnit; constructor TPointPair.Create(AX1, AY1, AX2, AY2: Double; AColor: TColor); begin X1 := AX1; Y1 := AY1; X2 := AX2; Y2 := AY2; Color := AColor; end; constructor TCircle.Create(ACX, ACY: Double; AR: Integer; AColor: TColor); begin CX := ACX; CY := ACY; R := AR; Color := AColor; end; constructor TTextLabel.Create(ACX, ACY: Double; AText: String; AColor: TColor); begin CX := ACX; CY := ACY; Text := AText; Color := AColor; end; procedure TMainForm.FormCreate(Sender: TObject); begin Randomize; FRealSize := False; FCenterOrigin := True; { TObjectList/TObjectDictionary je TList/TDictionary koji sam oslobađa memoriju posedovanih elemenata pri njihovom brisanju iz kolekcije, te mi ne moramo brinuti o tome. TObjectList u konstruktoru prima Boolean koji određuje da li je vlasnik svojih elemenata (default je True). Za TObjectDictionary doOwnsKeys znači da poseduje ključeve, a doOwnsValues da poseduje vrednosti (možemo navesti i oba). } FStack := TList<Integer>.Create; FLines := TObjectList<TPointPair>.Create; FCircles := TObjectList<TCircle>.Create; FEllipses := TObjectList<TPointPair>.Create; FTextLabels := TObjectList<TTextLabel>.Create; FPixels := TObjectDictionary < Integer, TDictionary < Integer, TColor >>.Create([doOwnsValues]); WatchTable.RowHeights[0] := 2; // pomoćni red za promenu veličine ćelija WatchTable.Cells[0, WATCH_TABLE_VARIABLE_ROW] := 'Variable'; WatchTable.Cells[0, WATCH_TABLE_VALUE_ROW] := 'Value'; FFormat := TFormatSettings.Create(''); FFormat.DecimalSeparator := '.'; RightPanel.DoubleBuffered := True; end; procedure TMainForm.FormShow(Sender: TObject); begin ResizeGrid(INITIAL_PIXELS_PER_QUADRANT_SIDE); NewFileButton.Click; CodeEditor.SetFocus; WriteLn(' by Branislav Stojković'); WriteLn(' & Nikola Kostić'); end; procedure TMainForm.FormResize(Sender: TObject); begin AdjustRightPanel; end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin { Pošto želim da ove prečice rade koja god da je komponenta u fokusu, upalio sam KeyPreview na formi. To znači da forma presreće sve događaje vezane za tastaturu. Ako sam u formi obradio događaj i ne želim da nakon toga bude prosleđen komponenti kojoj je bio namenjen, stavljam Key na #0 (KeyPress) ili 0 (KeyDown/KeyUp). } if Key = vk_F5 then begin RunButton.Click; Key := 0; end else if Key = vk_F6 then begin StepIntoButton.Click; Key := 0; end else if Key = vk_F7 then begin StepOverButton.Click; Key := 0; end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin StopButton.Click; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FStack.Free; FLines.Free; FCircles.Free; FEllipses.Free; FTextLabels.Free; FPixels.Free; end; procedure TMainForm.RightPanelResize(Sender: TObject); begin { Ako nije upaljen prikaz u realnoj veličini, broj piksela u mreži zavisi samo od podešavanja. Jasno je da u suprotnom važi da su dimenzije mreže jednake dimenzijama platna. Zato u tom slučaju pri svakoj promeni dimenzija brišem sve sa platna. } if FRealSize then ClearScreen; end; procedure TMainForm.LeftPanelWidthScrollBarChange(Sender: TObject); begin AdjustRightPanel; end; procedure TMainForm.NewFileButtonClick(Sender: TObject); var Code: String; begin Code := ''; SetCurrentFile(''); if FileExists(NEW_FILE_TEMPLATE_FILENAME) then Code := TFile.ReadAllText(NEW_FILE_TEMPLATE_FILENAME) else WriteLn(NEW_FILE_TEMPLATE_FILENAME + ' is missing.'); CodeEditor.Text := Code; end; procedure TMainForm.OpenFileButtonClick(Sender: TObject); begin if OpenFileDialog.Execute then begin SetCurrentFile(OpenFileDialog.FileName); CodeEditor.Lines.LoadFromFile(OpenFileDialog.FileName); end; end; procedure TMainForm.RunButtonClick(Sender: TObject); begin if PascalScript.Running then FResume := True else if Compile then Execute; end; procedure TMainForm.StepIntoButtonClick(Sender: TObject); begin if PascalScript.Exec.Status = isRunning then PascalScript.StepInto else begin if Compile then begin PascalScript.StepInto; Execute; end; end; end; procedure TMainForm.StepOverButtonClick(Sender: TObject); begin if PascalScript.Exec.Status = isRunning then PascalScript.StepOver else begin if Compile then begin PascalScript.StepOver; Execute; end; end; end; procedure TMainForm.RealSizeButtonClick(Sender: TObject); begin RealSizeForm.Visible := not RealSizeForm.Visible; end; procedure TMainForm.StopButtonClick(Sender: TObject); begin if PascalScript.Exec.Status = isRunning then PascalScript.Stop; end; procedure TMainForm.ExportImageButtonClick(Sender: TObject); var bmp: TBitmap; begin if SaveBmpDialog.Execute then begin bmp := TBitmap.Create; try bmp.Width := PaintBox.Width; bmp.Height := PaintBox.Height; PaintBox.Refresh; BitBlt(bmp.Canvas.Handle, 0, 0, bmp.Width, bmp.Height, PaintBox.Canvas.Handle, 0, 0, SRCCOPY); bmp.SaveToFile(SaveBmpDialog.FileName); finally bmp.Free end end; end; procedure TMainForm.ClearScreenButtonClick(Sender: TObject); begin ClearScreen; end; procedure TMainForm.SettingsButtonClick(Sender: TObject); begin SettingsForm.ShowModal; end; procedure TMainForm.HelpButtonClick(Sender: TObject); var Folder: String; FilePath: String; SEI: TShellExecuteInfo; begin Folder := ExtractFilePath(Application.ExeName); FilePath := TPath.Combine(Folder, HELP_FILE_NAME); if FileExists(FilePath) then begin ZeroMemory(@SEI, SizeOf(SEI)); SEI.cbSize := SizeOf(SEI); SEI.lpDirectory := PChar(Folder); SEI.lpFile := PChar(FilePath); SEI.nShow := SW_SHOWNORMAL; ShellExecuteEx(@SEI); end else WriteLn('Help file is missing.'); end; procedure TMainForm.ColorShapeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbRight then ColorShape.Brush.Color := RGB(Random(255), Random(255), Random(255)) else begin ColorDialog.Color := ColorShape.Brush.Color; if ColorDialog.Execute then ColorShape.Brush.Color := ColorDialog.Color; end; end; procedure TMainForm.SaveActionExecute(Sender: TObject); begin if FCurrentFileName <> '' then SaveFile(FCurrentFileName) else SaveAsAction.Execute; end; procedure TMainForm.SaveAsActionExecute(Sender: TObject); begin if SaveFileDialog.Execute then begin SaveFile(SaveFileDialog.FileName); SetCurrentFile(SaveFileDialog.FileName); end; end; procedure TMainForm.CodeEditorPopupPopup(Sender: TObject); begin CutMenuItem.Enabled := CodeEditor.SelLength > 0; CopyMenuItem.Enabled := CodeEditor.SelLength > 0; PasteMenuItem.Enabled := Clipboard.HasFormat(CF_TEXT); end; procedure TMainForm.CutMenuItemClick(Sender: TObject); begin CodeEditor.CutToClipboard; end; procedure TMainForm.CopyMenuItemClick(Sender: TObject); begin CodeEditor.CopyToClipboard; end; procedure TMainForm.PasteMenuItemClick(Sender: TObject); begin CodeEditor.PasteFromClipboard; end; procedure TMainForm.WatchTableSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); var VarName: String; begin if ARow = 1 then begin VarName := WatchTable.Cells[ACol, ARow]; if VarName = '' then WatchTable.Cells[ACol, WATCH_TABLE_VALUE_ROW] := '' else WatchTableRefresh; end; end; procedure TMainForm.WatchTableRefresh; var D: Double; I: Integer; N: Integer; Col: Integer; VarName: String; VarValue: String; FormattedVarValue: String; begin if PascalScript.Exec.Status = isRunning then for Col := 1 to WatchTable.ColCount do begin VarName := WatchTable.Cells[Col, WATCH_TABLE_VARIABLE_ROW]; if VarName = '' then Continue; if CompareText(VarName, '<stack>') = 0 then begin FormattedVarValue := '['; for I := FStack.Count - 1 downto 0 do begin FormattedVarValue := FormattedVarValue + IntToStr(FStack.Items[I]); if I > 0 then FormattedVarValue := FormattedVarValue + ', '; end; FormattedVarValue := FormattedVarValue + ']'; end else begin VarValue := String(PascalScript.GetVarContents(AnsiString(VarName))); FormattedVarValue := VarValue; if TryStrToInt(VarValue, N) then FormattedVarValue := IntToStr(N) else if TryStrToFloat(VarValue, D, FFormat) then FormattedVarValue := FloatToStr(D, FFormat) else if ((Pos('[', VarValue) > 0) or (Pos('(', VarValue) > 0)) then FormattedVarValue := FormatComplex(VarValue); end; WatchTable.Cells[Col, WATCH_TABLE_VALUE_ROW] := FormattedVarValue; end; end; procedure TMainForm.WatchTableDblClick(Sender: TObject); var ACol: Integer; ARow: Integer; CursorPos: TPoint; CellContent: String; begin GetCursorPos(CursorPos); CursorPos := WatchTable.ScreenToClient(CursorPos); WatchTable.MouseToCell(CursorPos.X, CursorPos.Y, ACol, ARow); if ((ACol > 0) and (ARow = WATCH_TABLE_VALUE_ROW)) then begin CellContent := WatchTable.Cells[ACol, WATCH_TABLE_VALUE_ROW]; if CellContent <> '' then begin InspectVariableForm.Caption := WatchTable.Cells[ACol, WATCH_TABLE_VARIABLE_ROW]; InspectVariableForm.VariableValueMemo.Text := CellContent; InspectVariableForm.ShowModal; end; end; end; procedure TMainForm.PaintBoxPaint(Sender: TObject); var I: Integer; GridR: Integer; GridC: Integer; PixelX: Integer; PixelY: Integer; TextWidth: Integer; TextHeight: Integer; Multiplier: Integer; HalfPaintBox: Integer; InnerItem: TPair<Integer, TColor>; OuterItem: TPair<Integer, TDictionary<Integer, TColor>>; begin // ** clearing canvas ** // PaintBox.Canvas.Pen.Style := psClear; PaintBox.Canvas.Brush.Color := BLANK_COLOR; PaintBox.Canvas.Rectangle(0, 0, PaintBox.Width, PaintBox.Height); PaintBox.Canvas.Pen.Style := psSolid; // ** filling pixels ** // for OuterItem in FPixels do for InnerItem in OuterItem.Value do begin PixelX := OffsetCoordinate(OuterItem.Key); PixelY := OffsetCoordinate(InnerItem.Key); if FRealSize then PaintBox.Canvas.Pixels[PixelX, PixelY] := InnerItem.Value else begin PaintBox.Canvas.Brush.Color := InnerItem.Value; PaintBox.Canvas.Rectangle( PixelX * FGridWH, PixelY * FGridWH, (PixelX + 1) * FGridWH + LINE_WIDTH, (PixelY + 1) * FGridWH + LINE_WIDTH ); end; end; if not FRealSize then begin // ** drawing grid ** // PaintBox.Canvas.Pen.Width := LINE_WIDTH; PaintBox.Canvas.Pen.Color := GRID_COLOR; for GridR := 1 to 2 * FPixelsPerQuadrantSide do begin PaintBox.Canvas.MoveTo(0, GridR * FGridWH); PaintBox.Canvas.LineTo(PaintBox.Width, GridR * FGridWH); end; for GridC := 1 to 2 * FPixelsPerQuadrantSide do begin PaintBox.Canvas.MoveTo(GridC * FGridWH, 0); PaintBox.Canvas.LineTo(GridC * FGridWH, PaintBox.Height); end; end; // ** drawing arrows ** // if FCenterOrigin then begin PaintBox.Canvas.Pen.Color := AXIS_COLOR; HalfPaintBox := (PaintBox.Width - IfThen(FRealSize, 0, FGridWH)) div 2; // ** vertical arrow ** // PaintBox.Canvas.MoveTo(HalfPaintBox, 0); PaintBox.Canvas.LineTo(HalfPaintBox, PaintBox.Height); PaintBox.Canvas.LineTo(HalfPaintBox - 7, PaintBox.Height - 9); PaintBox.Canvas.MoveTo(HalfPaintBox, PaintBox.Height); PaintBox.Canvas.LineTo(HalfPaintBox + 7, PaintBox.Height - 9); // ** horizontal arrow ** // PaintBox.Canvas.MoveTo(0, HalfPaintBox); PaintBox.Canvas.LineTo(PaintBox.Width, HalfPaintBox); PaintBox.Canvas.LineTo(PaintBox.Width - 9, HalfPaintBox - 7); PaintBox.Canvas.MoveTo(PaintBox.Width, HalfPaintBox); PaintBox.Canvas.LineTo(PaintBox.Width - 9, HalfPaintBox + 7); end; // ** drawing shapes ** // Multiplier := IfThen(FRealSize, 1, FGridWH); PaintBox.Canvas.Pen.Width := LINE_WIDTH; for I := 0 to FCircles.Count - 1 do with FCircles.Items[I] do begin CX := OffsetCoordinate(CX); CY := OffsetCoordinate(CY); PaintBox.Canvas.Pen.Color := Color; PaintBox.Canvas.Brush.Color := Color; PaintBox.Canvas.Ellipse( Round(CX * Multiplier) - R, Round(CY * Multiplier) - R, Round(CX * Multiplier) + R, Round(CY * Multiplier) + R ); end; PaintBox.Canvas.Brush.Style := bsClear; for I := 0 to FEllipses.Count - 1 do with FEllipses.Items[I] do begin PaintBox.Canvas.Pen.Color := Color; PaintBox.Canvas.Ellipse( Round(OffsetCoordinate(X1) * Multiplier), Round(OffsetCoordinate(Y1) * Multiplier), Round(OffsetCoordinate(X2) * Multiplier), Round(OffsetCoordinate(Y2) * Multiplier) ); end; for I := 0 to FLines.Count - 1 do with FLines.Items[I] do begin PaintBox.Canvas.Pen.Color := Color; PaintBox.Canvas.MoveTo(Round(OffsetCoordinate(X1) * Multiplier), Round(OffsetCoordinate(Y1) * Multiplier)); PaintBox.Canvas.LineTo(Round(OffsetCoordinate(X2) * Multiplier), Round(OffsetCoordinate(Y2) * Multiplier)); end; for I := 0 to FTextLabels.Count - 1 do with FTextLabels.Items[I] do begin PaintBox.Canvas.Font.Color := Color; TextWidth := PaintBox.Canvas.TextWidth(Text); TextHeight := PaintBox.Canvas.TextHeight(Text); PaintBox.Canvas.TextOut( Round(OffsetCoordinate(CX) * Multiplier - TextWidth div 2), Round(OffsetCoordinate(CY) * Multiplier - TextHeight div 2), Text ); end; end; procedure TMainForm.PaintBoxMouseLeave(Sender: TObject); begin StatusBar.SimpleText := ''; end; procedure TMainForm.PaintBoxMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var C: Integer; R: Integer; begin C := UnoffsetCoordinate(IfThen(FRealSize, X, X div FGridWH)); R := UnoffsetCoordinate(IfThen(FRealSize, Y, Y div FGridWH)); StatusBar.SimpleText := '(' + IntToStr(C) + ', ' + IntToStr(R) + ')'; end; procedure TMainForm.CodeEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = vk_F8 then ToggleBreakPoint(CodeEditor.CaretY); end; procedure TMainForm.CodeEditorGutterClick(Sender: TObject; Button: TMouseButton; X, Y, Line: Integer; Mark: TSynEditMark); begin ToggleBreakPoint(Line); end; procedure TMainForm.ToggleBreakPoint(Line: Integer); begin if PascalScript.HasBreakPoint(PascalScript.MainFileName, Line) then PascalScript.ClearBreakPoint(PascalScript.MainFileName, Line) else PascalScript.SetBreakPoint(PascalScript.MainFileName, Line); CodeEditor.Refresh; end; procedure TMainForm.CodeEditorSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor); begin if PascalScript.HasBreakPoint(PascalScript.MainFileName, Line) then begin Special := True; if Line = FActiveLine then begin FG := clWhite; BG := clPurple; end else begin FG := clWhite; BG := clRed; end; end else if Line = FActiveLine then begin Special := True; FG := clWhite; BG := clBlue; end else Special := False; end; procedure TMainForm.PascalScriptCompile(Sender: TPSScript); begin PascalScript.AddMethod(Self, @TMainForm.MyFrac, 'function Frac(X: Double): Double;'); PascalScript.AddMethod(Self, @TMainForm.MyRandomRange, 'function RandomRange(AFrom, ATo: Integer): Integer;'); PascalScript.AddMethod(Self, @TMainForm.ReadInt, 'procedure ReadInt(var X: Integer);'); PascalScript.AddMethod(Self, @TMainForm.ReadFloat, 'procedure ReadFloat(var X: Double);'); PascalScript.AddMethod(Self, @TMainForm.IsEmpty, 'function IsEmpty: Boolean;'); PascalScript.AddMethod(Self, @TMainForm.Push, 'procedure Push(X: Integer);'); PascalScript.AddMethod(Self, @TMainForm.Pop, 'procedure Pop(var X: Integer);'); PascalScript.AddMethod(Self, @TMainForm.Plot, 'procedure Plot(X, Y: Integer);'); PascalScript.AddMethod(Self, @TMainForm.PlotEx, 'procedure PlotEx(X, Y, Alpha: Integer)'); PascalScript.AddMethod(Self, @TMainForm.TurnOff, 'procedure TurnOff(X, Y: Integer);'); PascalScript.AddMethod(Self, @TMainForm.Invert, 'procedure Invert(X, Y: Integer);'); PascalScript.AddMethod(Self, @TMainForm.IsOn, 'function IsOn(X, Y: Integer): Boolean;'); PascalScript.AddMethod(Self, @TMainForm.DrawLine, 'procedure DrawLine(X1, Y1, X2, Y2: Double);'); PascalScript.AddMethod(Self, @TMainForm.DrawCircle, 'procedure DrawCircle(CX, CY: Double; R: Integer);'); PascalScript.AddMethod(Self, @TMainForm.DrawEllipse, 'procedure DrawEllipse(X1, Y1, X2, Y2: Double);'); PascalScript.AddMethod(Self, @TMainForm.DrawText, 'procedure DrawText(CX, CY: Double; Text: String);'); PascalScript.AddMethod(Self, @TMainForm.SetColor, 'procedure SetColor(Color: String);'); PascalScript.AddMethod(Self, @TMainForm.SetColorRGB, 'procedure SetColorRGB(R, G, B: Byte);'); PascalScript.AddMethod(Self, @TMainForm.WriteLn, 'procedure WriteLn(Text: String);'); end; procedure TMainForm.PascalScriptIdle(Sender: TObject); begin Application.HandleMessage; if FResume then begin FResume := False; PascalScript.Resume; FActiveLine := 0; CodeEditor.Refresh; end; end; procedure TMainForm.PascalScriptAfterExecute(Sender: TPSScript); begin FActiveLine := 0; CodeEditor.Refresh; end; procedure TMainForm.PascalScriptBreakpoint(Sender: TObject; const FileName: AnsiString; Position, Row, Col: Cardinal); begin ScrollToActiveLine(Row); end; procedure TMainForm.PascalScriptLineInfo(Sender: TObject; const FileName: AnsiString; Position, Row, Col: Cardinal); begin if ((PascalScript.Exec.DebugMode <> dmRun) and (FileName = '')) then ScrollToActiveLine(Row); end; function TMainForm.PascalScriptNeedFile(Sender: TObject; const OrginFileName: AnsiString; var FileName, Output: AnsiString): Boolean; var FilePath: String; begin FilePath := TPath.Combine(ExtractFilePath(Application.ExeName), String(FileName)); if FileExists(FilePath) then begin Result := True; Output := AnsiString(TFile.ReadAllText(FilePath)); end else Result := False; end; { ============================================= = Functions = ============================================= } function TMainForm.Compile: Boolean; var I: LongInt; CompilerErrors: String; CompilerMessage: TPSPascalCompilerMessage; begin ConsoleMemo.Clear; FStack.Clear; PascalScript.Script.Assign(CodeEditor.Lines); Result := PascalScript.Compile; CompilerErrors := ''; for I := 0 to PascalScript.CompilerMessageCount - 1 do begin CompilerMessage := PascalScript.CompilerMessages[I]; if CompilerMessage.ClassType = TPSPascalCompilerError then CompilerErrors := CompilerErrors + String(CompilerMessage.MessageToString) + #13 else WriteLn(String(CompilerMessage.MessageToString)); end; if not Result then MessageDlg(CompilerErrors, mtError, [mbOK], 0); end; function TMainForm.Execute: Boolean; var Msg: AnsiString; begin if PascalScript.Execute then Result := True else begin if PascalScript.ExecErrorParam <> '' then Msg := PascalScript.ExecErrorParam else Msg := PascalScript.ExecErrorToString; MessageDlg('[Exception] (' + IntToStr(PascalScript.ExecErrorRow) + ':' + IntToStr(PascalScript.ExecErrorCol) + '): ' + String(Msg), mtError, [mbOK], 0); Result := False; end; end; function TMainForm.FormatComplex(s: String): String; var I: Integer; FlPtNum: String; begin // sample input string // '[ 0.00000000000000E+0000, 0.00000000000000E+0000, 0.00000000000000E+0000]' I := 1; Result := ''; while I <= Length(s) do begin while (not CharInSet(s[I], ['0' .. '9', '.', 'E', '-', '+'])) and (I <= Length(s)) do begin Result := Result + s[I]; Inc(I); end; FlPtNum := ''; while CharInSet(s[I], ['0' .. '9', '.', 'E', '-', '+']) and (I <= Length(s)) do begin FlPtNum := FlPtNum + s[I]; Inc(I); end; if FlPtNum <> '' then Result := Result + FloatToStr(StrToFloat(FlPtNum, FFormat), FFormat); end; end; function TMainForm.PixelExists(X: Integer; Y: Integer): Boolean; begin Result := False; if FPixels.ContainsKey(X) then if FPixels.Items[X].ContainsKey(Y) then Result := True; end; function TMainForm.MixBytes(FG, BG, TRANS: Byte): Byte; asm push bx push cx push dx mov DH, TRANS mov BL, FG mov AL, DH mov CL, BG xor AH, AH xor BH, BH xor CH, CH mul BL mov BX, AX xor AH, AH mov AL, DH xor AL, $FF mul CL add AX, BX shr AX, 8 pop dx pop cx pop bx end; function TMainForm.MixColors(FG, BG: TColor; T: Byte): TColor; var R, G, B: Byte; begin R := MixBytes(FG and 255, BG and 255, T); G := MixBytes((FG shr 8) and 255, (BG shr 8) and 255, T); B := MixBytes((FG shr 16) and 255, (BG shr 16) and 255, T); Result := R + G * 256 + B * 65536; end; function TMainForm.OffsetCoordinate(X: Integer): Integer; var Offset: Integer; begin Offset := IfThen(FRealSize, PaintBox.Width div 2, FPixelsPerQuadrantSide); Result := IfThen(FCenterOrigin, X + Offset, X); end; function TMainForm.OffsetCoordinate(X: Double): Double; var Offset: Integer; begin Offset := IfThen(FRealSize, PaintBox.Width div 2, FPixelsPerQuadrantSide); Result := IfThen(FCenterOrigin, X + Offset, X); end; function TMainForm.UnoffsetCoordinate(X: Integer): Integer; var Offset: Integer; begin Offset := IfThen(FRealSize, PaintBox.Width div 2, FPixelsPerQuadrantSide); Result := IfThen(FCenterOrigin, X - Offset, X); end; { ============================================= = Procedures = ============================================= } procedure TMainForm.ClearScreen; begin FLines.Clear; FCircles.Clear; FEllipses.Clear; FTextLabels.Clear; FPixels.Clear; StopButton.Click; MainForm.PaintBox.Refresh; RealSizeForm.RealSizePaintBox.Refresh; end; procedure TMainForm.AdjustRightPanel; var RightPanelWidth: Integer; PotentialLeftPanelWidth: Integer; PotentialRightPanelWidth: Integer; begin PotentialLeftPanelWidth := (ClientWidth * LeftPanelWidthScrollBar.Position) div LeftPanelWidthScrollBar.Max; PotentialRightPanelWidth := ClientWidth - PotentialLeftPanelWidth; RightPanelWidth := Min(PotentialRightPanelWidth, RightPanel.Height); // get a number that's divisible with 2 * FPixelsPerQuadrantSide + 1 RightPanelWidth := RightPanelWidth - RightPanelWidth mod (2 * FPixelsPerQuadrantSide + 1); // add a couple of extra pixels for the last line RightPanelWidth := RightPanelWidth + LINE_WIDTH; LeftPanel.Width := ClientWidth - RightPanelWidth; RightPanel.Width := RightPanelWidth; RightPanel.Left := LeftPanel.Width; PaintBox.Width := RightPanelWidth; PaintBox.Height := RightPanelWidth; FGridWH := RightPanelWidth div (2 * FPixelsPerQuadrantSide + 1); end; procedure TMainForm.RefreshPaintBoxes; var I: Integer; NumberOfIntervals: Integer; begin with MainForm do begin PaintBox.Refresh; RealSizeForm.RealSizePaintBox.Refresh; { Da bi aplikacija mogla da obrađuje događaje i kako se ne bi zamrzla, vreme za spavanje delimo na kraće intervale i nakon svakog tražimo obradu poruka. } NumberOfIntervals := (SpeedScrollBar.Max - SpeedScrollBar.Position) div SLEEP_INTERVAL_DURATION; if NumberOfIntervals = 0 then begin Sleep(1); Application.ProcessMessages; end else for I := 1 to NumberOfIntervals do begin Sleep(SLEEP_INTERVAL_DURATION); Application.ProcessMessages; end; end; end; procedure TMainForm.CheckRange(Arr: Array of Integer); var A: Integer; MinC: Integer; MaxC: Integer; begin for A in Arr do begin if FCenterOrigin then begin MaxC := IfThen(FRealSize, (PaintBox.Width - FGridWH) div 2, FPixelsPerQuadrantSide); MinC := -MaxC; end else begin MinC := 0; MaxC := IfThen(FRealSize, PaintBox.Width, FPixelsPerQuadrantSide); end; if not((A >= MinC) and (A <= MaxC)) then raise ERangeError.Create(FloatToStr(A, FFormat) + ' is out of range'); end; end; procedure TMainForm.SaveFile(FileName: String); var StringList: TStrings; begin StringList := TStringList.Create; try StringList.Text := CodeEditor.Text; StringList.SaveToFile(FileName); finally StringList.Free; end; end; procedure TMainForm.SetRealSize(RealSize: Boolean); var OldRealSize: Boolean; begin OldRealSize := FRealSize; FRealSize := RealSize; if OldRealSize <> FRealSize then ClearScreen; if FRealSize then RealSizeForm.Close; RealSizeButton.Enabled := not FRealSize; end; procedure TMainForm.SetCenterOrigin(CenterOrigin: Boolean); var OldCenterOrigin: Boolean; begin OldCenterOrigin := FCenterOrigin; FCenterOrigin := CenterOrigin; if OldCenterOrigin <> FCenterOrigin then ClearScreen; end; procedure TMainForm.SetCurrentFile(FileName: String); begin FCurrentFileName := FileName; Self.Caption := Application.Title; if FileName <> '' then Self.Caption := Self.Caption + ' - ' + FileName; PascalScript.ClearBreakPoints; ClearScreen; end; procedure TMainForm.ResizeGrid(Dimensions: Integer); begin FPixelsPerQuadrantSide := Dimensions; if RealSizeForm <> nil then begin RealSizeForm.ClientWidth := 2 * FPixelsPerQuadrantSide; RealSizeForm.ClientHeight := 2 * FPixelsPerQuadrantSide; end; ClearScreen; AdjustRightPanel; end; procedure TMainForm.ScrollToActiveLine(Row: Cardinal); begin FActiveLine := Row; CodeEditor.CaretX := 1; CodeEditor.CaretY := FActiveLine; if (FActiveLine < CodeEditor.TopLine + 2) or (FActiveLine > CodeEditor.TopLine + CodeEditor.LinesInWindow - 2) then CodeEditor.TopLine := FActiveLine - (CodeEditor.LinesInWindow div 2); WatchTableRefresh; CodeEditor.Refresh; end; procedure TMainForm.PutPixel(X, Y: Integer; Color: TColor); begin if not FPixels.ContainsKey(X) then FPixels.Add(X, TDictionary<Integer, TColor>.Create); FPixels.Items[X].AddOrSetValue(Y, Color); end; procedure TMainForm.RemovePixel(X: Integer; Y: Integer); begin if PixelExists(X, Y) then begin FPixels.Items[X].Remove(Y); if FPixels.Items[X].Count = 0 then FPixels.Remove(X); end; end; { ============================================= = Pascal Script Functions = ============================================= } function TMainForm.MyFrac(X: Double): Double; begin Result := Frac(X); end; function TMainForm.MyRandomRange(AFrom, ATo: Integer): Integer; begin Result := RandomRange(AFrom, ATo); end; procedure TMainForm.ReadInt(var X: Integer); var S: String; begin if InputQuery('[Pascal Script]', 'Enter integer value:', s) then if not TryStrToInt(s, X) then if MessageDlg('Input error, integer value is expected!', mtError, [mbOK, mbCancel], 0) = mrOK then Read(X) else PascalScript.Stop; end; procedure TMainForm.ReadFloat(var X: Double); var S: String; begin if InputQuery('[Pascal Script]', 'Enter floating point value:', S) then if not TryStrToFloat(S, X, FFormat) then if MessageDlg('Input error, floating point value is expected!', mtError, [mbOK, mbCancel], 0) = mrOK then Read(X) else PascalScript.Stop; end; function TMainForm.IsEmpty: Boolean; begin Result := FStack.Count = 0; end; procedure TMainForm.Push(X: Integer); begin FStack.Add(X); end; procedure TMainForm.Pop(var X: Integer); begin if FStack.Count > 0 then begin X := FStack.Last; FStack.Delete(FStack.Count - 1); end else raise EListError.Create('Stack is empty'); end; procedure TMainForm.Plot(X, Y: Integer); var Color: Integer; begin CheckRange([X, Y]); Color := ColorShape.Brush.Color; if Color <> BLANK_COLOR then PutPixel(X, Y, Color) else RemovePixel(X, Y); RefreshPaintBoxes; end; procedure TMainForm.PlotEx(X, Y, Alpha: Integer); begin CheckRange([X, Y]); PutPixel(X, Y, MixColors(ColorShape.Brush.Color, BLANK_COLOR, Alpha)); RefreshPaintBoxes; end; procedure TMainForm.TurnOff(X, Y: Integer); begin CheckRange([X, Y]); RemovePixel(X, Y); RefreshPaintBoxes; end; procedure TMainForm.Invert(X, Y: Integer); begin CheckRange([X, Y]); if PixelExists(X, Y) then RemovePixel(X, Y) else PutPixel(X, Y, ColorShape.Brush.Color); RefreshPaintBoxes; end; function TMainForm.IsOn(X, Y: Integer): Boolean; begin CheckRange([X, Y]); Result := PixelExists(X, Y); end; procedure TMainForm.DrawLine(X1, Y1, X2, Y2: Double); begin CheckRange([Round(X1), Round(Y1), Round(X2), Round(Y2)]); FLines.Add(TPointPair.Create(X1, Y1, X2, Y2, ColorShape.Brush.Color)); PaintBox.Refresh; end; procedure TMainForm.DrawCircle(CX, CY: Double; R: Integer); begin CheckRange([Round(CX),Round(CY)]); FCircles.Add(TCircle.Create(CX, CY, R, ColorShape.Brush.Color)); MainForm.PaintBox.Refresh; end; procedure TMainForm.DrawEllipse(X1, Y1, X2, Y2: Double); begin CheckRange([Round(X1), Round(Y1), Round(X2), Round(Y2)]); FEllipses.Add(TPointPair.Create(X1, Y1, X2, Y2, ColorShape.Brush.Color)); MainForm.PaintBox.Refresh; end; procedure TMainForm.DrawText(CX, CY: Double; Text: String); begin CheckRange([Round(CX),Round(CY)]); FTextLabels.Add(TTextLabel.Create(CX, CY, Text, ColorShape.Brush.Color)); MainForm.PaintBox.Refresh; end; procedure TMainForm.SetColor(Color: String); begin ColorShape.Brush.Color := StringToColor(Color); end; procedure TMainForm.SetColorRGB(R, G, B: Byte); begin ColorShape.Brush.Color := RGB(R, G, B); end; procedure TMainForm.WriteLn(Text: String); begin ConsoleMemo.Lines.Append(Text); ConsoleMemo.Lines.Text := TrimRight(ConsoleMemo.Lines.Text); end; end.
unit uPedido; interface uses FireDAC.Comp.Client, System.SysUtils,System.Classes, uDm, Datasnap.DBClient; type TPedido = class private query: TFDQuery; function pConectaBanco() : boolean; public constructor Create(); destructor Destroy(); Override; function RetornaTodosClientes() : TFDQuery; function RetornaTodosProdutos() : TFDQuery; function RetornaClientePorId(idCliente : String) : TFDQuery; function RetornaProdutoPorId(idProduto : String) : TFDQuery; function RetornaProdutosPedido(idPedido : Integer) : TFDQuery; function IncluiNovoPedido(idCliente : Integer) : Integer; procedure IncluiItemPedido(idPedido, idProduto, quantidade : Integer; vlUnitario, vlTotal : Double); function RetornaValorPedido(idPedido : Integer) : TFDQuery; function RetornaDadosPedido() : TFDQuery; function RetornaDadosPedidoPorId(idPedido : Integer) : TFDQuery; procedure AtualizaVlTotalPedido(vlTotal: Double; IdPedido: Integer); procedure DeletarPedidoItens(idPedido : Integer); end; implementation { TPedido } procedure TPedido.AtualizaVlTotalPedido(vlTotal: Double; IdPedido: Integer); begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('UPDATE PEDIDOS_GERAIS SET VALOR_TOTAL = :VALOR_TOTAL WHERE CD_PEDIDO = :CD_PEDIDO'); query.Params.ParamByName('VALOR_TOTAL').AsFloat := vlTotal; query.Params.ParamByName('CD_PEDIDO').AsInteger := IdPedido; query.ExecSQL; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; end; constructor TPedido.Create; begin pConectaBanco(); end; procedure TPedido.DeletarPedidoItens(idPedido: Integer); begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('DELETE FROM PEDIDOS_PRODUTOS WHERE ID_PEDIDO = :ID_PEDIDO'); query.Params.ParamByName('ID_PEDIDO').AsInteger := idPedido; query.ExecSQL; query.Close; query.SQL.Clear; query.SQL.Add('DELETE FROM PEDIDOS_GERAIS WHERE CD_PEDIDO = :CD_PEDIDO'); query.Params.ParamByName('CD_PEDIDO').AsInteger := idPedido; query.ExecSQL; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; end; destructor TPedido.Destroy; begin inherited; end; procedure TPedido.IncluiItemPedido(idPedido, idProduto, quantidade : Integer; vlUnitario, vlTotal : Double); var cdPedidoProduto: Integer; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT MAX(CD_PEDIDO_PRODUTO) CD_PEDIDO_PRODUTO FROM PEDIDOS_PRODUTOS'); query.Open; cdPedidoProduto := query.FieldByName('CD_PEDIDO_PRODUTO').AsInteger + 1; query.Close; query.SQL.Clear; query.SQL.Add('INSERT INTO PEDIDOS_PRODUTOS(CD_PEDIDO_PRODUTO, ID_PEDIDO, ID_PRODUTO,'); query.SQL.Add('QUANTIDADE, VALOR_UNITARIO, VALOR_TOTAL)'); query.SQL.Add('VALUES(:CD_PEDIDO_PRODUTO, :ID_PEDIDO, :ID_PRODUTO,'); query.SQL.Add(':QUANTIDADE, :VALOR_UNITARIO, :VALOR_TOTAL)'); query.Params.ParamByName('CD_PEDIDO_PRODUTO').AsInteger := cdPedidoProduto; query.Params.ParamByName('ID_PEDIDO').AsInteger := idPedido; query.Params.ParamByName('ID_PRODUTO').AsInteger := idProduto; query.Params.ParamByName('QUANTIDADE').AsInteger := quantidade; query.Params.ParamByName('VALOR_UNITARIO').AsFloat := vlUnitario; query.Params.ParamByName('VALOR_TOTAL').AsFloat := vlTotal; query.ExecSQL; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; end; function TPedido.IncluiNovoPedido(idCliente : Integer) : Integer; var cdPedido: Integer; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT MAX(CD_PEDIDO) CD_PEDIDO FROM PEDIDOS_GERAIS'); query.Open; cdPedido := query.FieldByName('CD_PEDIDO').AsInteger + 1; query.Close; query.SQL.Clear; query.SQL.Add('INSERT INTO PEDIDOS_GERAIS(CD_PEDIDO, DATA_EMISSAO, ID_CLIENTE, VALOR_TOTAL)'); query.SQL.Add('VALUES(:CD_PEDIDO, :DATA_EMISSAO, :ID_CLIENTE, :VALOR_TOTAL)'); query.Params.ParamByName('CD_PEDIDO').AsInteger := cdPedido; query.Params.ParamByName('DATA_EMISSAO').AsDate := Now; query.Params.ParamByName('ID_CLIENTE').AsInteger := idCliente; query.Params.ParamByName('VALOR_TOTAL').AsFloat := 0; query.ExecSQL; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := cdPedido; end; function TPedido.pConectaBanco: boolean; begin try dm.Conexao.Connected := False; dm.Conexao.Params.UserName := 'root'; dm.Conexao.Params.Password := ''; dm.Conexao.Params.Database := 'bdpedido'; dm.Conexao.Params.Values['Server'] := '127.0.0.1'; dm.Conexao.Params.Values['Port'] := '3306'; dm.Conexao.Connected := True; Result := True; except on E: Exception do Result := False; end; end; function TPedido.RetornaClientePorId(idCliente : string): TFDQuery; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT * FROM CLIENTES WHERE CD_CLIENTE = '+idCliente); query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaDadosPedido: TFDQuery; begin query := TFDQuery.Create(nil); query.Connection := dm.Conexao; try query.Close; query.SQL.Clear; query.SQL.Add('SELECT CLIENTES.*, PEDIDOS_GERAIS.* FROM PEDIDOS_GERAIS'); query.SQL.Add('LEFT JOIN CLIENTES ON CLIENTES.CD_CLIENTE = PEDIDOS_GERAIS.ID_CLIENTE'); query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaDadosPedidoPorId(idPedido : Integer): TFDQuery; begin query := TFDQuery.Create(nil); query.Connection := dm.Conexao; try query.Close; query.SQL.Clear; query.SQL.Add('SELECT CLIENTES.*, PEDIDOS_GERAIS.* FROM PEDIDOS_GERAIS'); query.SQL.Add('LEFT JOIN CLIENTES ON CLIENTES.CD_CLIENTE = PEDIDOS_GERAIS.ID_CLIENTE'); query.SQL.Add('WHERE CD_PEDIDO = :CD_PEDIDO'); query.Params.ParamByName('CD_PEDIDO').AsInteger := idPedido; query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaProdutoPorId(idProduto : string): TFDQuery; begin query := TFDQuery.Create(nil); query.Connection := dm.Conexao; try query.Close; query.SQL.Clear; query.SQL.Add('SELECT * FROM PRODUTOS WHERE CD_PRODUTO = '+idProduto); query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaProdutosPedido(idPedido: Integer): TFDQuery; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT PEDIDOS_GERAIS.CD_PEDIDO, PEDIDOS_GERAIS.DATA_EMISSAO, PEDIDOS_GERAIS.ID_CLIENTE,'); query.SQL.Add('PRODUTOS.DESCRICAO, PEDIDOS_PRODUTOS.* FROM PEDIDOS_PRODUTOS'); query.SQL.Add('LEFT JOIN PEDIDOS_GERAIS ON PEDIDOS_GERAIS.CD_PEDIDO = PEDIDOS_PRODUTOS.ID_PEDIDO'); query.SQL.Add('LEFT JOIN PRODUTOS ON PRODUTOS.CD_PRODUTO = PEDIDOS_PRODUTOS.ID_PRODUTO'); query.SQL.Add('WHERE CD_PEDIDO = :CD_PEDIDO'); query.Params.ParamByName('CD_PEDIDO').AsInteger := idPedido; query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaTodosClientes: TFDQuery; var cdsTemp: TClientDataSet; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT * FROM CLIENTES'); query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaTodosProdutos: TFDQuery; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT * FROM PRODUTOS'); query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; function TPedido.RetornaValorPedido(idPedido: Integer): TFDQuery; begin try query := TFDQuery.Create(nil); query.Connection := dm.Conexao; query.Close; query.SQL.Clear; query.SQL.Add('SELECT SUM(VALOR_TOTAL) VALOR_TOTAL, COUNT(CD_PEDIDO_PRODUTO) CD_PEDIDO_PRODUTO FROM PEDIDOS_PRODUTOS'); query.SQL.Add('WHERE ID_PEDIDO = :ID_PEDIDO'); query.Params.ParamByName('ID_PEDIDO').AsInteger := idPedido; query.Open; except on E: Exception do begin raise Exception.Create(E.ToString); Abort; end; end; Result := query; end; end.
unit caUDP; interface uses Windows, SysUtils, Classes, WinSock, syncobjs; type TcaUDPDataEvent = procedure(Sender: TObject; const Buffer: Pointer; const RecvSize: Integer; const Peer: string; const Port: Integer) of object; TcaUDPSender = class(TComponent) private // Private fields  FHandle: TSocket; FActive: Boolean; FRemoteIP: String; FRemoteHost: String; FRemotePort: Word; CS: TCriticalSection; Procedure SetActive(const Value: Boolean); Procedure SetRemoteIP(const Value: String); Procedure SetRemoteHost(const Value: String); Procedure SetRemotePort(const Value: Word); public // Public methods  Class function ResolveHost(const psHost: string; var psIP: string): u_long; virtual; Class function ResolveIP(const psIP: string): string; virtual; Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Procedure Connect; Procedure Disconnect; Function SendBuf(var Buffer; BufSize: Integer): Integer; property Handle: TSocket read FHandle; published { Published declarations } property Active: Boolean read FActive write SetActive default False; property RemoteIP: String read FRemoteIP write SetRemoteIP; property RemoteHost: String read FRemoteHost write SetRemoteHost; property RemotePort: Word read FRemotePort write SetRemotePort; end; TUDPReceiver = class; TUDPReceiverThread = class(TThread) protected FReceiver: TUDPReceiver; FBuffer: Pointer; FRecvSize: Integer; FPeer: string; FPort: Integer; FBufSize: Integer; procedure SetBufSize(const Value: Integer); public procedure Execute; override; procedure UDPRead; published Property BufSize: Integer read FBufSize write SetBufSize; Property Receiver: TUDPReceiver read FReceiver write FReceiver; end; TUDPReceiver = class(TComponent) private { Private declarations } FHandle: TSocket; FActive: Boolean; FPort: Word; FBufferSize: Integer; FMulticastIP : String; // FUDPBuffer: Pointer; FOnUDPData: TcaUDPDataEvent; FUDPReceiverThread: TUDPReceiverThread; Procedure SetActive(const Value: Boolean); Procedure SetPort(const Value: Word); Procedure SetBufferSize(const Value: Integer); procedure SetMulticastIP(const Value: String); protected { Protected declarations } public { Public declarations } Class Function BindMulticast(const Socket: TSocket; const IP:String): LongInt; virtual; Constructor Create(AOwner: TComponent); override; Destructor Destroy; override; Procedure Connect; Procedure Disconnect; procedure DoUDPRead(const Buffer: Pointer; const RecvSize:Integer; const Peer: string; const Port: Integer); virtual; property Handle: TSocket read FHandle; published { Published declarations } property Active: Boolean read FActive write SetActive default False; property Port: Word read FPort write SetPort; property BufferSize: Integer read FBufferSize write SetBufferSize default 65000; property OnUDPData: TcaUDPDataEvent read FOnUDPData write FOnUDPData; property MulticastIP: String read FMulticastIP write SetMulticastIP; end; type // exception EBufferUDP = Exception; procedure Register; resourcestring EUDPNOTACTIVE = 'UDP Socket not connected'; EUDPACTIVED = 'UDP Socket already connected'; EWSAError = 'Socket Error : %d'; EUNABLERESOLVEHOST = 'Unable to resolve host: %s'; EUNABLERESOLVEIP = 'Unable to resolve IP: %s'; EZEROBYTESEND = '0 bytes were sent.'; EPACKAGETOOBIG = 'Package Size Too Big: %d'; ENOREMOTESIDE = 'Remote Host/IP not identified!'; ESIZEOUTOFBOUNDARY = 'Size value is out of boundary!'; EWSAENOBUFS = 'An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.'; EWSANOTINITIALISED = 'A successful WSAStartup must occur before using this function.'; EWSAENETDOWN = 'The network subsystem has failed.'; EWSAEFAULT = 'optval is not in a valid part of the process address space or optlen argument is too small.'; EWSAEINPROGRESS = 'A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.'; EWSAEINVAL = 'level is not valid, or the information in optval is not valid.'; EWSAENETRESET = 'Connection has timed out when SO_KEEPALIVE is set.'; EWSAENOPROTOOPT = 'The option is unknown or unsupported for the specified provider.'; EWSAENOTCONN = 'Connection has been reset when SO_KEEPALIVE is set.'; EWSAENOTSOCK = 'The descriptor is not a socket.'; EWSAUNKNOW = 'Unknow socket error.'; implementation procedure Register; begin RegisterComponents('Samson', [TcaUDPSender, TUDPReceiver]); end; Type TIMR = Packed Record imr_multiaddr: LongInt; imr_interface: LongInt; End; { TcaUDPSender } procedure TcaUDPSender.Connect; Var Faddr: TSockAddrIn; begin CS.Enter; try If FActive then Raise EBufferUDP.CreateRes(@EUDPACTIVED); If ((FRemoteHost='') and (FRemoteIP='')) then Raise EBufferUDP.CreateRes(@ENOREMOTESIDE); If Not (csDesigning in ComponentState) then Begin FHandle:= WinSock.Socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); If FHandle = INVALID_SOCKET then Raise EBufferUDP.CreateResFmt(@EWSAError, [WSAGetLastError]); with faddr do begin sin_family := PF_INET; sin_port := WinSock.htons(FRemotePort); // sin_addr.s_addr := WinSock.ResolveHost(fsHost, fsPeerAddress); if length(FRemoteIP) > 0 then begin sin_addr.s_addr := WinSock.inet_addr(PChar(FRemoteIP)); end; end; WinSock.connect(FHandle, faddr, Sizeof(faddr)); End; FActive:= True; finally CS.Leave; end; end; constructor TcaUDPSender.Create(AOwner: TComponent); begin inherited; CS:= TCriticalSection.Create; FActive:= False; FHandle := INVALID_SOCKET; // FReceiveTimeout := -1; end; destructor TcaUDPSender.Destroy; begin Active:= False; CS.Free; inherited; end; procedure TcaUDPSender.Disconnect; Var OldHandle: TSocket; begin CS.Enter; try If FActive then Begin OldHandle:= FHandle; FHandle:= INVALID_SOCKET; CloseSocket(OldHandle); End; finally FActive:= False; CS.Leave; end; end; class function TcaUDPSender.ResolveHost(const psHost: string; var psIP: string): u_long; Var pa: PChar; sa: TInAddr; aHost: PHostEnt; begin psIP := psHost; // Sometimes 95 forgets who localhost is if CompareText(psHost, 'LOCALHOST') = 0 then begin sa.S_un_b.s_b1 := #127; sa.S_un_b.s_b2 := #0; sa.S_un_b.s_b3 := #0; sa.S_un_b.s_b4 := #1; psIP := '127.0.0.1'; Result := sa.s_addr; end else begin // Done if is tranlated (ie There were numbers} Result := inet_addr(PChar(psHost)); // If no translation, see if it resolves} if Result = u_long(INADDR_NONE) then begin aHost := Winsock.GetHostByName(PChar(psHost)); if aHost = nil then begin Result:= 0; psIP:= ''; Exit; //Raise EBufferUDP.CreateResFmt(@EUNABLERESOLVEHOST, [psHost]); end else begin pa := aHost^.h_addr_list^; sa.S_un_b.s_b1 := pa[0]; sa.S_un_b.s_b2 := pa[1]; sa.S_un_b.s_b3 := pa[2]; sa.S_un_b.s_b4 := pa[3]; psIP:= String(inet_ntoa(sa)); //psIP := TInAddrToString(sa); end; Result := sa.s_addr; end; end; end; class function TcaUDPSender.ResolveIP(const psIP: string): string; var i: Integer; P: PHostEnt; begin result := ''; if CompareText(psIP, '127.0.0.1') = 0 then begin result := 'LOCALHOST'; end else begin i := Winsock.inet_addr(PChar(psIP)); P := Winsock.GetHostByAddr(@i, 4, PF_INET); If P = nil then Begin Result:= ''; Exit; // Raise EBufferUDP.CreateResFmt(@EUNABLERESOLVEIP, [psIP]); //CheckForSocketError2(SOCKET_ERROR, [WSANO_DATA]); End else Begin result := P.h_name; End; end; end; Function TcaUDPSender.SendBuf(var Buffer; BufSize: Integer): Integer; begin CS.Enter; try Result:= 0; If BufSize<=0 then Exit; If Not FActive then Raise EBufferUDP.CreateRes(@EUDPNOTACTIVE); Result:= Winsock.send(FHandle, Buffer, BufSize, 0); If Result<>BufSize then Begin Case Result of 0: Raise EBufferUDP.CreateRes(@EZEROBYTESEND); SOCKET_ERROR: If WSAGetLastError = WSAEMSGSIZE then Raise EBufferUDP.CreateResFmt(@EPACKAGETOOBIG, [BufSize]) End;{CASE} End; finally CS.Leave; end; end; procedure TcaUDPSender.SetActive(const Value: Boolean); begin If FActive<>Value then Begin If Value then Connect Else Disconnect; End; end; procedure TcaUDPSender.SetRemoteHost(const Value: String); Var IsConnected: Boolean; begin If FRemoteHost<>Value then Begin IsConnected:= Active; Active:= False; FRemoteHost:= Value; If Not (csDesigning in ComponentState) then ResolveHost(FRemoteHost, FRemoteIP); // Resovle IP Active:= IsConnected; End; end; procedure TcaUDPSender.SetRemoteIP(const Value: String); Var IsConnected: Boolean; begin If FRemoteIP<>Value then Begin IsConnected:= Active; Active:= False; FRemoteIP:= Value; // Resovle Host name If Not (csDesigning in ComponentState) then FRemoteHost:= ResolveIP(FRemoteIP); Active:= IsConnected; End; end; procedure TcaUDPSender.SetRemotePort(const Value: Word); Var IsConnected: Boolean; begin If FRemotePort<>Value then Begin IsConnected:= Active; Active:= False; FRemotePort:= Value; Active:= IsConnected; End; end; { TUDPReceiver } class function TUDPReceiver.BindMulticast(const Socket: TSocket; const IP: String): LongInt; Var lpMulti: TIMR; Begin lpMulti.imr_multiaddr := inet_addr(PChar(IP)); lpMulti.imr_interface := 0; Result:= SetSockOpt(Socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, @lpMulti, Sizeof(lpMulti)); End; procedure TUDPReceiver.Connect; var m_addr: TSockAddrIn; begin If FActive then Raise EBufferUDP.CreateRes(@EUDPACTIVED); If csDesigning in ComponentState then Begin FActive:= True; Exit; End; // SOCKET FHandle := Winsock.Socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); If FHandle = INVALID_SOCKET then Raise EBufferUDP.CreateResFmt(@EWSAError, [WSAGetLastError]); // BIND With m_addr do begin sin_family := PF_INET; sin_port := Winsock.htons(FPort); sin_addr.s_addr := INADDR_ANY; End; If WinSock.bind(FHandle, m_addr, Sizeof(m_addr))=SOCKET_ERROR then Raise EBufferUDP.CreateResFmt(@EWSAError, [WSAGetLastError]); // Bind Multicast If FMulticastIP<>'' then If BindMulticast(FHandle, FMulticastIP)=SOCKET_ERROR then Case WSAGetLastError of WSAENOBUFS: Raise EBufferUDP.CreateRes(@EWSAENOBUFS ); WSANOTINITIALISED: Raise EBufferUDP.CreateRes(@EWSANOTINITIALISED); WSAENETDOWN: Raise EBufferUDP.CreateRes(@EWSAENETDOWN ); WSAEFAULT: Raise EBufferUDP.CreateRes(@EWSAEFAULT ); WSAEINPROGRESS: Raise EBufferUDP.CreateRes(@EWSAEINPROGRESS ); WSAEINVAL: Raise EBufferUDP.CreateRes(@EWSAEINVAL ); WSAENETRESET: Raise EBufferUDP.CreateRes(@EWSAENETRESET ); WSAENOPROTOOPT: Raise EBufferUDP.CreateRes(@EWSAENOPROTOOPT ); WSAENOTCONN: Raise EBufferUDP.CreateRes(@EWSAENOTCONN ); WSAENOTSOCK: Raise EBufferUDP.CreateRes(@EWSAENOTSOCK ); Else Raise EBufferUDP.CreateRes(@EWSAUNKNOW); End; {CASE} // Thread read FUDPReceiverThread := TUDPReceiverThread.Create(True); With FUDPReceiverThread do Begin Receiver:= Self; BufSize:= FBufferSize; FreeOnTerminate := True; Resume; End; FActive:= True; end; constructor TUDPReceiver.Create(AOwner: TComponent); begin inherited; FHandle := INVALID_SOCKET; FActive:= False; FBufferSize:= 65000; FMulticastIP:= ''; end; destructor TUDPReceiver.Destroy; begin Active:= False; inherited; end; procedure TUDPReceiver.Disconnect; Var OldHandle: TSocket; begin If Not FActive then Exit; try OldHandle:= FHandle; FHandle:= INVALID_SOCKET; CloseSocket(OldHandle); finally FActive:= False; end; If FUDPReceiverThread <> nil then Begin FUDPReceiverThread.Terminate; FUDPReceiverThread.WaitFor; End; end; procedure TUDPReceiver.DoUDPRead(const Buffer: Pointer; const RecvSize:Integer; const Peer: string; const Port: Integer); begin If Assigned(FOnUDPData) then begin FOnUDPData(Self, Buffer, RecvSize, Peer, Port); End; end; procedure TUDPReceiver.SetActive(const Value: Boolean); begin If FActive<>Value then Begin If Value then Connect Else Disconnect; End; end; procedure TUDPReceiver.SetBufferSize(const Value: Integer); begin If FBufferSize<>Value then Begin If ((Value>=1024) and (Value<=65000)) then FBufferSize:= Value Else Raise EBufferUDP.CreateRes(@ESIZEOUTOFBOUNDARY); End; end; procedure TUDPReceiver.SetMulticastIP(const Value: String); Var IsConnected: Boolean; begin If Value<>FMulticastIP then Begin IsConnected:= Active; Active:= False; FMulticastIP:= Value; Active:= IsConnected; End; end; procedure TUDPReceiver.SetPort(const Value: Word); Var IsConnected: Boolean; begin If FPort<>Value then Begin IsConnected:= Active; Active:= False; FPort:= Value; Active:= IsConnected; End; end; { TUDPReceiverThread } procedure TUDPReceiverThread.Execute; var i: Integer; addr_remote: TSockAddrin; arSize: Integer; begin GetMem(FBuffer, FBufSize); arSize:= SizeOf(addr_remote); while FReceiver.Active and not Terminated do Begin i := arSize; FRecvSize := Winsock.RecvFrom(FReceiver.Handle, FBuffer^, FBufSize, 0, addr_remote, i); If FReceiver.Active and (FRecvSize>0) then Begin //fsData := Copy(fListener.fsUDPBuffer, 1, iByteCount); FPeer := String(inet_ntoa(addr_remote.sin_addr)); //FPeer := String(TWinshoe.TInAddrToString(addr_remote.sin_addr)); FPort := Winsock.NToHS(addr_remote.sin_port); Synchronize(UDPRead); End; End; FreeMem(FBuffer); end; procedure TUDPReceiverThread.SetBufSize(const Value: Integer); begin If FBufSize<> Value then FBufSize:= Value; end; procedure TUDPReceiverThread.UDPRead; begin FReceiver.DoUDPRead(FBuffer, FRecvSize, FPeer, FPort); end; Var GWSADATA: TWSADATA; initialization WSAStartup(MakeWord(2, 0), GWSADATA); finalization WSACleanup; end.
{ AD.A.P.T. Library Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved Original Source Location: https://github.com/LaKraven/ADAPT Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md } unit ADAPT.Performance.Threadsafe; {$I ADAPT.inc} interface uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} ADAPT, ADAPT.Intf, ADAPT.Threadsafe, ADAPT.Performance; {$I ADAPT_RTTI.inc} type TADPerformanceCounterTS = class; /// <summary><c>Threadsafe Performance Counter Type.</c></summary> /// <remarks> /// <para><c>Keeps track of Performance both Instant and Average, in units of Things Per Second.</c></para> /// <para><c>Note that this does NOT operate like a "Stopwatch", it merely takes the given Time Difference (Delta) Values to calculate smooth averages.</c></para> /// <para><c>Contains a Threadsafe Lock.</c></para> /// </remarks> TADPerformanceCounterTS = class(TADPerformanceCounter, IADReadWriteLock) protected FLock: TADReadWriteLock; function GetLock: IADReadWriteLock; { Getters } function GetAverageOver: Cardinal; override; function GetAverageRate: ADFloat; override; function GetInstantRate: ADFloat; override; { Setters } procedure SetAverageOver(const AAverageOver: Cardinal = 10); override; public constructor Create(const AAverageOver: Cardinal); override; destructor Destroy; override; procedure RecordSample(const AValue: ADFloat); override; procedure Reset; override; /// <summary><c>The number of Samples over which to calculate the Average</c></summary> property AverageOver: Cardinal read GetAverageOver write SetAverageOver; /// <summary><c>The Average Rate (based on the number of Samples over which to calculate it)</c></summary> property AverageRate: ADFloat read GetAverageRate; /// <summary><c>The Instant Rate (based only on the last given Sample)</c></summary> property InstantRate: ADFloat read GetInstantRate; /// <summary><c>Multi-Read, Exclusive-Write Threadsafe Lock.</c></summary> property Lock: IADReadWriteLock read GetLock implements IADReadWriteLock; end; implementation { TADPerformanceCounterTS } constructor TADPerformanceCounterTS.Create(const AAverageOver: Cardinal); begin FLock := ADReadWriteLock(Self); inherited; end; destructor TADPerformanceCounterTS.Destroy; begin FLock.{$IFDEF SUPPORTS_DISPOSEOF}DisposeOf{$ELSE}Free{$ENDIF SUPPORTS_DISPOSEOF}; inherited; end; function TADPerformanceCounterTS.GetAverageOver: Cardinal; begin FLock.AcquireRead; try Result := inherited; finally FLock.ReleaseRead; end; end; function TADPerformanceCounterTS.GetAverageRate: ADFloat; begin FLock.AcquireRead; try Result := inherited; finally FLock.ReleaseRead; end; end; function TADPerformanceCounterTS.GetInstantRate: ADFloat; begin FLock.AcquireRead; try Result := inherited; finally FLock.ReleaseRead; end; end; function TADPerformanceCounterTS.GetLock: IADReadWriteLock; begin Result := FLock; end; procedure TADPerformanceCounterTS.RecordSample(const AValue: ADFloat); begin FLock.AcquireWrite; try inherited; finally FLock.ReleaseWrite; end; end; procedure TADPerformanceCounterTS.Reset; begin FLock.AcquireWrite; try inherited; finally FLock.ReleaseWrite; end; end; procedure TADPerformanceCounterTS.SetAverageOver(const AAverageOver: Cardinal); begin FLock.AcquireWrite; try inherited; finally FLock.ReleaseWrite; end; end; end.
unit BodyVariationOptionQuery; 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, DSWrap; type TBodyVariationOptionW = class(TDSWrap) private FIDBodyOption: TFieldWrap; FID: TFieldWrap; FIDBodyVariation: TFieldWrap; public constructor Create(AOwner: TComponent); override; property IDBodyOption: TFieldWrap read FIDBodyOption; property ID: TFieldWrap read FID; property IDBodyVariation: TFieldWrap read FIDBodyVariation; end; TQueryBodyVariationOption = class(TQueryBase) private FW: TBodyVariationOptionW; { Private declarations } public constructor Create(AOwner: TComponent); override; function SearchByIDBodyVariation(AIDBodyVariation: Integer): Integer; procedure UpdateOption(AIDBodyVariation: Integer; AOptionIDArr: TArray<Integer>); property W: TBodyVariationOptionW read FW; { Public declarations } end; implementation uses StrHelper, System.Generics.Collections; {$R *.dfm} constructor TQueryBodyVariationOption.Create(AOwner: TComponent); begin inherited; FW := TBodyVariationOptionW.Create(FDQuery); end; function TQueryBodyVariationOption.SearchByIDBodyVariation(AIDBodyVariation : Integer): Integer; begin Assert(AIDBodyVariation > 0); // Ищем Result := SearchEx([TParamRec.Create(W.IDBodyVariation.FullName, AIDBodyVariation)]); end; procedure TQueryBodyVariationOption.UpdateOption(AIDBodyVariation: Integer; AOptionIDArr: TArray<Integer>); var i: Integer; begin SearchByIDBodyVariation(AIDBodyVariation); // Сначала удалим всё лишнее W.DeleteAll; { TArray.Sort<Integer>(AOptionIDArr); FDQuery.First; while not FDQuery.Eof do begin // Ищем в массиве такого кода нет - нужно удалить его из БД if not TArray.BinarySearch(AOptionIDArr, W.IDBodyOption.F.AsInteger, i) then FDQuery.Delete else FDQuery.Next; end; } // Теперь добавим недостающее for i := Low(AOptionIDArr) to High(AOptionIDArr) do begin if not W.IDBodyOption.Locate(AOptionIDArr[i], []) then begin W.TryAppend; W.IDBodyVariation.F.AsInteger := AIDBodyVariation; W.IDBodyOption.F.AsInteger := AOptionIDArr[i]; W.TryPost; end; end; end; constructor TBodyVariationOptionW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FIDBodyOption := TFieldWrap.Create(Self, 'IDBodyOption'); FIDBodyVariation := TFieldWrap.Create(Self, 'IDBodyVariation'); end; end.
program _demo; Array[0] var State : AutoGKState; V : Double; Rep : AutoGKReport; A : Double; B : Double; Alpha : Double; begin // // f1(x) = (1+x)*(x-a)^alpha, alpha=-0.3 // Exact answer is (B-A)^(Alpha+2)/(Alpha+2) + (1+A)*(B-A)^(Alpha+1)/(Alpha+1) // // This code demonstrates use of the State.XMinusA (State.BMinusX) field. // // If we try to use State.X instead of State.XMinusA, // we will end up dividing by zero! (in 64-bit precision) // A := 1.0; B := 5.0; Alpha := -0.9; AutoGKSingular(A, B, Alpha, 0.0, State); while AutoGKIteration(State) do begin State.F := Power(State.XMinusA, Alpha)*(1+State.X); end; AutoGKResults(State, V, Rep); Write(Format('integral((1+x)*(x-a)^alpha) on [%0.1f; %0.1f] = %0.2f'#13#10'Exact answer is %0.2f'#13#10'',[ A, B, V, Power(B-A, Alpha+2)/(Alpha+2)+(1+A)*Power(B-A, Alpha+1)/(Alpha+1)])); end.
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { 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 Vector.pas. } { } { The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by } { Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) } { All rights reserved. } { } { Contributors: } { Daniele Teti (dade2004) } { Robert Marquardt (marquardt) } { Robert Rossmair (rrossmair) } { Florent Ouchet (outchy) } { } {**************************************************************************************************} { } { The Delphi Container Library } { } {**************************************************************************************************} { } { Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ } { Revision: $Rev:: 2376 $ } { Author: $Author:: obones $ } { } {**************************************************************************************************} unit JclVectors; {$I jcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} {$IFDEF SUPPORTS_GENERICS} {$IFDEF CLR} System.Collections.Generic, {$ENDIF CLR} JclAlgorithms, {$ENDIF SUPPORTS_GENERICS} Classes, JclBase, JclAbstractContainers, JclContainerIntf, JclSynch; {$I containers\JclContainerCommon.imp} {$I containers\JclVectors.imp} {$I containers\JclVectors.int} type (*$JPPEXPANDMACRO JCLVECTORINT(TJclIntfVector,TJclIntfAbstractContainer,IJclIntfCollection,IJclIntfList,IJclIntfArray,IJclIntfIterator, IJclIntfEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AInterface,IInterface,nil,JclBase.TDynIInterfaceArray,GetObject,SetObject)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclAnsiStrVector,TJclAnsiStrAbstractCollection,IJclAnsiStrCollection,IJclAnsiStrList,IJclAnsiStrArray,IJclAnsiStrIterator, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrFlatContainer\, IJclAnsiStrEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,AnsiString,'',JclBase.TDynAnsiStringArray,GetString,SetString)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclWideStrVector,TJclWideStrAbstractCollection,IJclWideStrCollection,IJclWideStrList,IJclWideStrArray,IJclWideStrIterator, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrFlatContainer\, IJclWideStrEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,,const ,AString,WideString,'',JclBase.TDynWideStringArray,GetString,SetString)*) {$IFDEF CONTAINER_ANSISTR} TJclStrVector = TJclAnsiStrVector; {$ENDIF CONTAINER_ANSISTR} {$IFDEF CONTAINER_WIDESTR} TJclStrVector = TJclWideStrVector; {$ENDIF CONTAINER_WIDESTR} (*$JPPEXPANDMACRO JCLVECTORINT(TJclSingleVector,TJclSingleAbstractContainer,IJclSingleCollection,IJclSingleList,IJclSingleArray,IJclSingleIterator, IJclSingleContainer\, IJclSingleEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Single,0.0,JclBase.TDynSingleArray,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclDoubleVector,TJclDoubleAbstractContainer,IJclDoubleCollection,IJclDoubleList,IJclDoubleArray,IJclDoubleIterator, IJclDoubleContainer\, IJclDoubleEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Double,0.0,JclBase.TDynDoubleArray,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclExtendedVector,TJclExtendedAbstractContainer,IJclExtendedCollection,IJclExtendedList,IJclExtendedArray,IJclExtendedIterator, IJclExtendedContainer\, IJclExtendedEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Extended,0.0,JclBase.TDynExtendedArray,GetValue,SetValue)*) {$IFDEF MATH_EXTENDED_PRECISION} TJclFloatVector = TJclExtendedVector; {$ENDIF MATH_EXTENDED_PRECISION} {$IFDEF MATH_DOUBLE_PRECISION} TJclFloatVector = TJclDoubleVector; {$ENDIF MATH_DOUBLE_PRECISION} {$IFDEF MATH_SINGLE_PRECISION} TJclFloatVector = TJclSingleVector; {$ENDIF MATH_SINGLE_PRECISION} (*$JPPEXPANDMACRO JCLVECTORINT(TJclIntegerVector,TJclIntegerAbstractContainer,IJclIntegerCollection,IJclIntegerList,IJclIntegerArray,IJclIntegerIterator, IJclIntegerEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Integer,0,JclBase.TDynIntegerArray,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclCardinalVector,TJclCardinalAbstractContainer,IJclCardinalCollection,IJclCardinalList,IJclCardinalArray,IJclCardinalIterator, IJclCardinalEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,AValue,Cardinal,0,JclBase.TDynCardinalArray,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORINT(TJclInt64Vector,TJclInt64AbstractContainer,IJclInt64Collection,IJclInt64List,IJclInt64Array,IJclInt64Iterator, IJclInt64EqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,const ,AValue,Int64,0,JclBase.TDynInt64Array,GetValue,SetValue)*) {$IFNDEF CLR} (*$JPPEXPANDMACRO JCLVECTORINT(TJclPtrVector,TJclPtrAbstractContainer,IJclPtrCollection,IJclPtrList,IJclPtrArray,IJclPtrIterator, IJclPtrEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,,APtr,Pointer,nil,JclBase.TDynPointerArray,GetPointer,SetPointer)*) {$ENDIF ~CLR} (*$JPPEXPANDMACRO JCLVECTORINT(TJclVector,TJclAbstractContainer,IJclCollection,IJclList,IJclArray,IJclIterator, IJclObjectOwner\, IJclEqualityComparer\,,, function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,; AOwnsObjects: Boolean,,AObject,TObject,nil,JclBase.TDynObjectArray,GetObject,SetObject)*) {$IFDEF SUPPORTS_GENERICS} (*$JPPEXPANDMACRO JCLVECTORINT(TJclVector<T>,TJclAbstractContainer<T>,IJclCollection<T>,IJclList<T>,IJclArray<T>,IJclIterator<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\,,,,,,; AOwnsItems: Boolean,const ,AItem,T,Default(T),TJclBase<T>.TDynArray,GetItem,SetItem)*) // E = External helper to compare items for equality (GetHashCode is not used) TJclVectorE<T> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) private FEqualityComparer: IEqualityComparer<T>; protected procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override; function CreateEmptyContainer: TJclAbstractContainerBase; override; function ItemsEqual(const A, B: T): Boolean; override; { IJclCloneable } function IJclCloneable.Clone = ObjectClone; { IJclIntfCloneable } function IJclIntfCloneable.Clone = IntfClone; public constructor Create(const AEqualityComparer: IEqualityComparer<T>; ACapacity: Integer; AOwnsItems: Boolean); property EqualityComparer: IEqualityComparer<T> read FEqualityComparer write FEqualityComparer; end; // F = Function to compare items for equality TJclVectorF<T> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) protected function CreateEmptyContainer: TJclAbstractContainerBase; override; { IJclCloneable } function IJclCloneable.Clone = ObjectClone; { IJclIntfCloneable } function IJclIntfCloneable.Clone = IntfClone; public constructor Create(const AEqualityCompare: TEqualityCompare<T>; ACapacity: Integer; AOwnsItems: Boolean); end; // I = Items can compare themselves to an other for equality TJclVectorI<T: IEquatable<T>> = class(TJclVector<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE} IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclItemOwner<T>) protected function CreateEmptyContainer: TJclAbstractContainerBase; override; function ItemsEqual(const A, B: T): Boolean; override; { IJclCloneable } function IJclCloneable.Clone = ObjectClone; { IJclIntfCloneable } function IJclIntfCloneable.Clone = IntfClone; end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclVectors.pas $'; Revision: '$Revision: 2376 $'; Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $'; LogPath: 'JCL\source\common' ); {$ENDIF UNITVERSIONING} implementation uses SysUtils; type TItrStart = (isFirst, isLast); type (*$JPPEXPANDMACRO JCLVECTORITRINT(TIntfItr,IJclIntfIterator,IJclIntfList,const ,AInterface,IInterface,GetObject,SetObject)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TIntfItr,IJclIntfIterator,IJclIntfList,const ,AInterface,IInterface,GetObject,SetObject)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrList,const ,AString,AnsiString,GetString,SetString)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TAnsiStrItr,IJclAnsiStrIterator,IJclAnsiStrList,const ,AString,AnsiString,GetString,SetString)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TWideStrItr,IJclWideStrIterator,IJclWideStrList,const ,AString,WideString,GetString,SetString)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TWideStrItr,IJclWideStrIterator,IJclWideStrList,const ,AString,WideString,GetString,SetString)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TSingleItr,IJclSingleIterator,IJclSingleList,const ,AValue,Single,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TSingleItr,IJclSingleIterator,IJclSingleList,const ,AValue,Single,GetValue,SetValue)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TDoubleItr,IJclDoubleIterator,IJclDoubleList,const ,AValue,Double,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TDoubleItr,IJclDoubleIterator,IJclDoubleList,const ,AValue,Double,GetValue,SetValue)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TExtendedItr,IJclExtendedIterator,IJclExtendedList,const ,AValue,Extended,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TExtendedItr,IJclExtendedIterator,IJclExtendedList,const ,AValue,Extended,GetValue,SetValue)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TIntegerItr,IJclIntegerIterator,IJclIntegerList,,AValue,Integer,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TIntegerItr,IJclIntegerIterator,IJclIntegerList,,AValue,Integer,GetValue,SetValue)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TCardinalItr,IJclCardinalIterator,IJclCardinalList,,AValue,Cardinal,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TCardinalItr,IJclCardinalIterator,IJclCardinalList,,AValue,Cardinal,GetValue,SetValue)*) type (*$JPPEXPANDMACRO JCLVECTORITRINT(TInt64Itr,IJclInt64Iterator,IJclInt64List,const ,AValue,Int64,GetValue,SetValue)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TInt64Itr,IJclInt64Iterator,IJclInt64List,const ,AValue,Int64,GetValue,SetValue)*) {$IFNDEF CLR} type (*$JPPEXPANDMACRO JCLVECTORITRINT(TPtrItr,IJclPtrIterator,IJclPtrList,,APtr,Pointer,GetPointer,SetPointer)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TPtrItr,IJclPtrIterator,IJclPtrList,,APtr,Pointer,GetPointer,SetPointer)*) {$ENDIF ~CLR} type (*$JPPEXPANDMACRO JCLVECTORITRINT(TItr,IJclIterator,IJclList,,AObject,TObject,GetObject,SetObject)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TItr,IJclIterator,IJclList,,AObject,TObject,GetObject,SetObject)*) {$IFDEF SUPPORTS_GENERICS} type (*$JPPEXPANDMACRO JCLVECTORITRINT(TItr<T>,IJclIterator<T>,IJclList<T>,const ,AItem,T,GetItem,SetItem)*) (*$JPPEXPANDMACRO JCLVECTORITRIMP(TItr<T>,IJclIterator<T>,IJclList<T>,const ,AItem,T,GetItem,SetItem)*) {$ENDIF SUPPORTS_GENERICS} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclIntfVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclIntfVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclIntfVector,IJclIntfCollection,IJclIntfList,IJclIntfIterator,TIntfItr,,,const ,AInterface,IInterface,nil,GetObject,SetObject,FreeObject,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclAnsiStrVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclAnsiStrVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclAnsiStrVector,IJclAnsiStrCollection,IJclAnsiStrList,IJclAnsiStrIterator,TAnsiStrItr,,,const ,AString,AnsiString,'',GetString,SetString,FreeString,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclWideStrVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclWideStrVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclWideStrVector,IJclWideStrCollection,IJclWideStrList,IJclWideStrIterator,TWideStrItr,,,const ,AString,WideString,'',GetString,SetString,FreeString,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclSingleVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclSingleVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclSingleVector,IJclSingleCollection,IJclSingleList,IJclSingleIterator,TSingleItr,,,const ,AValue,Single,0.0,GetValue,SetValue,FreeSingle,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclDoubleVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclDoubleVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclDoubleVector,IJclDoubleCollection,IJclDoubleList,IJclDoubleIterator,TDoubleItr,,,const ,AValue,Double,0.0,GetValue,SetValue,FreeDouble,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclExtendedVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclExtendedVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclExtendedVector,IJclExtendedCollection,IJclExtendedList,IJclExtendedIterator,TExtendedItr,,,const ,AValue,Extended,0.0,GetValue,SetValue,FreeExtended,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclIntegerVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclIntegerVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclIntegerVector,IJclIntegerCollection,IJclIntegerList,IJclIntegerIterator,TIntegerItr,,,,AValue,Integer,0,GetValue,SetValue,FreeInteger,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclCardinalVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclCardinalVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclCardinalVector,IJclCardinalCollection,IJclCardinalList,IJclCardinalIterator,TCardinalItr,,,,AValue,Cardinal,0,GetValue,SetValue,FreeCardinal,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclInt64Vector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclInt64Vector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclInt64Vector,IJclInt64Collection,IJclInt64List,IJclInt64Iterator,TInt64Itr,,,const ,AValue,Int64,0,GetValue,SetValue,FreeInt64,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$IFNDEF CLR} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclPtrVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclPtrVector.Create(FSize); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclPtrVector,IJclPtrCollection,IJclPtrList,IJclPtrIterator,TPtrItr,,,,APtr,Pointer,nil,GetPointer,SetPointer,FreePointer,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$ENDIF ~CLR} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER function TJclVector.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVector.Create(FSize, False); AssignPropertiesTo(Result); end; } (*$JPPEXPANDMACRO JCLVECTORIMP(TJclVector,IJclCollection,IJclList,IJclIterator,TItr,; AOwnsObjects: Boolean,AOwnsObjects,,AObject,TObject,nil,GetObject,SetObject,FreeObject,JclBase.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} {$IFDEF SUPPORTS_GENERICS} {$JPPDEFINEMACRO CREATEEMPTYCONTAINER} (*$JPPEXPANDMACRO JCLVECTORIMP(TJclVector<T>,IJclCollection<T>,IJclList<T>,IJclIterator<T>,TItr<T>,; AOwnsItems: Boolean,AOwnsItems,const ,AItem,T,Default(T),GetItem,SetItem,FreeItem,TJclBase<T>.MoveArray)*) {$JPPUNDEFMACRO CREATEEMPTYCONTAINER} //=== { TJclVectorE<T> } ===================================================== constructor TJclVectorE<T>.Create(const AEqualityComparer: IEqualityComparer<T>; ACapacity: Integer; AOwnsItems: Boolean); begin inherited Create(ACapacity, AOwnsItems); FEqualityComparer := AEqualityComparer; end; procedure TJclVectorE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase); begin inherited AssignPropertiesTo(Dest); if Dest is TJclVectorE<T> then TJclVectorE<T>(Dest).FEqualityComparer := FEqualityComparer; end; function TJclVectorE<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorE<T>.Create(EqualityComparer, FSize, False); AssignPropertiesTo(Result); end; function TJclVectorE<T>.ItemsEqual(const A, B: T): Boolean; begin if EqualityComparer <> nil then Result := EqualityComparer.Equals(A, B) else Result := inherited ItemsEqual(A, B); end; //=== { TJclVectorF<T> } ===================================================== constructor TJclVectorF<T>.Create(const AEqualityCompare: TEqualityCompare<T>; ACapacity: Integer; AOwnsItems: Boolean); begin inherited Create(ACapacity, AOwnsItems); SetEqualityCompare(AEqualityCompare); end; function TJclVectorF<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorF<T>.Create(EqualityCompare, FSize, False); AssignPropertiesTo(Result); end; //=== { TJclVectorI<T> } ===================================================== function TJclVectorI<T>.CreateEmptyContainer: TJclAbstractContainerBase; begin Result := TJclVectorI<T>.Create(FSize, False); AssignPropertiesTo(Result); end; function TJclVectorI<T>.ItemsEqual(const A, B: T): Boolean; begin if Assigned(FEqualityCompare) then Result := FEqualityCompare(A, B) else if Assigned(FCompare) then Result := FCompare(A, B) = 0 else Result := A.Equals(B); end; {$ENDIF SUPPORTS_GENERICS} {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
{*********************************************} { TeeBI Software Library } { TTeeBISource class } { Copyright (c) 2015-2016 by Steema Software } { All Rights Reserved } {*********************************************} unit FMXBI.Chart.Source; {$DEFINE FMX} interface uses System.Classes, {$IFDEF FMX} FMXTee.Engine, {$ELSE} VCLTee.TeEngine, {$ENDIF} BI.DataItem, BI.CollectionItem; type TTeeBISource=class(TTeeSeriesSource) private FItem : TDataCollectionItem; function GetData: TDataItem; function GetProvider: TComponent; procedure SetData(const Value: TDataItem); procedure SetProvider(const Value: TComponent); protected procedure DefineProperties(Filer: TFiler); override; procedure Loaded; override; public Constructor Create(AOwner:TComponent); override; Destructor Destroy; override; class Function Description:String; override; class Function Editor:TComponentClass; override; Procedure Load; override; published property Active; property Data:TDataItem read GetData write SetData; property Provider:TComponent read GetProvider write SetProvider; property Series; end; implementation
unit uMainForm; interface uses Winapi.Windows, System.Classes, System.SysUtils, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, // GLScene GLCadencer, GLWin32Viewer, GLKeyboard, GLVectorGeometry, GLGeomObjects, GLScene, GLObjects, GLGraph, GLCrossPlatform, GLSmoothNavigator, GLCoordinates, GLBaseClasses, GLScreen; type TForm1 = class(TForm) GLScene1: TGLScene; GLCadencer1: TGLCadencer; GLCamera1: TGLCamera; scene: TGLDummyCube; FPSTimer: TTimer; GLSceneViewer1: TGLSceneViewer; Panel3: TPanel; MouseLookCheckBox: TCheckBox; GLLightSource1: TGLLightSource; GLSphere1: TGLSphere; GLXYZGrid1: TGLXYZGrid; GLArrowLine1: TGLArrowLine; GroupBox2: TGroupBox; RadioButton6: TRadioButton; RadioButton7: TRadioButton; RadioButton8: TRadioButton; GroupBox1: TGroupBox; Label1: TLabel; Panel1: TPanel; procedure GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: Double); procedure FPSTimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure MouseLookCheckBoxClick(Sender: TObject); procedure RadioButton6Click(Sender: TObject); procedure RadioButton7Click(Sender: TObject); procedure RadioButton8Click(Sender: TObject); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); private { Private declarations } UI: TGLSmoothUserInterface; Navigator: TGLSmoothNavigator; // RealPos: TPoint; ShiftState: TShiftState; xx, yy: Integer; NewXX, NewYY: Integer; procedure CheckControls(DeltaTime, newTime: Double); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin Navigator := TGLSmoothNavigator.Create(Self); Navigator.AngleLock := False; Navigator.AutoUpdateObject := False; Navigator.InvertHorizontalSteeringWhenUpsideDown := True; Navigator.MoveUpWhenMovingForward := True; Navigator.UseVirtualUp := True; Navigator.VirtualUp.AsAffineVector := YVector; Navigator.MovingObject := GLCamera1; Navigator.InertiaParams.MovementAcceleration := 7; Navigator.InertiaParams.MovementInertia := 200; Navigator.InertiaParams.MovementSpeed := 200; Navigator.InertiaParams.TurnInertia := 150; Navigator.InertiaParams.TurnSpeed := 40; Navigator.InertiaParams.TurnMaxAngle := 0.5; Navigator.MoveAroundParams.TargetObject := GLArrowLine1; UI := TGLSmoothUserInterface.Create(Self); // UI.AutoUpdateMouse := False; UI.SmoothNavigator := Navigator; end; procedure TForm1.CheckControls(DeltaTime, newtime: Double); var NeedToAccelerate: Boolean; begin NeedToAccelerate := isKeyDown(VK_SHIFT); Navigator.StrafeVertical(isKeyDown('F'), isKeyDown('R'), DeltaTime, NeedToAccelerate); Navigator.MoveForward(isKeyDown('W'), isKeyDown('S'), DeltaTime, NeedToAccelerate); Navigator.StrafeHorizontal(isKeyDown('D'), isKeyDown('A'), DeltaTime, NeedToAccelerate); // GetCursorPos(RealPos); UI.MouseLook({RealPos, }DeltaTime); // if UI.MouseLookActive then // SetCursorPos(Round(UI.OriginalMousePos.X), Round(UI.OriginalMousePos.Y)); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: Double); begin GLSceneViewer1.Invalidate; if UI.MouseLookActive then CheckControls(DeltaTime, newtime) else begin if (ssRight in ShiftState) and (ssLeft in ShiftState) then begin Navigator.MoveAroundTarget(0, 0, DelTaTime); Navigator.AdjustDistanceToTarget(yy - NewYY, DelTaTime) end else if (ssRight in ShiftState) or (ssLeft in ShiftState) then begin Navigator.MoveAroundTarget(yy - NewYY, xx - NewXX, DelTaTime); Navigator.AdjustDistanceToTarget(0, DelTaTime); end else begin Navigator.MoveAroundTarget(0, 0, DelTaTime); Navigator.AdjustDistanceToTarget(0, DelTaTime); end; xx := NewXX; yy := NewYY; end; end; procedure TForm1.FPSTimerTimer(Sender: TObject); begin Caption := 'Smooth Navigator - ' + GLSceneViewer1.FramesPerSecondText; Navigator.AutoScaleParameters(GLSceneViewer1.FramesPerSecond); GLSceneViewer1.ResetPerformanceMonitor; end; procedure TForm1.MouseLookCheckBoxClick(Sender: TObject); begin if MouseLookCheckBox.Checked then begin GLCamera1.TargetObject := nil; GLCamera1.PointTo(GLArrowLine1, YHmgVector); UI.MouseLookActive := True; // GetCursorPos(RealPos); // UI.OriginalMousePos.SetPoint2D(RealPos.X, RealPos.Y); // ShowCursor(False); end else begin UI.MouseLookActive := False; // ShowCursor(True); GLCamera1.Up.SetVector(0, 1, 0); GLCamera1.TargetObject := GLArrowLine1; end; end; procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin if Key = Char(VK_SPACE) then MouseLookCheckBoxClick(Self); if Key = Char(VK_ESCAPE) then Close; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin GLSceneViewer1.Enabled := False; GLCadencer1.Enabled := False; FPSTimer.Enabled := False; FreeAndNil(UI); FreeAndNil(Navigator); GLShowCursor(True); end; procedure TForm1.RadioButton6Click(Sender: TObject); begin GLCadencer1.FixedDeltaTime := 0; end; procedure TForm1.RadioButton7Click(Sender: TObject); begin GLCadencer1.FixedDeltaTime := 0.01; end; procedure TForm1.RadioButton8Click(Sender: TObject); begin GLCadencer1.FixedDeltaTime := 0.1; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin ShiftState := Shift; NewXX := X; NewYY := Y; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin xx := x; yy := y; end; procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean); begin // (WheelDelta / Abs(WheelDelta) is used to deternime the sign. Navigator.AdjustDistanceParams.AddImpulse((WheelDelta / Abs(WheelDelta))); end; end.
unit FrmDivisiones01; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls; type TFormDivisiones01 = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; cbProvincia: TComboBoxEx; cbCanton: TComboBoxEx; cbDistrito: TComboBoxEx; cbBarrio: TComboBoxEx; btnCerrar: TBitBtn; edtResultado: TEdit; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCerrarClick(Sender: TObject); procedure cbProvinciaChange(Sender: TObject); procedure cbCantonChange(Sender: TObject); procedure cbDistritoChange(Sender: TObject); procedure cbBarrioChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormDivisiones01: TFormDivisiones01; procedure InicializarForma; procedure FinalizarForma; procedure KeyDownForma(var Key: Word; Shift: TShiftState); procedure LimpiarCampos; procedure Cerrar; procedure LlenarProvincia(cb: TComboBoxEx); procedure LlenarCanton(cb: TComboBoxEx; mIdProvincia: Integer); procedure LlenarDistrito(cb: TComboBoxEx; mIdProvincia: Integer; mIdCanton: Integer); procedure LlenarBarrio(cb: TComboBoxEx; mIdProvincia: Integer; mIdCanton: Integer; mIdDistrito: Integer); function Obtener_Resultado: string; implementation uses uDL_tb_Provincias, uDL_tb_Cantones, uDL_tb_Distritos, uDL_tb_Barrios, uSistema, ufunciones; {$R *.dfm} var Forma01: TFormDivisiones01; mPasaForma: Boolean; {$REGION 'Funciones Forma'} procedure TFormDivisiones01.FormShow(Sender: TObject); begin mPasaForma := False; Forma01 := FormDivisiones01; InicializarForma; end; procedure TFormDivisiones01.FormClose(Sender: TObject; var Action: TCloseAction); begin FinalizarForma; end; procedure TFormDivisiones01.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin KeyDownForma(Key, Shift); end; procedure TFormDivisiones01.btnCerrarClick(Sender: TObject); begin Cerrar; end; procedure TFormDivisiones01.cbProvinciaChange(Sender: TObject); begin if mPasaForma = True then begin mPasaForma := False; LlenarCanton(cbCanton, GetCombo(cbProvincia)); LlenarDistrito(cbDistrito, GetCombo(cbProvincia), GetCombo(cbCanton)); LlenarBarrio(cbBarrio, GetCombo(cbProvincia), GetCombo(cbCanton), GetCombo(cbDistrito)); cbCanton.ItemIndex := 0; cbDistrito.ItemIndex := 0; cbBarrio.ItemIndex := 0; edtResultado.Text := Obtener_Resultado; mPasaForma := True; end; end; procedure TFormDivisiones01.cbCantonChange(Sender: TObject); begin if mPasaForma = True then begin mPasaForma := False; LlenarDistrito(cbDistrito, GetCombo(cbProvincia), GetCombo(cbCanton)); LlenarBarrio(cbBarrio, GetCombo(cbProvincia), GetCombo(cbCanton), GetCombo(cbDistrito)); cbDistrito.ItemIndex := 0; cbBarrio.ItemIndex := 0; edtResultado.Text := Obtener_Resultado; mPasaForma := True; end; end; procedure TFormDivisiones01.cbDistritoChange(Sender: TObject); begin if mPasaForma = True then begin mPasaForma := False; LlenarBarrio(cbBarrio, GetCombo(cbProvincia), GetCombo(cbCanton), GetCombo(cbDistrito)); cbBarrio.ItemIndex := 0; edtResultado.Text := Obtener_Resultado; mPasaForma := True; end; end; procedure TFormDivisiones01.cbBarrioChange(Sender: TObject); begin if mPasaForma = True then begin mPasaForma := False; edtResultado.Text := Obtener_Resultado; mPasaForma := True; end; end; {$ENDREGION} {$REGION 'Funciones Generales'} procedure InicializarForma; begin with Forma01 do begin try Tag := 0; LlenarProvincia(cbProvincia); if _Resultado = -1 then raise Exception.Create(''); LlenarCanton(cbCanton, 0); if _Resultado = -1 then raise Exception.Create(''); LlenarDistrito(cbDistrito, 0, 0); if _Resultado = -1 then raise Exception.Create(''); LlenarBarrio(cbBarrio, 0, 0, 0); if _Resultado = -1 then raise Exception.Create(''); LimpiarCampos; mPasaForma := True; except end; end; end; procedure FinalizarForma; begin with Forma01 do begin try except end; end; end; procedure KeyDownForma(var Key: Word; Shift: TShiftState); begin with Forma01 do begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; end; procedure LimpiarCampos; begin with Forma01 do begin cbProvincia.ItemIndex := 0; cbCanton.ItemIndex := 0; cbDistrito.ItemIndex := 0; cbBarrio.ItemIndex := 0; edtResultado.Clear; end; end; procedure Cerrar; begin with Forma01 do begin Close; end; end; procedure LlenarProvincia(cb: TComboBoxEx); var mtb_Provincias: TDL_tb_Provincias; mWhere: TStringList; begin with Forma01 do begin try _Resultado := 1; cb.Items.Clear; cb.Items.AddObject('[SIN SELECCIONAR]', TObject(0)); mWhere := TStringList.Create; mtb_Provincias := TDL_tb_Provincias.Create; mtb_Provincias.Consultar(_Resultado, _ErrorM, mWhere.Text); mWhere.Free; if _Resultado = -1 then raise Exception.Create(''); with mtb_Provincias.Dataset do begin First; while not Eof do begin cb.Items.AddObject(FieldByName('Codigo').AsString + ' ' + FieldByName('Nombre').AsString, TObject(FieldByName('Id').AsInteger)); Next; end; end; mtb_Provincias.Destroy; _Resultado := 1; except _Resultado := -1; end; end; end; procedure LlenarCanton(cb: TComboBoxEx; mIdProvincia: Integer); var mtb_Cantones: TDL_tb_Cantones; mWhere: TStringList; begin with Forma01 do begin try _Resultado := 1; cb.Items.Clear; cb.Items.AddObject('[SIN SELECCIONAR]', TObject(0)); mWhere := TStringList.Create; mWhere.Add('CodigoProvincia = ' + IntToStr(mIdProvincia)); mtb_Cantones := TDL_tb_Cantones.Create; mtb_Cantones.Consultar(_Resultado, _ErrorM, mWhere.Text); mWhere.Free; if _Resultado = -1 then raise Exception.Create(''); with mtb_Cantones.Dataset do begin First; while not Eof do begin cb.Items.AddObject(FieldByName('Codigo').AsString + ' ' + FieldByName('Nombre').AsString, TObject(FieldByName('Id').AsInteger)); Next; end; end; mtb_Cantones.Destroy; _Resultado := 1; except _Resultado := -1; end; end; end; procedure LlenarDistrito(cb: TComboBoxEx; mIdProvincia: Integer; mIdCanton: Integer); var mtb_Distritos: TDL_tb_Distritos; mWhere: TStringList; begin with Forma01 do begin try _Resultado := 1; cb.Items.Clear; cb.Items.AddObject('[SIN SELECCIONAR]', TObject(0)); mWhere := TStringList.Create; mWhere.Add('CodigoProvincia = ' + IntToStr(mIdProvincia)); mWhere.Add(' And '); mWhere.Add('CodigoCanton = ' + IntToStr(mIdCanton)); mtb_Distritos := TDL_tb_Distritos.Create; mtb_Distritos.Consultar(_Resultado, _ErrorM, mWhere.Text); mWhere.Free; if _Resultado = -1 then raise Exception.Create(''); with mtb_Distritos.Dataset do begin First; while not Eof do begin cb.Items.AddObject(FieldByName('Codigo').AsString + ' ' + FieldByName('Nombre').AsString, TObject(FieldByName('Id').AsInteger)); Next; end; end; mtb_Distritos.Destroy; _Resultado := 1; except _Resultado := -1; end; end; end; procedure LlenarBarrio(cb: TComboBoxEx; mIdProvincia: Integer; mIdCanton: Integer; mIdDistrito: Integer); var mtb_Barrios: TDL_tb_Barrios; mWhere: TStringList; begin with Forma01 do begin try _Resultado := 1; cb.Items.Clear; cb.Items.AddObject('[SIN SELECCIONAR]', TObject(0)); mWhere := TStringList.Create; mWhere.Add('CodigoProvincia = ' + IntToStr(mIdProvincia)); mWhere.Add(' And '); mWhere.Add('CodigoCanton = ' + IntToStr(mIdCanton)); mWhere.Add(' And '); mWhere.Add('CodigoDistrito = ' + IntToStr(mIdDistrito)); mtb_Barrios := TDL_tb_Barrios.Create; mtb_Barrios.Consultar(_Resultado, _ErrorM, mWhere.Text); mWhere.Free; if _Resultado = -1 then raise Exception.Create(''); with mtb_Barrios.Dataset do begin First; while not Eof do begin cb.Items.AddObject(FieldByName('Codigo').AsString + ' ' + FieldByName('Nombre').AsString, TObject(FieldByName('Id').AsInteger)); Next; end; end; mtb_Barrios.Destroy; _Resultado := 1; except _Resultado := -1; end; end; end; function Obtener_Resultado: string; var mWhere: TStringList; mIdProvincia, mIdCanton, mIdDistrito, mIdBarrio: Integer; mtb_Provincias: TDL_tb_Provincias; mtb_Cantones: TDL_tb_Cantones; mtb_Distritos: TDL_tb_Distritos; mtb_Barrios: TDL_tb_Barrios; mCodigoProvincia, mCodigoCanton, mCodigoDistrito, mCodigoBarrio: string; mResultado: string; begin with Forma01 do begin try _Resultado := 1; mResultado := ''; mIdProvincia := GetCombo(cbProvincia); mIdCanton := GetCombo(cbCanton); mIdDistrito := GetCombo(cbDistrito); mIdBarrio := GetCombo(cbBarrio); mtb_Provincias := TDL_tb_Provincias.Create; mCodigoProvincia := mtb_Provincias.Obtener_Valor('Id=' + IntToStr(mIdProvincia), 'Codigo', _Resultado, _ErrorM); mtb_Provincias.Destroy; mtb_Cantones := TDL_tb_Cantones.Create; mCodigoCanton := mtb_Cantones.Obtener_Valor('Id=' + IntToStr(mIdCanton), 'Codigo', _Resultado, _ErrorM); if _Resultado = -1 then raise Exception.Create(''); mtb_Cantones.Destroy; mtb_Distritos := TDL_tb_Distritos.Create; mCodigoDistrito := mtb_Distritos.Obtener_Valor('Id=' + IntToStr(mIdDistrito), 'Codigo', _Resultado, _ErrorM); if _Resultado = -1 then raise Exception.Create(''); mtb_Distritos.Destroy; mtb_Barrios := TDL_tb_Barrios.Create; mCodigoBarrio := mtb_Barrios.Obtener_Valor('Id=' + IntToStr(mIdBarrio), 'Codigo', _Resultado, _ErrorM); mtb_Barrios.Destroy; _Resultado := 1; except _Resultado := -1; end; mResultado := mCodigoProvincia + ';' + mCodigoCanton + ';' + mCodigoDistrito + ';' + mCodigoBarrio; Result := mResultado; end; end; {$ENDREGION} end.
unit ATipoChamado; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, BotaoCadastro, StdCtrls, Buttons, Db, DBTables, Tabela, CBancoDados, Grids, DBGrids, DBKeyViolation, Localizacao, Mask, DBCtrls, DBClient; type TFTipoChamado = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; MoveBasico1: TMoveBasico; BotaoCadastrar1: TBotaoCadastrar; BotaoAlterar1: TBotaoAlterar; BotaoExcluir1: TBotaoExcluir; BotaoGravar1: TBotaoGravar; BotaoCancelar1: TBotaoCancelar; BFechar: TBitBtn; TipoChamado: TRBSQL; DataTipoChamado: TDataSource; TipoChamadoCODTIPOCHAMADO: TFMTBCDField; TipoChamadoNOMTIPOCHAMADO: TWideStringField; ECodigo: TDBKeyViolation; DBEditColor1: TDBEditColor; Label1: TLabel; Label2: TLabel; Label3: TLabel; Bevel1: TBevel; EConsulta: TLocalizaEdit; Grade: TGridIndice; Label4: TLabel; EModeloEmail: TComboBoxColor; TipoChamadoNUMMODELOEMAIL: TFMTBCDField; TipoChamadoINDGARANTIA: TWideStringField; DBCheckBox1: TDBCheckBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure TipoChamadoAfterEdit(DataSet: TDataSet); procedure TipoChamadoAfterInsert(DataSet: TDataSet); procedure TipoChamadoAfterPost(DataSet: TDataSet); procedure TipoChamadoBeforePost(DataSet: TDataSet); procedure TipoChamadoAfterScroll(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var FTipoChamado: TFTipoChamado; implementation uses APrincipal, FunObjeto; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFTipoChamado.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } EConsulta.AtualizaConsulta; InicializaVerdadeiroeFalsoCheckBox(PanelColor2,'S','N'); end; { ******************* Quando o formulario e fechado ************************** } procedure TFTipoChamado.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } TipoChamado.close; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFTipoChamado.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFTipoChamado.TipoChamadoAfterEdit(DataSet: TDataSet); begin ECodigo.readonly := true; EModeloEmail.Enabled := true; end; {******************************************************************************} procedure TFTipoChamado.TipoChamadoAfterInsert(DataSet: TDataSet); begin ECodigo.ReadOnly := false; ECodigo.ProximoCodigo; EModeloEmail.Enabled := true; TipoChamadoINDGARANTIA.AsString := 'N'; end; {******************************************************************************} procedure TFTipoChamado.TipoChamadoAfterPost(DataSet: TDataSet); begin EConsulta.AtualizaConsulta; end; {******************************************************************************} procedure TFTipoChamado.TipoChamadoBeforePost(DataSet: TDataSet); begin if TipoChamado.State = dsinsert then ECodigo.VerificaCodigoUtilizado; TIPOCHAMADONUMMODELOEMAIL.AsInteger := EModeloEmail.ItemIndex; end; {******************************************************************************} procedure TFTipoChamado.TipoChamadoAfterScroll(DataSet: TDataSet); begin EModeloEmail.Enabled := false; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFTipoChamado]); end.